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
b3d8cdfa7bc26c59b6f2a9329cf816d53af541f0
src/natools-web-containers.adb
src/natools-web-containers.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Printers; with Natools.Time_IO.RFC_3339; package body Natools.Web.Containers is procedure Add_Atom (List : in out Unsafe_Atom_Lists.List; Context : in Meaningless_Type; Atom : in S_Expressions.Atom); -- Append a new atom to List procedure Add_Date (Map : in out Date_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class); -- Append a new named date to Map procedure Add_Expression (Map : in out Expression_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class); -- Insert a new node (Name -> Cache (Value)) in Map procedure Add_Expression_Map (Map : in out Expression_Map_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class); -- Insert a new node (Name -> Expression_Map (Value)) in Map procedure Date_Reader is new S_Expressions.Interpreter_Loop (Date_Maps.Unsafe_Maps.Map, Meaningless_Type, Add_Date); procedure List_Reader is new S_Expressions.Interpreter_Loop (Unsafe_Atom_Lists.List, Meaningless_Type, Dispatch_Without_Argument => Add_Atom); procedure Map_Map_Reader is new S_Expressions.Interpreter_Loop (Expression_Map_Maps.Unsafe_Maps.Map, Meaningless_Type, Add_Expression_Map); procedure Map_Reader is new S_Expressions.Interpreter_Loop (Expression_Maps.Unsafe_Maps.Map, Meaningless_Type, Add_Expression); ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Add_Atom (List : in out Unsafe_Atom_Lists.List; Context : in Meaningless_Type; Atom : in S_Expressions.Atom) is pragma Unreferenced (Context); begin List.Append (Atom); end Add_Atom; procedure Add_Date (Map : in out Date_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); use type S_Expressions.Events.Event; Item : Date; begin if Value.Current_Event = S_Expressions.Events.Add_Atom then declare Image : constant String := S_Expressions.To_String (Value.Current_Atom); begin if Time_IO.RFC_3339.Is_Valid (Image) then Time_IO.RFC_3339.Value (Image, Item.Time, Item.Offset); Map.Include (Name, Item); else Log (Severities.Warning, "Ignoring invalid date named """ & S_Expressions.To_String (Name) & '"'); end if; end; else Map.Exclude (Name); end if; end Add_Date; procedure Add_Expression (Map : in out Expression_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); Expression : S_Expressions.Caches.Reference; begin S_Expressions.Printers.Transfer (Value, Expression); Map.Include (Name, Expression.First); end Add_Expression; procedure Add_Expression_Map (Map : in out Expression_Map_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); Expression_Map : Expression_Maps.Constant_Map; begin if Map.Contains (Name) then Log (Severities.Error, "Duplicate name """ & S_Expressions.To_String (Name) & """ in expression map map"); return; end if; Set_Expressions (Expression_Map, Value); Map.Insert (Name, Expression_Map); end Add_Expression_Map; -------------------- -- Map Interfaces -- -------------------- procedure Set_Dates (Map : in out Date_Maps.Constant_Map; Date_List : in out S_Expressions.Lockable.Descriptor'Class) is New_Map : Date_Maps.Unsafe_Maps.Map; begin Date_Reader (Date_List, New_Map, Meaningless_Value); Map.Replace (New_Map); end Set_Dates; procedure Set_Expressions (Map : in out Expression_Maps.Constant_Map; Expression_List : in out S_Expressions.Lockable.Descriptor'Class) is New_Map : Expression_Maps.Unsafe_Maps.Map; begin Map_Reader (Expression_List, New_Map, Meaningless_Value); Map.Replace (New_Map); end Set_Expressions; procedure Set_Expression_Maps (Map : in out Expression_Map_Maps.Constant_Map; Expression_Map_List : in out S_Expressions.Lockable.Descriptor'Class) is New_Map : Expression_Map_Maps.Unsafe_Maps.Map; begin Map_Map_Reader (Expression_Map_List, New_Map, Meaningless_Value); Map.Replace (New_Map); end Set_Expression_Maps; --------------------------- -- Atom Arrays Interface -- --------------------------- procedure Append_Atoms (Target : in out Unsafe_Atom_Lists.List; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin List_Reader (Expression, Target, Meaningless_Value); end Append_Atoms; function Create (Source : Unsafe_Atom_Lists.List) return Atom_Array_Refs.Immutable_Reference is function Create_Array return Atom_Array; function Create_Array return Atom_Array is Cursor : Unsafe_Atom_Lists.Cursor := Source.First; Result : Atom_Array (1 .. S_Expressions.Count (Source.Length)); begin for I in Result'Range loop Result (I) := S_Expressions.Atom_Ref_Constructors.Create (Unsafe_Atom_Lists.Element (Cursor)); Unsafe_Atom_Lists.Next (Cursor); end loop; return Result; end Create_Array; begin return Atom_Array_Refs.Create (Create_Array'Access); end Create; function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Array_Refs.Immutable_Reference is List : Unsafe_Atom_Lists.List; begin Append_Atoms (List, Expression); return Create (List); end Create; -------------------------- -- Atom Table Interface -- -------------------------- function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Table_Refs.Immutable_Reference is List : Atom_Row_Lists.List; Event : S_Expressions.Events.Event := Expression.Current_Event; Lock : S_Expressions.Lockable.Lock_State; begin Read_Expression : loop case Event is when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => exit Read_Expression; when S_Expressions.Events.Add_Atom => null; when S_Expressions.Events.Open_List => Expression.Lock (Lock); begin Expression.Next (Event); if Event in S_Expressions.Events.Add_Atom | S_Expressions.Events.Open_List then List.Append (Create (Expression)); end if; Expression.Unlock (Lock); exception when others => Expression.Unlock (Lock, False); raise; end; end case; Expression.Next (Event); end loop Read_Expression; return Create (List); end Create; function Create (Row_List : in Atom_Row_Lists.List) return Atom_Table_Refs.Immutable_Reference is begin if Atom_Row_Lists.Is_Empty (Row_List) then return Atom_Table_Refs.Null_Immutable_Reference; end if; Build_Table : declare Data : constant Atom_Table_Refs.Data_Access := new Atom_Table (1 .. S_Expressions.Count (Atom_Row_Lists.Length (Row_List))); Ref : constant Atom_Table_Refs.Immutable_Reference := Atom_Table_Refs.Create (Data); Cursor : Atom_Row_Lists.Cursor := Atom_Row_Lists.First (Row_List); begin for I in Data.all'Range loop Data (I) := Atom_Row_Lists.Element (Cursor); Atom_Row_Lists.Next (Cursor); end loop; pragma Assert (not Atom_Row_Lists.Has_Element (Cursor)); return Ref; end Build_Table; end Create; end Natools.Web.Containers;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Printers; with Natools.Time_IO.RFC_3339; package body Natools.Web.Containers is procedure Add_Atom (List : in out Unsafe_Atom_Lists.List; Context : in Meaningless_Type; Atom : in S_Expressions.Atom); -- Append a new atom to List procedure Add_Date (Map : in out Date_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class); -- Append a new named date to Map procedure Add_Expression (Map : in out Expression_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class); -- Insert a new node (Name -> Cache (Value)) in Map procedure Add_Expression_Map (Map : in out Expression_Map_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class); -- Insert a new node (Name -> Expression_Map (Value)) in Map procedure Date_Reader is new S_Expressions.Interpreter_Loop (Date_Maps.Unsafe_Maps.Map, Meaningless_Type, Add_Date); procedure List_Reader is new S_Expressions.Interpreter_Loop (Unsafe_Atom_Lists.List, Meaningless_Type, Dispatch_Without_Argument => Add_Atom); procedure Map_Map_Reader is new S_Expressions.Interpreter_Loop (Expression_Map_Maps.Unsafe_Maps.Map, Meaningless_Type, Add_Expression_Map); procedure Map_Reader is new S_Expressions.Interpreter_Loop (Expression_Maps.Unsafe_Maps.Map, Meaningless_Type, Add_Expression); ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Add_Atom (List : in out Unsafe_Atom_Lists.List; Context : in Meaningless_Type; Atom : in S_Expressions.Atom) is pragma Unreferenced (Context); begin List.Append (Atom); end Add_Atom; procedure Add_Date (Map : in out Date_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); use type S_Expressions.Events.Event; Item : Date; begin if Value.Current_Event = S_Expressions.Events.Add_Atom then declare Image : constant String := S_Expressions.To_String (Value.Current_Atom); begin if Time_IO.RFC_3339.Is_Valid (Image) then Time_IO.RFC_3339.Value (Image, Item.Time, Item.Offset); Map.Include (Name, Item); else Log (Severities.Warning, "Ignoring invalid date named """ & S_Expressions.To_String (Name) & '"'); end if; end; else Map.Exclude (Name); end if; end Add_Date; procedure Add_Expression (Map : in out Expression_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); Expression : S_Expressions.Caches.Reference; begin S_Expressions.Printers.Transfer (Value, Expression); Map.Include (Name, Expression.First); end Add_Expression; procedure Add_Expression_Map (Map : in out Expression_Map_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Value : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); Expression_Map : Expression_Maps.Constant_Map; begin if Map.Contains (Name) then Log (Severities.Error, "Duplicate name """ & S_Expressions.To_String (Name) & """ in expression map map"); return; end if; Set_Expressions (Expression_Map, Value); Map.Insert (Name, Expression_Map); end Add_Expression_Map; -------------------- -- Map Interfaces -- -------------------- procedure Set_Dates (Map : in out Date_Maps.Constant_Map; Date_List : in out S_Expressions.Lockable.Descriptor'Class) is New_Map : Date_Maps.Unsafe_Maps.Map; begin Date_Reader (Date_List, New_Map, Meaningless_Value); Map.Replace (New_Map); end Set_Dates; procedure Set_Expressions (Map : in out Expression_Maps.Constant_Map; Expression_List : in out S_Expressions.Lockable.Descriptor'Class) is New_Map : Expression_Maps.Unsafe_Maps.Map; begin Map_Reader (Expression_List, New_Map, Meaningless_Value); Map.Replace (New_Map); end Set_Expressions; procedure Set_Expression_Maps (Map : in out Expression_Map_Maps.Constant_Map; Expression_Map_List : in out S_Expressions.Lockable.Descriptor'Class) is New_Map : Expression_Map_Maps.Unsafe_Maps.Map; begin Map_Map_Reader (Expression_Map_List, New_Map, Meaningless_Value); Map.Replace (New_Map); end Set_Expression_Maps; --------------------------- -- Atom Arrays Interface -- --------------------------- procedure Append_Atoms (Target : in out Unsafe_Atom_Lists.List; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin List_Reader (Expression, Target, Meaningless_Value); end Append_Atoms; function Create (Source : Unsafe_Atom_Lists.List) return Atom_Array_Refs.Immutable_Reference is function Create_Array return Atom_Array; function Create_Array return Atom_Array is Cursor : Unsafe_Atom_Lists.Cursor := Source.First; Result : Atom_Array (1 .. S_Expressions.Count (Source.Length)); begin for I in Result'Range loop Result (I) := S_Expressions.Atom_Ref_Constructors.Create (Unsafe_Atom_Lists.Element (Cursor)); Unsafe_Atom_Lists.Next (Cursor); end loop; return Result; end Create_Array; begin return Atom_Array_Refs.Create (Create_Array'Access); end Create; function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Array_Refs.Immutable_Reference is List : Unsafe_Atom_Lists.List; begin Append_Atoms (List, Expression); return Create (List); end Create; -------------------------- -- Atom Table Interface -- -------------------------- function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Table_Refs.Immutable_Reference is List : Atom_Row_Lists.List; Event : S_Expressions.Events.Event := Expression.Current_Event; Lock : S_Expressions.Lockable.Lock_State; begin Read_Expression : loop case Event is when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => exit Read_Expression; when S_Expressions.Events.Add_Atom => null; when S_Expressions.Events.Open_List => Expression.Lock (Lock); begin Expression.Next (Event); if Event in S_Expressions.Events.Add_Atom | S_Expressions.Events.Open_List then List.Append (Create (Expression)); end if; Expression.Unlock (Lock); exception when others => Expression.Unlock (Lock, False); raise; end; end case; Expression.Next (Event); end loop Read_Expression; return Create (List); end Create; function Create (Row_List : in Atom_Row_Lists.List) return Atom_Table_Refs.Immutable_Reference is begin Build_Table : declare Data : constant Atom_Table_Refs.Data_Access := new Atom_Table (1 .. S_Expressions.Count (Atom_Row_Lists.Length (Row_List))); Ref : constant Atom_Table_Refs.Immutable_Reference := Atom_Table_Refs.Create (Data); Cursor : Atom_Row_Lists.Cursor := Atom_Row_Lists.First (Row_List); begin for I in Data.all'Range loop Data (I) := Atom_Row_Lists.Element (Cursor); Atom_Row_Lists.Next (Cursor); end loop; pragma Assert (not Atom_Row_Lists.Has_Element (Cursor)); return Ref; end Build_Table; end Create; end Natools.Web.Containers;
create non-empty reference when the list is empty
containers: create non-empty reference when the list is empty
Ada
isc
faelys/natools-web,faelys/natools-web
fe2625dbad32b7a3f61863a19a0628de66f2e8c1
regtests/util-log-tests.adb
regtests/util-log-tests.adb
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Directories; with Ada.Text_IO; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Log; with Util.Log.Loggers; with Util.Files; with Util.Properties; with Util.Measures; package body Util.Log.Tests is Log : constant Loggers.Logger := Loggers.Create ("util.log.test"); procedure Test_Log (T : in out Test) is pragma Unreferenced (T); L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin L.Set_Level (DEBUG_LEVEL); Log.Info ("My log message"); Log.Error ("My error message"); Log.Debug ("A debug message Not printed"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); end Test_Log; -- Test configuration and creation of file procedure Test_File_Appender (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); end; end Test_File_Appender; procedure Test_Log_Perf (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); for I in 1 .. 1000 loop declare S : Util.Measures.Stamp; begin Util.Measures.Report (S, "Util.Measures.Report", 1000); end; end loop; declare L : Loggers.Logger := Loggers.Create ("util.log.test.perf"); S : Util.Measures.Stamp; begin L.Set_Level (DEBUG_LEVEL); for I in 1 .. 1000 loop L.Info ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Info message (output)", 1000); L.Set_Level (INFO_LEVEL); for I in 1 .. 10_000 loop L.Debug ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Debug message (no output)", 10_000); end; end Test_Log_Perf; -- ------------------------------ -- Test appending the log on several log files -- ------------------------------ procedure Test_List_Appender (T : in out Test) is use Ada.Strings; use Ada.Directories; Props : Util.Properties.Manager; begin for I in 1 .. 10 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Name : constant String := "log4j.appender.test" & Id; begin Props.Set (Name, "File"); Props.Set (Name & ".File", "test" & Id & ".log"); Props.Set (Name & ".layout", "date-level-message"); if I > 5 then Props.Set (Name & ".level", "INFO"); end if; end; end loop; Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); end; -- Check that we have non empty log files (up to test8.log). for I in 1 .. 8 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := "test" & Id & ".log"; begin T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); if I > 5 then T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty"); else T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty"); end if; end; end loop; end Test_List_Appender; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_File_Appender_Modes (T : in out Test) is use Ada.Directories; Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test-append.log"); Props.Set ("log4j.appender.test.append", "true"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.appender.test_global", "File"); Props.Set ("log4j.appender.test_global.File", "test-append-global.log"); Props.Set ("log4j.appender.test_global.append", "false"); Props.Set ("log4j.appender.test_global.immediateFlush", "false"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG"); Props.Set ("log4j.rootCategory", "DEBUG,test_global,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Error ("This is the error test message"); end; Props.Set ("log4j.appender.test_append", "File"); Props.Set ("log4j.appender.test_append.File", "test-append2.log"); Props.Set ("log4j.appender.test_append.append", "true"); Props.Set ("log4j.appender.test_append.immediateFlush", "true"); Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global"); Util.Log.Loggers.Initialize (Props); declare L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file"); begin L1.Info ("L1-1 Writing a info message"); L2.Info ("L2-2 {0}: {1}", "Parameter", "Value"); L1.Info ("L1-3 Done"); L2.Error ("L2-4 This is the error test2 message"); end; Props.Set ("log4j.appender.test_append.append", "plop"); Props.Set ("log4j.appender.test_append.immediateFlush", "falsex"); Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Util.Log.Loggers.Initialize (Props); T.Assert (Ada.Directories.Size ("test-append.log") > 100, "Log file test-append.log is empty"); T.Assert (Ada.Directories.Size ("test-append2.log") > 100, "Log file test-append2.log is empty"); T.Assert (Ada.Directories.Size ("test-append-global.log") > 100, "Log file test-append.log is empty"); end Test_File_Appender_Modes; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_Console_Appender (T : in out Test) is Props : Util.Properties.Manager; File : Ada.Text_IO.File_Type; Content : Ada.Strings.Unbounded.Unbounded_String; begin Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, "test_err.log"); Ada.Text_IO.Set_Error (File); Props.Set ("log4j.appender.test_console", "Console"); Props.Set ("log4j.appender.test_console.stderr", "true"); Props.Set ("log4j.appender.test_console.level", "WARN"); Props.Set ("log4j.rootCategory", "INFO,test_console"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Info ("INFO MESSAGE!"); L.Warn ("WARN MESSAGE!"); L.Error ("This {0} {1} {2} test message", "is", "the", "error"); end; Ada.Text_IO.Flush (Ada.Text_IO.Current_Error); Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); Ada.Text_IO.Close (File); Util.Files.Read_File ("test_err.log", Content); Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content, "Invalid console log (WARN)"); Util.Tests.Assert_Matches (T, ".*This is the error test message", Content, "Invalid console log (ERROR)"); exception when others => Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); raise; end Test_Console_Appender; procedure Test_Missing_Config (T : in out Test) is L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin Util.Log.Loggers.Initialize ("plop"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); end Test_Missing_Config; procedure Test_Log_Traceback (T : in out Test) is Props : Util.Properties.Manager; Content : Ada.Strings.Unbounded.Unbounded_String; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test-traceback.log"); Props.Set ("log4j.appender.test.append", "false"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.rootCategory", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Error ("This is the error test message"); raise Constraint_Error with "Test"; exception when E : others => L.Error ("Something wrong", E, True); end; Props.Set ("log4j.rootCategory", "DEBUG,console"); Props.Set ("log4j.appender.console", "Console"); Util.Log.Loggers.Initialize (Props); Util.Files.Read_File ("test-traceback.log", Content); Util.Tests.Assert_Matches (T, ".*Something wrong: Exception CONSTRAINT_ERROR:", Content, "Invalid console log (ERROR)"); end Test_Log_Traceback; package Caller is new Util.Test_Caller (Test, "Log"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Error", Test_Log_Traceback'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize", Test_Missing_Config'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender", Test_File_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)", Test_File_Appender_Modes'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender", Test_List_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console", Test_Console_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)", Test_Log_Perf'Access); end Add_Tests; end Util.Log.Tests;
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Directories; with Ada.Text_IO; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Log; with Util.Log.Loggers; with Util.Files; with Util.Properties; with Util.Measures; package body Util.Log.Tests is Log : constant Loggers.Logger := Loggers.Create ("util.log.test"); procedure Test_Log (T : in out Test) is L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin L.Set_Level (DEBUG_LEVEL); Log.Info ("My log message"); Log.Error ("My error message"); Log.Debug ("A debug message Not printed"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name, "Get_Level_Name function is invalid"); end Test_Log; -- Test configuration and creation of file procedure Test_File_Appender (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); end; end Test_File_Appender; procedure Test_Log_Perf (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); for I in 1 .. 1000 loop declare S : Util.Measures.Stamp; begin Util.Measures.Report (S, "Util.Measures.Report", 1000); end; end loop; declare L : Loggers.Logger := Loggers.Create ("util.log.test.perf"); S : Util.Measures.Stamp; begin L.Set_Level (DEBUG_LEVEL); for I in 1 .. 1000 loop L.Info ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Info message (output)", 1000); L.Set_Level (INFO_LEVEL); for I in 1 .. 10_000 loop L.Debug ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Debug message (no output)", 10_000); end; end Test_Log_Perf; -- ------------------------------ -- Test appending the log on several log files -- ------------------------------ procedure Test_List_Appender (T : in out Test) is use Ada.Strings; use Ada.Directories; Props : Util.Properties.Manager; begin for I in 1 .. 10 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Name : constant String := "log4j.appender.test" & Id; begin Props.Set (Name, "File"); Props.Set (Name & ".File", "test" & Id & ".log"); Props.Set (Name & ".layout", "date-level-message"); if I > 5 then Props.Set (Name & ".level", "INFO"); end if; end; end loop; Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); end; -- Check that we have non empty log files (up to test8.log). for I in 1 .. 8 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := "test" & Id & ".log"; begin T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); if I > 5 then T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty"); else T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty"); end if; end; end loop; end Test_List_Appender; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_File_Appender_Modes (T : in out Test) is use Ada.Directories; Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test-append.log"); Props.Set ("log4j.appender.test.append", "true"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.appender.test_global", "File"); Props.Set ("log4j.appender.test_global.File", "test-append-global.log"); Props.Set ("log4j.appender.test_global.append", "false"); Props.Set ("log4j.appender.test_global.immediateFlush", "false"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG"); Props.Set ("log4j.rootCategory", "DEBUG,test_global,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Error ("This is the error test message"); end; Props.Set ("log4j.appender.test_append", "File"); Props.Set ("log4j.appender.test_append.File", "test-append2.log"); Props.Set ("log4j.appender.test_append.append", "true"); Props.Set ("log4j.appender.test_append.immediateFlush", "true"); Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global"); Util.Log.Loggers.Initialize (Props); declare L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file"); begin L1.Info ("L1-1 Writing a info message"); L2.Info ("L2-2 {0}: {1}", "Parameter", "Value"); L1.Info ("L1-3 Done"); L2.Error ("L2-4 This is the error test2 message"); end; Props.Set ("log4j.appender.test_append.append", "plop"); Props.Set ("log4j.appender.test_append.immediateFlush", "falsex"); Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Util.Log.Loggers.Initialize (Props); T.Assert (Ada.Directories.Size ("test-append.log") > 100, "Log file test-append.log is empty"); T.Assert (Ada.Directories.Size ("test-append2.log") > 100, "Log file test-append2.log is empty"); T.Assert (Ada.Directories.Size ("test-append-global.log") > 100, "Log file test-append.log is empty"); end Test_File_Appender_Modes; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_Console_Appender (T : in out Test) is Props : Util.Properties.Manager; File : Ada.Text_IO.File_Type; Content : Ada.Strings.Unbounded.Unbounded_String; begin Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, "test_err.log"); Ada.Text_IO.Set_Error (File); Props.Set ("log4j.appender.test_console", "Console"); Props.Set ("log4j.appender.test_console.stderr", "true"); Props.Set ("log4j.appender.test_console.level", "WARN"); Props.Set ("log4j.rootCategory", "INFO,test_console"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Info ("INFO MESSAGE!"); L.Warn ("WARN MESSAGE!"); L.Error ("This {0} {1} {2} test message", "is", "the", "error"); end; Ada.Text_IO.Flush (Ada.Text_IO.Current_Error); Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); Ada.Text_IO.Close (File); Util.Files.Read_File ("test_err.log", Content); Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content, "Invalid console log (WARN)"); Util.Tests.Assert_Matches (T, ".*This is the error test message", Content, "Invalid console log (ERROR)"); exception when others => Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); raise; end Test_Console_Appender; procedure Test_Missing_Config (T : in out Test) is L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin Util.Log.Loggers.Initialize ("plop"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); end Test_Missing_Config; procedure Test_Log_Traceback (T : in out Test) is Props : Util.Properties.Manager; Content : Ada.Strings.Unbounded.Unbounded_String; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test-traceback.log"); Props.Set ("log4j.appender.test.append", "false"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.rootCategory", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Error ("This is the error test message"); raise Constraint_Error with "Test"; exception when E : others => L.Error ("Something wrong", E, True); end; Props.Set ("log4j.rootCategory", "DEBUG,console"); Props.Set ("log4j.appender.console", "Console"); Util.Log.Loggers.Initialize (Props); Util.Files.Read_File ("test-traceback.log", Content); Util.Tests.Assert_Matches (T, ".*Something wrong: Exception CONSTRAINT_ERROR:", Content, "Invalid console log (ERROR)"); end Test_Log_Traceback; package Caller is new Util.Test_Caller (Test, "Log"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Error", Test_Log_Traceback'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize", Test_Missing_Config'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender", Test_File_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)", Test_File_Appender_Modes'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender", Test_List_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console", Test_Console_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)", Test_Log_Perf'Access); end Add_Tests; end Util.Log.Tests;
Update Test_Log to check the Get_Level_Name function
Update Test_Log to check the Get_Level_Name function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6b939771e4adacdc78db12998134b48349ea6f06
awa/plugins/awa-storages/src/awa-storages.ads
awa/plugins/awa-storages/src/awa-storages.ads
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A content in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in the file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- -- Data.Set_Storage (Storage => AWA.Storages.Models.DATABASE); -- -- To save a file in the store, we can use the `Save` operation. It will read the file -- and put in in the corresponding persistent store (the database in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier: -- -- Service.Load (From => Id, Into => Data); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- == Ada Beans == -- @include storages.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png] -- -- @include Storages.hbm.xml package AWA.Storages is end AWA.Storages;
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A content in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in the file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- -- Data.Set_Storage (Storage => AWA.Storages.Models.DATABASE); -- -- To save a file in the store, we can use the `Save` operation. It will read the file -- and put in in the corresponding persistent store (the database in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- === Local file === -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading locally we -- also indicate whether the file will be read or written. A file that is in `READ` mode -- can be shared by several tasks or processes. A file that is in `WRITE` mode will have -- a specific copy for the caller. An optional expiration parameter indicate when the -- local file representation can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- == Ada Beans == -- @include storages.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png] -- -- @include Storages.hbm.xml package AWA.Storages is end AWA.Storages;
Update the documentation of the storage module
Update the documentation of the storage module
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa
f6cb9b1e6d31dc302ff0b7435c467ae7259a21e8
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; package AWA.Wikis.Beans is type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Service : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; package AWA.Wikis.Beans is type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Service : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Service : Modules.Wiki_Module_Access := null; Wiki_Space : Wiki_Space_Bean; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
Declare the Wiki_Page_Bean type with the Get_Value, Set_Value, Save and Delete operations
Declare the Wiki_Page_Bean type with the Get_Value, Set_Value, Save and Delete operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ac12b99749838cd50da31a9e21f2c2779f8e7404
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers.URLs; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Perm : constant Security.Controllers.URLs.URL_Controller_Access := new Security.Controllers.URLs.URL_Controller; begin Perm.Manager := Policy'Unchecked_Access; Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Perm.Manager); Policy.Manager.Add_Permission (Name => "url", Permission => Perm.all'Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
Create the URL controller and register it when the URL policy configuration is read
Create the URL controller and register it when the URL policy configuration is read
Ada
apache-2.0
Letractively/ada-security
093d6cada50ea6c96f89309259dabafc2109f36e
src/wiki-filters-variables.adb
src/wiki-filters-variables.adb
----------------------------------------------------------------------- -- wiki-filters-variables -- Expand variables in text and links -- 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. ----------------------------------------------------------------------- package body Wiki.Filters.Variables is function Need_Expand (Text : in Wiki.Strings.WString) return Boolean; function Need_Expand (Text : in Wiki.Strings.WString) return Boolean is begin return Wiki.Strings.Index (Text, "$") > 0; end Need_Expand; procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is Filter : Filter_Type_Access := Chain.Next; begin while Filter /= null loop if Filter.all in Variable_Filter'Class then Variable_Filter'Class (Filter.all).Add_Variable (Name, Value); return; end if; Filter := Filter.Next; end loop; end Add_Variable; -- ------------------------------ -- Add a variable to replace the given name by its value. -- ------------------------------ procedure Add_Variable (Filter : in out Variable_Filter; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is begin Filter.Variables.Include (Name, Value); end Add_Variable; procedure Add_Variable (Filter : in out Variable_Filter; Name : in String; Value : in Wiki.Strings.WString) is begin Filter.Variables.Include (Wiki.Strings.To_WString (Name), Value); end Add_Variable; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ overriding procedure Add_Header (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Need_Expand (Header) then Filter_Type (Filter).Add_Header (Document, Filter.Expand (Header), Level); else Filter_Type (Filter).Add_Header (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Add a text content with the given format to the document. Replace variables -- that are contained in the text. -- ------------------------------ overriding procedure Add_Text (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Need_Expand (Text) then Filter_Type (Filter).Add_Text (Document, Filter.Expand (Text), Format); else Filter_Type (Filter).Add_Text (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Need_Expand (Name) then Filter_Type (Filter).Add_Link (Document, Filter.Expand (Name), Attributes); else Filter_Type (Filter).Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Need_Expand (Name) then Filter_Type (Filter).Add_Quote (Document, Filter.Expand (Name), Attributes); else Filter_Type (Filter).Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Expand the variables contained in the text. -- ------------------------------ function Expand (Filter : in Variable_Filter; Text : in Wiki.Strings.WString) return Wiki.Strings.WString is First : Natural := Text'First; Pos : Natural; Last : Natural; Name_Start : Natural; Name_End : Natural; Result : Wiki.Strings.BString (256); Item : Variable_Cursor; Match_End : Wiki.Strings.WChar; begin while First <= Text'Last loop Pos := First; while Pos <= Text'Last and then Text (Pos) /= '$' loop Pos := Pos + 1; end loop; exit when Pos >= Text'Last; Strings.Wide_Wide_Builders.Append (Result, Text (First .. Pos - 1)); First := Pos; Name_Start := Pos + 1; if Text (Name_Start) = '(' or Text (Name_Start) = '{' then Match_End := (if Text (Name_Start) = '(' then ')' else '}'); Name_Start := Name_Start + 1; Name_End := Name_Start; while Name_End <= Text'Last and then Text (Name_End) /= Match_End loop Name_End := Name_End + 1; end loop; exit when Name_End > Text'Last; exit when Text (Name_End) /= Match_End; Last := Name_End + 1; Name_End := Name_End - 1; else Name_End := Name_Start; while Name_End <= Text'Last and then Text (Name_End) /= ' ' loop Name_End := Name_End + 1; end loop; Last := Name_End; Name_End := Name_End - 1; end if; Item := Filter.Variables.Find (Text (Name_Start .. Name_End)); if Variable_Maps.Has_Element (Item) then Strings.Wide_Wide_Builders.Append (Result, Variable_Maps.Element (Item)); First := Last; elsif Last > Text'Last then exit; else Strings.Wide_Wide_Builders.Append (Result, Text (First .. Last)); First := Last + 1; end if; end loop; if First <= Text'Last then Strings.Wide_Wide_Builders.Append (Result, Text (First .. Text'Last)); end if; return Strings.Wide_Wide_Builders.To_Array (Result); end Expand; -- ------------------------------ -- Iterate over the filter variables. -- ------------------------------ procedure Iterate (Filter : in Variable_Filter; Process : not null access procedure (Name, Value : in Strings.WString)) is Iter : Variable_Cursor := Filter.Variables.First; begin while Variable_Maps.Has_Element (Iter) loop Variable_Maps.Query_Element (Iter, Process); Variable_Maps.Next (Iter); end loop; end Iterate; procedure Iterate (Chain : in Wiki.Filters.Filter_Chain; Process : not null access procedure (Name, Value : in Strings.WString)) is Filter : Filter_Type_Access := Chain.Next; begin while Filter /= null loop if Filter.all in Variable_Filter'Class then Variable_Filter'Class (Filter.all).Iterate (Process); return; end if; Filter := Filter.Next; end loop; end Iterate; end Wiki.Filters.Variables;
----------------------------------------------------------------------- -- wiki-filters-variables -- Expand variables in text and links -- Copyright (C) 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.Filters.Variables is function Need_Expand (Text : in Wiki.Strings.WString) return Boolean; function Need_Expand (Text : in Wiki.Strings.WString) return Boolean is begin return Wiki.Strings.Index (Text, "$") > 0; end Need_Expand; procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is Filter : Filter_Type_Access := Chain.Next; begin while Filter /= null loop if Filter.all in Variable_Filter'Class then Variable_Filter'Class (Filter.all).Add_Variable (Name, Value); return; end if; Filter := Filter.Next; end loop; end Add_Variable; -- ------------------------------ -- Add a variable to replace the given name by its value. -- ------------------------------ procedure Add_Variable (Filter : in out Variable_Filter; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is begin Filter.Variables.Include (Name, Value); end Add_Variable; procedure Add_Variable (Filter : in out Variable_Filter; Name : in String; Value : in Wiki.Strings.WString) is begin Filter.Variables.Include (Wiki.Strings.To_WString (Name), Value); end Add_Variable; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ overriding procedure Add_Header (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Need_Expand (Header) then Filter_Type (Filter).Add_Header (Document, Filter.Expand (Header), Level); else Filter_Type (Filter).Add_Header (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Add a text content with the given format to the document. Replace variables -- that are contained in the text. -- ------------------------------ overriding procedure Add_Text (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Need_Expand (Text) then Filter_Type (Filter).Add_Text (Document, Filter.Expand (Text), Format); else Filter_Type (Filter).Add_Text (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Need_Expand (Name) then Filter_Type (Filter).Add_Link (Document, Filter.Expand (Name), Attributes); else Filter_Type (Filter).Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Need_Expand (Name) then Filter_Type (Filter).Add_Quote (Document, Filter.Expand (Name), Attributes); else Filter_Type (Filter).Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Expand the variables contained in the text. -- ------------------------------ function Expand (Filter : in Variable_Filter; Text : in Wiki.Strings.WString) return Wiki.Strings.WString is First : Natural := Text'First; Pos : Natural; Last : Natural; Name_Start : Natural; Name_End : Natural; Result : Wiki.Strings.BString (256); Item : Variable_Cursor; Match_End : Wiki.Strings.WChar; begin while First <= Text'Last loop Pos := First; while Pos <= Text'Last and then Text (Pos) /= '$' loop Pos := Pos + 1; end loop; exit when Pos >= Text'Last; Strings.Wide_Wide_Builders.Append (Result, Text (First .. Pos - 1)); First := Pos; Name_Start := Pos + 1; if Text (Name_Start) = '(' or Text (Name_Start) = '{' then Match_End := (if Text (Name_Start) = '(' then ')' else '}'); Name_Start := Name_Start + 1; Name_End := Name_Start; while Name_End <= Text'Last and then Text (Name_End) /= Match_End loop Name_End := Name_End + 1; end loop; exit when Name_End > Text'Last; exit when Text (Name_End) /= Match_End; Last := Name_End + 1; Name_End := Name_End - 1; else Name_End := Name_Start; while Name_End <= Text'Last and then Text (Name_End) /= ' ' loop Name_End := Name_End + 1; end loop; Last := Name_End; Name_End := Name_End - 1; end if; Item := Filter.Variables.Find (Text (Name_Start .. Name_End)); if Strings.Maps.Has_Element (Item) then Strings.Wide_Wide_Builders.Append (Result, Strings.Maps.Element (Item)); First := Last; elsif Last > Text'Last then exit; else Strings.Wide_Wide_Builders.Append (Result, Text (First .. Last)); First := Last + 1; end if; end loop; if First <= Text'Last then Strings.Wide_Wide_Builders.Append (Result, Text (First .. Text'Last)); end if; return Strings.Wide_Wide_Builders.To_Array (Result); end Expand; -- ------------------------------ -- Iterate over the filter variables. -- ------------------------------ procedure Iterate (Filter : in Variable_Filter; Process : not null access procedure (Name, Value : in Strings.WString)) is Iter : Variable_Cursor := Filter.Variables.First; begin while Strings.Maps.Has_Element (Iter) loop Strings.Maps.Query_Element (Iter, Process); Strings.Maps.Next (Iter); end loop; end Iterate; procedure Iterate (Chain : in Wiki.Filters.Filter_Chain; Process : not null access procedure (Name, Value : in Strings.WString)) is Filter : Filter_Type_Access := Chain.Next; begin while Filter /= null loop if Filter.all in Variable_Filter'Class then Variable_Filter'Class (Filter.all).Iterate (Process); return; end if; Filter := Filter.Next; end loop; end Iterate; end Wiki.Filters.Variables;
Update to use the Wiki.Strings.Maps package
Update to use the Wiki.Strings.Maps package
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0148b4d4c76e1e8e7b7d1001cc12f2f25e68e0b1
src/util-serialize-io-csv.adb
src/util-serialize-io-csv.adb
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Dates.ISO8601; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character) is begin Stream.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Enable or disable the double quotes by default for strings. -- ------------------------------ procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean) is begin Stream.Quote := Enable; end Set_Quotes; -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ('"'); end if; for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; if Stream.Quote then Stream.Write ('"'); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ("""null"""); else Stream.Write ("null"); end if; when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; -- Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); -- Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (Stream.Separator); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Ada.Strings.Unbounded.To_String (Value.Value)); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Ada.Strings.Unbounded.To_String (Value.Value)); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Handler.Sink.Finish_Object ("", Handler); else Handler.Sink.Start_Array ("", Handler); end if; Handler.Sink.Start_Object ("", Handler); end if; Handler.Row := Row; Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; begin if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; Handler.Sink := Sink'Unchecked_Access; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Handler.Sink := null; return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Dates.ISO8601; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character) is begin Stream.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Enable or disable the double quotes by default for strings. -- ------------------------------ procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean) is begin Stream.Quote := Enable; end Set_Quotes; -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ('"'); end if; for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; if Stream.Quote then Stream.Write ('"'); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ("""null"""); else Stream.Write ("null"); end if; when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; -- Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); -- Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (Stream.Separator); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Ada.Strings.Unbounded.To_String (Value.Value)); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Ada.Strings.Unbounded.To_String (Value.Value)); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ------------------------------ -- Write the attribute with a null value. -- ------------------------------ overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is begin Stream.Write_Entity (Name, ""); end Write_Null_Attribute; -- ------------------------------ -- Write an entity with a null value. -- ------------------------------ procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is begin Stream.Write_Null_Attribute (Name); end Write_Null_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Handler.Sink.Finish_Object ("", Handler); else Handler.Sink.Start_Array ("", Handler); end if; Handler.Sink.Start_Object ("", Handler); end if; Handler.Row := Row; Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; begin if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; Handler.Sink := Sink'Unchecked_Access; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Handler.Sink := null; return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
Implement the Write_Null_Attribute and Write_Null_Entity operations
Implement the Write_Null_Attribute and Write_Null_Entity operations
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e8d99340e83cfa6155fa451f20a5952d90ed25c8
src/util-commands.ads
src/util-commands.ads
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Util.Strings.Vectors; private with Ada.Strings.Unbounded; package Util.Commands is -- The argument list interface that gives access to command arguments. type Argument_List is limited interface; -- Get the number of arguments available. function Get_Count (List : in Argument_List) return Natural is abstract; -- Get the argument at the given position. function Get_Argument (List : in Argument_List; Pos : in Positive) return String is abstract; -- Get the command name. function Get_Command_Name (List : in Argument_List) return String is abstract; type Default_Argument_List (Offset : Natural) is new Argument_List with null record; -- Get the number of arguments available. overriding function Get_Count (List : in Default_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Default_Argument_List) return String; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with private; -- Set the argument list to the given string and split the arguments. procedure Initialize (List : in out String_Argument_List; Line : in String); -- Get the number of arguments available. overriding function Get_Count (List : in String_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in String_Argument_List; Pos : in Positive) return String; -- Get the command name. overriding function Get_Command_Name (List : in String_Argument_List) return String; -- The argument list interface that gives access to command arguments. type Dynamic_Argument_List is limited new Argument_List with private; -- Get the number of arguments available. function Get_Count (List : in Dynamic_Argument_List) return Natural; -- Get the argument at the given position. function Get_Argument (List : in Dynamic_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Dynamic_Argument_List) return String; private type Argument_Pos is array (Natural range <>) of Natural; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with record Count : Natural := 0; Length : Natural := 0; Line : String (1 .. Max_Length); Start_Pos : Argument_Pos (0 .. Max_Args); End_Pos : Argument_Pos (0 .. Max_Args); end record; type Dynamic_Argument_List is limited new Argument_List with record List : Util.Strings.Vectors.Vector; Name : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands;
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Util.Strings.Vectors; private with Ada.Strings.Unbounded; package Util.Commands is -- The argument list interface that gives access to command arguments. type Argument_List is limited interface; -- Get the number of arguments available. function Get_Count (List : in Argument_List) return Natural is abstract; -- Get the argument at the given position. function Get_Argument (List : in Argument_List; Pos : in Positive) return String is abstract; -- Get the command name. function Get_Command_Name (List : in Argument_List) return String is abstract; type Default_Argument_List (Offset : Natural) is new Argument_List with null record; -- Get the number of arguments available. overriding function Get_Count (List : in Default_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Default_Argument_List) return String; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with private; -- Set the argument list to the given string and split the arguments. procedure Initialize (List : in out String_Argument_List; Line : in String); -- Get the number of arguments available. overriding function Get_Count (List : in String_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in String_Argument_List; Pos : in Positive) return String; -- Get the command name. overriding function Get_Command_Name (List : in String_Argument_List) return String; -- The argument list interface that gives access to command arguments. type Dynamic_Argument_List is limited new Argument_List with private; -- Get the number of arguments available. function Get_Count (List : in Dynamic_Argument_List) return Natural; -- Get the argument at the given position. function Get_Argument (List : in Dynamic_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Dynamic_Argument_List) return String; private type Argument_Pos is array (Natural range <>) of Natural; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with record Count : Natural := 0; Length : Natural := 0; Line : String (1 .. Max_Length); Start_Pos : Argument_Pos (0 .. Max_Args) := (others => 0); End_Pos : Argument_Pos (0 .. Max_Args) := (others => 0); end record; type Dynamic_Argument_List is limited new Argument_List with record List : Util.Strings.Vectors.Vector; Name : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands;
Initialize the Start_Pos and End_Pos arrays by default in the String_Argument_List record
Initialize the Start_Pos and End_Pos arrays by default in the String_Argument_List record
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
be2ea5b17405ca6e8837ef2b28b543c272750830
src/configure.ads
src/configure.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Definitions; use Definitions; private with Ada.Characters.Latin_1; private with Parameters; package Configure is menu_error : exception; -- Interactive configuration menu procedure launch_configure_menu; -- Print out configuration value -- If input not 'A' - 'Q', return "Error: Input must be character 'A'...'Q'" procedure print_configuration_value (option : Character); private package LAT renames Ada.Characters.Latin_1; package PM renames Parameters; indent : constant String (1 .. 3) := (others => LAT.Space); type option is range 1 .. 17; type default is range 1 .. 10; subtype ofield is String (1 .. 30); type desc_type is array (option) of ofield; type default_type is array (default) of ofield; descriptions : constant desc_type := ( "[A] System root directory ", "[B] Toolchain directory ", "[C] Localbase directory ", "[D] Conspiracy directory ", "[E] Custom ports directory ", "[F] Distfiles directory ", "[G] Profile directory (logs+) ", "[H] Packages directory ", "[I] Compiler cache directory ", "[J] Build base directory ", "[K] Num. concurrent builders ", "[L] Max. jobs per builder ", "[M] Avoid use of tmpfs ", "[N] Fetch prebuilt packages ", "[O] Display using ncurses ", "[P] Always record options ", "[Q] Assume default options " ); version_desc : constant default_type := ( "[A] Firebird SQL server ", "[B] Lua (language) ", "[C] MySQL-workalike server ", "[D] Perl (language) ", "[E] PHP (language) ", "[F] PostgreSQL server ", "[G] Python 3 (language) ", "[H] Ruby (language) ", "[I] SSL/TLS library ", "[J] TCL/TK toolkit " ); optX5A : constant String := "[V] Set version defaults (e.g. perl, ruby, mysql ...)"; optX1A : constant String := "[>] Switch/create profiles (changes discarded)"; optX1B : constant String := "[>] Switch/create profiles"; optX4B : constant String := "[<] Delete alternative profile"; optX2A : constant String := "[ESC] Exit without saving changes"; optX3A : constant String := "[RET] Save changes (starred) "; optX3B : constant String := "[RET] Exit "; dupe : PM.configuration_record; version_A : constant String := default_firebird & ":3.0"; version_B : constant String := "5.2:" & default_lua & ":5.4"; version_C : constant String := "oracle-5.7:" & default_mysql & "mariadb-10.3:mariadb-10.4:mariadb-10.5:mariadb-10.6:" & "mariadb-10.7:mariadb-10.8:mariadb-10.9:" & "percona-5.6:percona-5.7:percona-8.0"; version_D : constant String := default_perl & ":5.36"; version_E : constant String := "7.4:" & default_php & ":8.1"; version_F : constant String := "10:11:" & default_pgsql & ":13:14"; version_G : constant String := default_python3 & ":3.10"; version_H : constant String := "2.7:" & default_ruby & ":3.1"; version_I : constant String := "openssl10:openssl11:openssl30:" & default_ssl & ":libressl-devel"; version_J : constant String := "8.5:" & default_tcltk; procedure clear_screen; procedure print_header; procedure print_opt (opt : option; pristine : in out Boolean); procedure change_directory_option (opt : option; pristine : in out Boolean); procedure change_boolean_option (opt : option; pristine : in out Boolean); procedure change_positive_option (opt : option; pristine : in out Boolean); procedure delete_profile; procedure switch_profile; procedure move_to_defaults_menu (pristine_def : in out Boolean); procedure print_default (def : default; pristine_def : in out Boolean); procedure update_version (def : default; choices : String; label : String); procedure print_menu (pristine : in out Boolean; extra_profiles : Boolean; pristine_def : Boolean); end Configure;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Definitions; use Definitions; private with Ada.Characters.Latin_1; private with Parameters; package Configure is menu_error : exception; -- Interactive configuration menu procedure launch_configure_menu; -- Print out configuration value -- If input not 'A' - 'Q', return "Error: Input must be character 'A'...'Q'" procedure print_configuration_value (option : Character); private package LAT renames Ada.Characters.Latin_1; package PM renames Parameters; indent : constant String (1 .. 3) := (others => LAT.Space); type option is range 1 .. 17; type default is range 1 .. 10; subtype ofield is String (1 .. 30); type desc_type is array (option) of ofield; type default_type is array (default) of ofield; descriptions : constant desc_type := ( "[A] System root directory ", "[B] Toolchain directory ", "[C] Localbase directory ", "[D] Conspiracy directory ", "[E] Custom ports directory ", "[F] Distfiles directory ", "[G] Profile directory (logs+) ", "[H] Packages directory ", "[I] Compiler cache directory ", "[J] Build base directory ", "[K] Num. concurrent builders ", "[L] Max. jobs per builder ", "[M] Avoid use of tmpfs ", "[N] Fetch prebuilt packages ", "[O] Display using ncurses ", "[P] Always record options ", "[Q] Assume default options " ); version_desc : constant default_type := ( "[A] Firebird SQL server ", "[B] Lua (language) ", "[C] MySQL-workalike server ", "[D] Perl (language) ", "[E] PHP (language) ", "[F] PostgreSQL server ", "[G] Python 3 (language) ", "[H] Ruby (language) ", "[I] SSL/TLS library ", "[J] TCL/TK toolkit " ); optX5A : constant String := "[V] Set version defaults (e.g. perl, ruby, mysql ...)"; optX1A : constant String := "[>] Switch/create profiles (changes discarded)"; optX1B : constant String := "[>] Switch/create profiles"; optX4B : constant String := "[<] Delete alternative profile"; optX2A : constant String := "[ESC] Exit without saving changes"; optX3A : constant String := "[RET] Save changes (starred) "; optX3B : constant String := "[RET] Exit "; dupe : PM.configuration_record; version_A : constant String := default_firebird & ":3.0"; version_B : constant String := "5.2:" & default_lua & ":5.4"; version_C : constant String := "oracle-5.7:" & default_mysql & ":" & "mariadb-10.3:mariadb-10.4:mariadb-10.5:mariadb-10.6:" & "mariadb-10.7:mariadb-10.8:mariadb-10.9:" & "percona-5.6:percona-5.7:percona-8.0"; version_D : constant String := default_perl & ":5.36"; version_E : constant String := "7.4:" & default_php & ":8.1"; version_F : constant String := "10:11:" & default_pgsql & ":13:14"; version_G : constant String := default_python3 & ":3.10"; version_H : constant String := "2.7:" & default_ruby & ":3.1"; version_I : constant String := "openssl10:openssl11:openssl30:" & default_ssl & ":libressl-devel"; version_J : constant String := "8.5:" & default_tcltk; procedure clear_screen; procedure print_header; procedure print_opt (opt : option; pristine : in out Boolean); procedure change_directory_option (opt : option; pristine : in out Boolean); procedure change_boolean_option (opt : option; pristine : in out Boolean); procedure change_positive_option (opt : option; pristine : in out Boolean); procedure delete_profile; procedure switch_profile; procedure move_to_defaults_menu (pristine_def : in out Boolean); procedure print_default (def : default; pristine_def : in out Boolean); procedure update_version (def : default; choices : String; label : String); procedure print_menu (pristine : in out Boolean; extra_profiles : Boolean; pristine_def : Boolean); end Configure;
Fix mysql options
Fix mysql options
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
543be083c7ad21c75883467c10bf7f31d9ea900f
ARM/STM32/driver_demos/demo_serial_ports/src/serial_io-streaming.adb
ARM/STM32/driver_demos/demo_serial_ports/src/serial_io-streaming.adb
------------------------------------------------------------------------------ -- -- -- 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 STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with STM32.Device; use STM32.Device; with HAL; use HAL; package body Serial_IO.Streaming is ---------------- -- Initialize -- ---------------- procedure Initialize (This : out Serial_Port) is begin Serial_IO.Initialize_Peripheral (This.Device); This.Initialized := True; end Initialize; ----------------- -- Initialized -- ----------------- function Initialized (This : Serial_Port) return Boolean is (This.Initialized); --------------- -- Configure -- --------------- procedure Configure (This : in out Serial_Port; Baud_Rate : Baud_Rates; Parity : Parities := No_Parity; Data_Bits : Word_Lengths := Word_Length_8; End_Bits : Stop_Bits := Stopbits_1; Control : Flow_Control := No_Flow_Control) is begin Serial_IO.Configure (This.Device, Baud_Rate, Parity, Data_Bits, End_Bits, Control); end Configure; -- --------- -- -- Get -- -- --------- -- -- procedure Get (This : in out Serial_Port; Msg : not null access Message) is -- Received_Char : Character; -- Raw : UInt9; -- Timeout : constant Time_Span := Milliseconds (50); -- arbitrary (???) -- Timed_Out : Boolean; -- begin -- Msg.Clear; -- Receiving : for K in 1 .. Msg.Physical_Size loop -- Await_Data_Available (This.Device.Transceiver.all, Timeout, Timed_Out); -- exit Receiving when Timed_Out; -- Receive (This.Device.Transceiver.all, Raw); -- Received_Char := Character'Val (Raw); -- exit Receiving when Received_Char = Msg.Terminator; -- Msg.Append (Received_Char); -- end loop Receiving; -- end Get; ---------------------- -- Await_Send_Ready -- ---------------------- procedure Await_Send_Ready (This : USART) is begin loop exit when Tx_Ready (This); end loop; end Await_Send_Ready; ---------------------- -- Set_Read_Timeout -- ---------------------- procedure Set_Read_Timeout (This : in out Serial_Port; Wait : Time_Span := Time_Span_Last) is begin This.Timeout := Wait; end Set_Read_Timeout; -------------------------- -- Await_Data_Available -- -------------------------- procedure Await_Data_Available (This : USART; Timeout : Time_Span := Time_Span_Last; Timed_Out : out Boolean) is Deadline : constant Time := Clock + Timeout; begin Timed_Out := True; while Clock < Deadline loop if Rx_Ready (This) then Timed_Out := False; exit; end if; end loop; end Await_Data_Available; ---------------- -- Last_Index -- ---------------- function Last_Index (First : Stream_Element_Offset; Count : Long_Integer) return Stream_Element_Offset is begin if First = Stream_Element_Offset'First and then Count = 0 then -- we need to return First - 1, but cannot raise Constraint_Error; -- per RM else return First + Stream_Element_Offset (Count) - 1; end if; end Last_Index; ---------- -- Read -- ---------- overriding procedure Read (This : in out Serial_Port; Buffer : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Raw : UInt9; Timed_Out : Boolean; Count : Long_Integer := 0; begin Receiving : for K in Buffer'Range loop Await_Data_Available (This.Device.Transceiver.all, This.Timeout, Timed_Out); exit Receiving when Timed_Out; Receive (This.Device.Transceiver.all, Raw); Buffer (K) := Stream_Element (Raw); Count := Count + 1; end loop Receiving; Last := Last_Index (Buffer'First, Count); end Read; ----------- -- Write -- ----------- overriding procedure Write (This : in out Serial_Port; Buffer : Ada.Streams.Stream_Element_Array) is begin for Next of Buffer loop Await_Send_Ready (This.Device.Transceiver.all); Transmit (This.Device.Transceiver.all, Stream_Element'Pos (Next)); end loop; end Write; end Serial_IO.Streaming;
------------------------------------------------------------------------------ -- -- -- 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 STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with STM32.Device; use STM32.Device; with HAL; use HAL; package body Serial_IO.Streaming is ---------------- -- Initialize -- ---------------- procedure Initialize (This : out Serial_Port) is begin Serial_IO.Initialize_Peripheral (This.Device); This.Initialized := True; end Initialize; ----------------- -- Initialized -- ----------------- function Initialized (This : Serial_Port) return Boolean is (This.Initialized); --------------- -- Configure -- --------------- procedure Configure (This : in out Serial_Port; Baud_Rate : Baud_Rates; Parity : Parities := No_Parity; Data_Bits : Word_Lengths := Word_Length_8; End_Bits : Stop_Bits := Stopbits_1; Control : Flow_Control := No_Flow_Control) is begin Serial_IO.Configure (This.Device, Baud_Rate, Parity, Data_Bits, End_Bits, Control); end Configure; ---------------------- -- Await_Send_Ready -- ---------------------- procedure Await_Send_Ready (This : USART) is begin loop exit when Tx_Ready (This); end loop; end Await_Send_Ready; ---------------------- -- Set_Read_Timeout -- ---------------------- procedure Set_Read_Timeout (This : in out Serial_Port; Wait : Time_Span := Time_Span_Last) is begin This.Timeout := Wait; end Set_Read_Timeout; -------------------------- -- Await_Data_Available -- -------------------------- procedure Await_Data_Available (This : USART; Timeout : Time_Span := Time_Span_Last; Timed_Out : out Boolean) is Deadline : constant Time := Clock + Timeout; begin Timed_Out := True; while Clock < Deadline loop if Rx_Ready (This) then Timed_Out := False; exit; end if; end loop; end Await_Data_Available; ---------------- -- Last_Index -- ---------------- function Last_Index (First : Stream_Element_Offset; Count : Long_Integer) return Stream_Element_Offset is begin if First = Stream_Element_Offset'First and then Count = 0 then -- we need to return First - 1, but cannot raise Constraint_Error; -- per RM else return First + Stream_Element_Offset (Count) - 1; end if; end Last_Index; ---------- -- Read -- ---------- overriding procedure Read (This : in out Serial_Port; Buffer : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Raw : UInt9; Timed_Out : Boolean; Count : Long_Integer := 0; begin Receiving : for K in Buffer'Range loop Await_Data_Available (This.Device.Transceiver.all, This.Timeout, Timed_Out); exit Receiving when Timed_Out; Receive (This.Device.Transceiver.all, Raw); Buffer (K) := Stream_Element (Raw); Count := Count + 1; end loop Receiving; Last := Last_Index (Buffer'First, Count); end Read; ----------- -- Write -- ----------- overriding procedure Write (This : in out Serial_Port; Buffer : Ada.Streams.Stream_Element_Array) is begin for Next of Buffer loop Await_Send_Ready (This.Device.Transceiver.all); Transmit (This.Device.Transceiver.all, Stream_Element'Pos (Next)); end loop; end Write; end Serial_IO.Streaming;
Remove commented-out code
Remove commented-out code
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library
c0881f31b57b6b4585207b4d9642cc72823ab2b8
mat/src/mat-expressions.ads
mat/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_CONDITION, N_THREAD); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_CONDITION, N_THREAD); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
Change the Is_Selected operation to give the slot address and allocation as parameter
Change the Is_Selected operation to give the slot address and allocation as parameter
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ed5c2a33b366f62be6841c2bfe40a415d44c4901
mat/src/mat-targets-probes.adb
mat/src/mat-targets-probes.adb
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes"); MSG_BEGIN : constant MAT.Events.Targets.Probe_Index_Type := 0; MSG_END : constant MAT.Events.Targets.Probe_Index_Type := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in out Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin -- Probe.Target.Create_Process (Pid => Pid, -- Path => Path, -- Process => Probe.Process); Probe.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in out Process_Probe_Type; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Process.Memory.Add_Region (Heap); end Probe_Begin; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is begin null; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes"); MSG_BEGIN : constant MAT.Events.Targets.Probe_Index_Type := 0; MSG_END : constant MAT.Events.Targets.Probe_Index_Type := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Id : in MAT.Events.Targets.Probe_Index_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); end Probe_Begin; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MSG_BEGIN then Probe.Probe_Begin (Event.Index, Params.all, Msg); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
Call Probe_Begin to extract the begin event information, create the new process
Call Probe_Begin to extract the begin event information, create the new process
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a25449d1f250e2ab00ed68b9a1c3e574c6c6c537
src/orka/implementation/orka-resources-textures-ktx.adb
src/orka/implementation/orka-resources-textures-ktx.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System; with Ada.Exceptions; with Ada.Real_Time; with Ada.Unchecked_Deallocation; with GL.Low_Level.Enums; with GL.Types; with GL.Pixels.Extensions; with GL.Pixels.Queries; with Orka.Jobs; with Orka.Logging; with Orka.KTX; package body Orka.Resources.Textures.KTX is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; package Messages is new Orka.Logging.Messages (Resource_Loader); type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record Data : Loaders.Resource_Data; Manager : Managers.Manager_Ptr; end record; overriding procedure Execute (Object : KTX_Load_Job; Context : Jobs.Execution_Context'Class); ----------------------------------------------------------------------------- use all type Ada.Real_Time.Time; function Read_Texture (Bytes : Byte_Array_Pointers.Constant_Reference; Path : String; Start : Ada.Real_Time.Time) return GL.Objects.Textures.Texture is T1 : Ada.Real_Time.Time renames Start; T2 : constant Ada.Real_Time.Time := Clock; use Ada.Streams; use GL.Low_Level.Enums; use type GL.Types.Size; T3, T4, T5, T6 : Ada.Real_Time.Time; begin if not Orka.KTX.Valid_Identifier (Bytes) then raise Texture_Load_Error with Path & " is not a KTX file"; end if; declare Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes); Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels); Texture : GL.Objects.Textures.Texture (Header.Kind); Width : constant GL.Types.Size := Header.Width; Height : GL.Types.Size := Header.Height; Depth : GL.Types.Size := Header.Depth; begin T3 := Clock; if not Header.Compressed and then Header.Data_Type in GL.Pixels.Extensions.Packed_Data_Type then raise GL.Feature_Not_Supported_Exception with "Packed data type " & Header.Data_Type'Image & " is not supported yet"; end if; -- Allocate storage case Header.Kind is when Texture_2D_Array => Depth := Header.Array_Elements; when Texture_1D_Array => Height := Header.Array_Elements; pragma Assert (Depth = 0); when Texture_Cube_Map_Array => -- For a cube map array, depth is the number of layer-faces Depth := Header.Array_Elements * 6; when Texture_3D => null; when Texture_2D | Texture_Cube_Map => pragma Assert (Depth = 0); when Texture_1D => if Header.Compressed then raise Texture_Load_Error with Path & " has unknown 1D compressed format"; end if; pragma Assert (Height = 0); pragma Assert (Depth = 0); when others => raise Program_Error; end case; if Header.Compressed then Texture.Allocate_Storage (Levels, 1, Header.Compressed_Format, Width, Height, Depth); else Texture.Allocate_Storage (Levels, 1, Header.Internal_Format, Width, Height, Depth); end if; case Header.Kind is when Texture_1D => Height := 1; Depth := 1; when Texture_1D_Array | Texture_2D => Depth := 1; when Texture_2D_Array | Texture_3D => null; when Texture_Cube_Map | Texture_Cube_Map_Array => -- Texture_Cube_Map uses 2D storage, but 3D load operation -- according to table 8.15 of the OpenGL specification -- For a cube map, depth is the number of faces, for -- a cube map array, depth is the number of layer-faces Depth := GL.Types.Size'Max (1, Header.Array_Elements) * 6; when others => raise Program_Error; end case; T4 := Clock; -- TODO Handle KTXorientation key value pair -- Upload texture data declare Image_Size_Index : Stream_Element_Offset := Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value); Cube_Map : constant Boolean := Header.Kind = Texture_Cube_Map; begin for Level in 0 .. Levels - 1 loop declare Face_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index); -- If not Cube_Map, then Face_Size is the size of the whole level Cube_Padding : constant Natural := 3 - ((Face_Size + 3) mod 4); Image_Size : constant Natural := (if Cube_Map then (Face_Size + Cube_Padding) * 6 else Face_Size); -- If Cube_Map then Levels = 1 so no need to add it to the expression -- Compute size of the whole mipmap level Mip_Padding : constant Natural := 3 - ((Image_Size + 3) mod 4); Mipmap_Size : constant Natural := 4 + Image_Size + Mip_Padding; Offset : constant Stream_Element_Offset := Image_Size_Index + 4; pragma Assert (Offset + Stream_Element_Offset (Image_Size) - 1 <= Bytes.Value'Last); Image_Data : constant System.Address := Bytes (Offset)'Address; -- TODO Unpack_Alignment must be 4, but Load_From_Data wants 1 | 2 | 4 -- depending on Header.Data_Type Level_Width : constant GL.Types.Size := Texture.Width (Level); Level_Height : constant GL.Types.Size := Texture.Height (Level); Level_Depth : constant GL.Types.Size := Texture.Depth (Level); begin if Header.Compressed then Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data); else Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth, Header.Format, Header.Data_Type, Image_Data); end if; Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size); end; end loop; end; T5 := Clock; -- Generate a full mipmap pyramid if Mipmap_Levels = 0 if Header.Mipmap_Levels = 0 then Texture.Generate_Mipmap; end if; T6 := Clock; Messages.Log (Info, "Loaded texture " & Path & " in " & Logging.Trim (Logging.Image (T6 - T1))); Messages.Log (Info, " size: " & Logging.Trim (Width'Image) & " x " & Logging.Trim (Height'Image) & " x " & Logging.Trim (Depth'Image) & ", mipmap levels:" & Levels'Image); Messages.Log (Info, " kind: " & Header.Kind'Image); if Header.Compressed then Messages.Log (Info, " format: " & Header.Compressed_Format'Image); else Messages.Log (Info, " format: " & Header.Internal_Format'Image); end if; Messages.Log (Info, " statistics:"); Messages.Log (Info, " reading file: " & Logging.Image (T2 - T1)); Messages.Log (Info, " parsing header: " & Logging.Image (T3 - T2)); Messages.Log (Info, " storage: " & Logging.Image (T4 - T3)); Messages.Log (Info, " buffers: " & Logging.Image (T5 - T4)); if Header.Mipmap_Levels = 0 then Messages.Log (Info, " generating mipmap:" & Logging.Image (T6 - T5)); end if; return Texture; end; exception when Error : Orka.KTX.Invalid_Enum_Error => declare Message : constant String := Ada.Exceptions.Exception_Message (Error); begin raise Texture_Load_Error with Path & " has " & Message; end; end Read_Texture; function Read_Texture (Location : Locations.Location_Ptr; Path : String) return GL.Objects.Textures.Texture is Start_Time : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin return Read_Texture (Location.Read_Data (Path).Get, Path, Start_Time); end Read_Texture; overriding procedure Execute (Object : KTX_Load_Job; Context : Jobs.Execution_Context'Class) is Bytes : Byte_Array_Pointers.Constant_Reference := Object.Data.Bytes.Get; Path : String renames SU.To_String (Object.Data.Path); Resource : constant Texture_Ptr := new Texture'(others => <>); begin Resource.Texture.Replace_Element (Read_Texture (Bytes, Path, Object.Data.Start_Time)); -- Register resource at the resource manager Object.Manager.Add_Resource (Path, Resource_Ptr (Resource)); end Execute; ----------------------------------------------------------------------------- -- Loader -- ----------------------------------------------------------------------------- type KTX_Loader is limited new Loaders.Loader with record Manager : Managers.Manager_Ptr; end record; overriding function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx"); overriding procedure Load (Object : KTX_Loader; Data : Loaders.Resource_Data; Enqueue : not null access procedure (Element : Jobs.Job_Ptr); Location : Locations.Location_Ptr) is Job : constant Jobs.Job_Ptr := new KTX_Load_Job' (Jobs.Abstract_Job with Data => Data, Manager => Object.Manager); begin Enqueue (Job); end Load; function Create_Loader (Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr is (new KTX_Loader'(Manager => Manager)); ----------------------------------------------------------------------------- -- Writer -- ----------------------------------------------------------------------------- procedure Write_Texture (Texture : GL.Objects.Textures.Texture; Location : Locations.Writable_Location_Ptr; Path : String) is package Textures renames GL.Objects.Textures; package Pointers is new Textures.Texture_Pointers (Byte_Pointers); Format : GL.Pixels.Format := GL.Pixels.RGBA; Data_Type : GL.Pixels.Data_Type := GL.Pixels.Float; -- Note: unused if texture is compressed Base_Level : constant := 0; use Ada.Streams; use all type GL.Low_Level.Enums.Texture_Kind; use type GL.Types.Size; Compressed : constant Boolean := Texture.Compressed; Header : Orka.KTX.Header (Compressed); function Convert (Bytes : in out GL.Types.UByte_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); procedure Free is new Ada.Unchecked_Deallocation (Object => GL.Types.UByte_Array, Name => GL.Types.UByte_Array_Access); begin for Index in Bytes'Range loop declare Target_Index : constant Stream_Element_Offset := Stream_Element_Offset (Index - Bytes'First + 1); begin Result (Target_Index) := Stream_Element (Bytes (Index)); end; end loop; Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Convert (Bytes : in out Pointers.Element_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); begin Result.all := Bytes.all; Pointers.Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Get_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : Pointers.Element_Array_Access; begin Data := Pointers.Get_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Format, Data_Type); return Convert (Data); end Get_Data; function Get_Compressed_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : GL.Types.UByte_Array_Access; begin Data := Textures.Get_Compressed_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Texture.Compressed_Format); return Convert (Data); end Get_Compressed_Data; begin Header.Kind := Texture.Kind; Header.Width := Texture.Width (Base_Level); case Texture.Kind is when Texture_3D => Header.Height := Texture.Height (Base_Level); Header.Depth := Texture.Depth (Base_Level); when Texture_2D | Texture_2D_Array | Texture_Cube_Map | Texture_Cube_Map_Array => Header.Height := Texture.Height (Base_Level); Header.Depth := 0; when Texture_1D | Texture_1D_Array => Header.Height := 0; Header.Depth := 0; when others => raise Program_Error; end case; case Texture.Kind is when Texture_1D_Array => Header.Array_Elements := Texture.Height (Base_Level); when Texture_2D_Array => Header.Array_Elements := Texture.Depth (Base_Level); when Texture_Cube_Map_Array => Header.Array_Elements := Texture.Depth (Base_Level) / 6; when Texture_1D | Texture_2D | Texture_3D | Texture_Cube_Map => Header.Array_Elements := 0; when others => raise Program_Error; end case; Header.Mipmap_Levels := Texture.Mipmap_Levels; Header.Bytes_Key_Value := 0; if Compressed then Header.Compressed_Format := Texture.Compressed_Format; else declare Internal_Format : constant GL.Pixels.Internal_Format := Texture.Internal_Format; begin Format := GL.Pixels.Queries.Get_Texture_Format (Internal_Format, Texture.Kind); Data_Type := GL.Pixels.Queries.Get_Texture_Type (Internal_Format, Texture.Kind); Header.Internal_Format := Internal_Format; Header.Format := Format; Header.Data_Type := Data_Type; end; end if; declare function Get_Level_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is (if Compressed then Get_Compressed_Data (Level) else Get_Data (Level)); Bytes : constant Byte_Array_Pointers.Pointer := Orka.KTX.Create_KTX_Bytes (Header, Get_Level_Data'Access); begin Location.Write_Data (Path, Bytes.Get); end; end Write_Texture; end Orka.Resources.Textures.KTX;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System; with Ada.Exceptions; with Ada.Real_Time; with Ada.Unchecked_Deallocation; with GL.Low_Level.Enums; with GL.Types; with GL.Pixels.Extensions; with GL.Pixels.Queries; with Orka.Jobs; with Orka.Logging; with Orka.KTX; package body Orka.Resources.Textures.KTX is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; package Messages is new Orka.Logging.Messages (Resource_Loader); type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record Data : Loaders.Resource_Data; Manager : Managers.Manager_Ptr; end record; overriding procedure Execute (Object : KTX_Load_Job; Context : Jobs.Execution_Context'Class); ----------------------------------------------------------------------------- use all type Ada.Real_Time.Time; function Read_Texture (Bytes : Byte_Array_Pointers.Constant_Reference; Path : String; Start : Ada.Real_Time.Time) return GL.Objects.Textures.Texture is T1 : Ada.Real_Time.Time renames Start; T2 : constant Ada.Real_Time.Time := Clock; use Ada.Streams; use GL.Low_Level.Enums; use type GL.Types.Size; T3, T4, T5, T6 : Ada.Real_Time.Time; begin if not Orka.KTX.Valid_Identifier (Bytes) then raise Texture_Load_Error with Path & " is not a KTX file"; end if; declare Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes); Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels); Texture : GL.Objects.Textures.Texture (Header.Kind); Width : constant GL.Types.Size := Header.Width; Height : GL.Types.Size := Header.Height; Depth : GL.Types.Size := Header.Depth; begin T3 := Clock; if not Header.Compressed and then Header.Data_Type in GL.Pixels.Extensions.Packed_Data_Type then raise GL.Feature_Not_Supported_Exception with "Packed data type " & Header.Data_Type'Image & " is not supported yet"; end if; -- Allocate storage case Header.Kind is when Texture_2D_Array => Depth := Header.Array_Elements; when Texture_1D_Array => Height := Header.Array_Elements; pragma Assert (Depth = 0); when Texture_Cube_Map_Array => -- For a cube map array, depth is the number of layer-faces Depth := Header.Array_Elements * 6; when Texture_3D => null; when Texture_2D | Texture_Cube_Map => pragma Assert (Depth = 0); when Texture_1D => if Header.Compressed then raise Texture_Load_Error with Path & " has unknown 1D compressed format"; end if; pragma Assert (Height = 0); pragma Assert (Depth = 0); when others => raise Program_Error; end case; if Header.Compressed then Texture.Allocate_Storage (Levels, 1, Header.Compressed_Format, Width, Height, Depth); else Texture.Allocate_Storage (Levels, 1, Header.Internal_Format, Width, Height, Depth); end if; case Header.Kind is when Texture_1D => Height := 1; Depth := 1; when Texture_1D_Array | Texture_2D => Depth := 1; when Texture_2D_Array | Texture_3D => null; when Texture_Cube_Map | Texture_Cube_Map_Array => -- Texture_Cube_Map uses 2D storage, but 3D load operation -- according to table 8.15 of the OpenGL specification -- For a cube map, depth is the number of faces, for -- a cube map array, depth is the number of layer-faces Depth := GL.Types.Size'Max (1, Header.Array_Elements) * 6; when others => raise Program_Error; end case; T4 := Clock; -- TODO Handle KTXorientation key value pair -- Upload texture data declare Image_Size_Index : Stream_Element_Offset := Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value); Cube_Map : constant Boolean := Header.Kind = Texture_Cube_Map; begin for Level in 0 .. Levels - 1 loop declare Face_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index); -- If not Cube_Map, then Face_Size is the size of the whole level Cube_Padding : constant Natural := 3 - ((Face_Size + 3) mod 4); Image_Size : constant Natural := (if Cube_Map then (Face_Size + Cube_Padding) * 6 else Face_Size); -- If Cube_Map then Levels = 1 so no need to add it to the expression -- Compute size of the whole mipmap level Mip_Padding : constant Natural := 3 - ((Image_Size + 3) mod 4); Mipmap_Size : constant Natural := 4 + Image_Size + Mip_Padding; Offset : constant Stream_Element_Offset := Image_Size_Index + 4; pragma Assert (Offset + Stream_Element_Offset (Image_Size) - 1 <= Bytes.Value'Last); Image_Data : constant System.Address := Bytes (Offset)'Address; -- TODO Unpack_Alignment must be 4, but Load_From_Data wants 1 | 2 | 4 -- depending on Header.Data_Type Level_Width : constant GL.Types.Size := Texture.Width (Level); Level_Height : constant GL.Types.Size := Texture.Height (Level); Level_Depth : constant GL.Types.Size := (if Cube_Map then 6 else Texture.Depth (Level)); begin if Header.Compressed then Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data); else Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth, Header.Format, Header.Data_Type, Image_Data); end if; Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size); end; end loop; end; T5 := Clock; -- Generate a full mipmap pyramid if Mipmap_Levels = 0 if Header.Mipmap_Levels = 0 then Texture.Generate_Mipmap; end if; T6 := Clock; Messages.Log (Info, "Loaded texture " & Path & " in " & Logging.Trim (Logging.Image (T6 - T1))); Messages.Log (Info, " size: " & Logging.Trim (Width'Image) & " x " & Logging.Trim (Height'Image) & " x " & Logging.Trim (Depth'Image) & ", mipmap levels:" & Levels'Image); Messages.Log (Info, " kind: " & Header.Kind'Image); if Header.Compressed then Messages.Log (Info, " format: " & Header.Compressed_Format'Image); else Messages.Log (Info, " format: " & Header.Internal_Format'Image); end if; Messages.Log (Info, " statistics:"); Messages.Log (Info, " reading file: " & Logging.Image (T2 - T1)); Messages.Log (Info, " parsing header: " & Logging.Image (T3 - T2)); Messages.Log (Info, " storage: " & Logging.Image (T4 - T3)); Messages.Log (Info, " buffers: " & Logging.Image (T5 - T4)); if Header.Mipmap_Levels = 0 then Messages.Log (Info, " generating mipmap:" & Logging.Image (T6 - T5)); end if; return Texture; end; exception when Error : Orka.KTX.Invalid_Enum_Error => declare Message : constant String := Ada.Exceptions.Exception_Message (Error); begin raise Texture_Load_Error with Path & " has " & Message; end; end Read_Texture; function Read_Texture (Location : Locations.Location_Ptr; Path : String) return GL.Objects.Textures.Texture is Start_Time : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin return Read_Texture (Location.Read_Data (Path).Get, Path, Start_Time); end Read_Texture; overriding procedure Execute (Object : KTX_Load_Job; Context : Jobs.Execution_Context'Class) is Bytes : Byte_Array_Pointers.Constant_Reference := Object.Data.Bytes.Get; Path : String renames SU.To_String (Object.Data.Path); Resource : constant Texture_Ptr := new Texture'(others => <>); begin Resource.Texture.Replace_Element (Read_Texture (Bytes, Path, Object.Data.Start_Time)); -- Register resource at the resource manager Object.Manager.Add_Resource (Path, Resource_Ptr (Resource)); end Execute; ----------------------------------------------------------------------------- -- Loader -- ----------------------------------------------------------------------------- type KTX_Loader is limited new Loaders.Loader with record Manager : Managers.Manager_Ptr; end record; overriding function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx"); overriding procedure Load (Object : KTX_Loader; Data : Loaders.Resource_Data; Enqueue : not null access procedure (Element : Jobs.Job_Ptr); Location : Locations.Location_Ptr) is Job : constant Jobs.Job_Ptr := new KTX_Load_Job' (Jobs.Abstract_Job with Data => Data, Manager => Object.Manager); begin Enqueue (Job); end Load; function Create_Loader (Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr is (new KTX_Loader'(Manager => Manager)); ----------------------------------------------------------------------------- -- Writer -- ----------------------------------------------------------------------------- procedure Write_Texture (Texture : GL.Objects.Textures.Texture; Location : Locations.Writable_Location_Ptr; Path : String) is package Textures renames GL.Objects.Textures; package Pointers is new Textures.Texture_Pointers (Byte_Pointers); Format : GL.Pixels.Format := GL.Pixels.RGBA; Data_Type : GL.Pixels.Data_Type := GL.Pixels.Float; -- Note: unused if texture is compressed Base_Level : constant := 0; use Ada.Streams; use all type GL.Low_Level.Enums.Texture_Kind; use type GL.Types.Size; Compressed : constant Boolean := Texture.Compressed; Header : Orka.KTX.Header (Compressed); function Convert (Bytes : in out GL.Types.UByte_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); procedure Free is new Ada.Unchecked_Deallocation (Object => GL.Types.UByte_Array, Name => GL.Types.UByte_Array_Access); begin for Index in Bytes'Range loop declare Target_Index : constant Stream_Element_Offset := Stream_Element_Offset (Index - Bytes'First + 1); begin Result (Target_Index) := Stream_Element (Bytes (Index)); end; end loop; Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Convert (Bytes : in out Pointers.Element_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); begin Result.all := Bytes.all; Pointers.Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Get_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : Pointers.Element_Array_Access; begin Data := Pointers.Get_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Format, Data_Type); return Convert (Data); end Get_Data; function Get_Compressed_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : GL.Types.UByte_Array_Access; begin Data := Textures.Get_Compressed_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Texture.Compressed_Format); return Convert (Data); end Get_Compressed_Data; begin Header.Kind := Texture.Kind; Header.Width := Texture.Width (Base_Level); case Texture.Kind is when Texture_3D => Header.Height := Texture.Height (Base_Level); Header.Depth := Texture.Depth (Base_Level); when Texture_2D | Texture_2D_Array | Texture_Cube_Map | Texture_Cube_Map_Array => Header.Height := Texture.Height (Base_Level); Header.Depth := 0; when Texture_1D | Texture_1D_Array => Header.Height := 0; Header.Depth := 0; when others => raise Program_Error; end case; case Texture.Kind is when Texture_1D_Array => Header.Array_Elements := Texture.Height (Base_Level); when Texture_2D_Array => Header.Array_Elements := Texture.Depth (Base_Level); when Texture_Cube_Map_Array => Header.Array_Elements := Texture.Depth (Base_Level) / 6; when Texture_1D | Texture_2D | Texture_3D | Texture_Cube_Map => Header.Array_Elements := 0; when others => raise Program_Error; end case; Header.Mipmap_Levels := Texture.Mipmap_Levels; Header.Bytes_Key_Value := 0; if Compressed then Header.Compressed_Format := Texture.Compressed_Format; else declare Internal_Format : constant GL.Pixels.Internal_Format := Texture.Internal_Format; begin Format := GL.Pixels.Queries.Get_Texture_Format (Internal_Format, Texture.Kind); Data_Type := GL.Pixels.Queries.Get_Texture_Type (Internal_Format, Texture.Kind); Header.Internal_Format := Internal_Format; Header.Format := Format; Header.Data_Type := Data_Type; end; end if; declare function Get_Level_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is (if Compressed then Get_Compressed_Data (Level) else Get_Data (Level)); Bytes : constant Byte_Array_Pointers.Pointer := Orka.KTX.Create_KTX_Bytes (Header, Get_Level_Data'Access); begin Location.Write_Data (Path, Bytes.Get); end; end Write_Texture; end Orka.Resources.Textures.KTX;
Fix loading cube map texture from KTX file
orka: Fix loading cube map texture from KTX file Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
b16e7ac28561911d21e1f86d665aa01c544da18d
matp/src/mat-formats.ads
matp/src/mat-formats.ads
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- 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.Strings.Unbounded; with MAT.Types; with MAT.Events.Targets; package MAT.Formats is type Format_Type is (BRIEF, NORMAL); -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format the time relative to the start time. function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String; -- Format the duration in seconds, milliseconds or microseconds. function Duration (Value : in MAT.Types.Target_Tick_Ref) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Mode : in Format_Type := NORMAL) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- 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.Strings.Unbounded; with MAT.Types; with MAT.Events.Targets; package MAT.Formats is type Format_Type is (BRIEF, NORMAL); -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format the time relative to the start time. function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String; -- Format the duration in seconds, milliseconds or microseconds. function Duration (Value : in MAT.Types.Target_Tick_Ref) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format an event range description. function Event (First : in MAT.Events.Targets.Probe_Event_Type; Last : in MAT.Events.Targets.Probe_Event_Type) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Mode : in Format_Type := NORMAL) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; end MAT.Formats;
Declare the Event function to print an event range
Declare the Event function to print an event range
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7a0a0a23ac310defede286a3486b68fcf2fb11a1
matp/src/mat-formats.ads
matp/src/mat-formats.ads
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- 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.Strings.Unbounded; with MAT.Types; with MAT.Memory; with MAT.Events.Tools; package MAT.Formats is type Format_Type is (BRIEF, NORMAL); -- Format the PID into a string. function Pid (Value : in MAT.Types.Target_Process_Ref) return String; -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format the memory growth size into a string. function Size (Alloced : in MAT.Types.Target_Size; Freed : in MAT.Types.Target_Size) return String; -- Format the time relative to the start time. function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String; -- Format the duration in seconds, milliseconds or microseconds. function Duration (Value : in MAT.Types.Target_Tick_Ref) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format an event range description. function Event (First : in MAT.Events.Target_Event_Type; Last : in MAT.Events.Target_Event_Type) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Target_Event_Type; Mode : in Format_Type := NORMAL) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- Format a short description of the memory allocation slot. function Slot (Value : in MAT.Types.Target_Addr; Item : in MAT.Memory.Allocation; Start_Time : in MAT.Types.Target_Tick_Ref) return String; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- 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.Strings.Unbounded; with MAT.Types; with MAT.Memory; with MAT.Events.Tools; package MAT.Formats is type Format_Type is (BRIEF, NORMAL); -- Format the PID into a string. function Pid (Value : in MAT.Types.Target_Process_Ref) return String; -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format the memory growth size into a string. function Size (Alloced : in MAT.Types.Target_Size; Freed : in MAT.Types.Target_Size) return String; -- Format the time relative to the start time. function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String; -- Format the duration in seconds, milliseconds or microseconds. function Duration (Value : in MAT.Types.Target_Tick_Ref) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format an event range description. function Event (First : in MAT.Events.Target_Event_Type; Last : in MAT.Events.Target_Event_Type) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Target_Event_Type; Mode : in Format_Type := NORMAL) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- Format the difference between two event IDs (offset). function Offset (First : in MAT.Events.Event_Id_Type; Second : in MAT.Events.Event_Id_Type) return String; -- Format a short description of the memory allocation slot. function Slot (Value : in MAT.Types.Target_Addr; Item : in MAT.Memory.Allocation; Start_Time : in MAT.Types.Target_Tick_Ref) return String; end MAT.Formats;
Declare the Offset function to format an event Id difference
Declare the Offset function to format an event Id difference
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
085dd491e9797f9242b443a06e9a2e50d25de996
regtests/ado-queries-tests.adb
regtests/ado-queries-tests.adb
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- 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 Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query", Test_Set_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Limit", Test_Set_Limit'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, 0, False); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 0, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Mysql_Driver.Get_Driver_Index, False); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Sqlite_Driver.Get_Driver_Index, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), False); T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; -- ------------------------------ -- Test the Set_Query operation. -- ------------------------------ procedure Test_Set_Query (T : in out Test) is Query : ADO.Queries.Context; begin Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (0); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; end Test_Set_Query; -- ------------------------------ -- Test the Set_Limit operation. -- ------------------------------ procedure Test_Set_Limit (T : in out Test) is Query : ADO.Queries.Context; begin Query.Set_Query ("index"); Query.Set_Limit (0, 10); Assert_Equals (T, 0, Query.Get_First_Row_Index, "Invalid first row index"); Assert_Equals (T, 10, Query.Get_Last_Row_Index, "Invalid last row index"); end Test_Set_Limit; end ADO.Queries.Tests;
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query", Test_Set_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Limit", Test_Set_Limit'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; use type ADO.Drivers.Driver_Index; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Manager, Config); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null and then Manager.Driver = Mysql_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); -- T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); -- Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. -- T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; -- ------------------------------ -- Test the Set_Query operation. -- ------------------------------ procedure Test_Set_Query (T : in out Test) is Query : ADO.Queries.Context; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Manager : Query_Manager; Config : ADO.Drivers.Connections.Configuration; begin ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (Manager); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; end Test_Set_Query; -- ------------------------------ -- Test the Set_Limit operation. -- ------------------------------ procedure Test_Set_Limit (T : in out Test) is Query : ADO.Queries.Context; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; begin ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("index"); Query.Set_Limit (0, 10); Assert_Equals (T, 0, Query.Get_First_Row_Index, "Invalid first row index"); Assert_Equals (T, 10, Query.Get_Last_Row_Index, "Invalid last row index"); end Test_Set_Limit; end ADO.Queries.Tests;
Update the tests to use the Query_Manager
Update the tests to use the Query_Manager
Ada
apache-2.0
stcarrez/ada-ado
17854861424121503c4d441435d4e626fe1ef4da
boards/HiFive1/src/hifive1.ads
boards/HiFive1/src/hifive1.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of 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 HiFive1 is end HiFive1;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with FE310.Device; use FE310.Device; with FE310.GPIO; use FE310.GPIO; package HiFive1 is HF1_Pin_0 : GPIO_Point renames P16; HF1_Pin_1 : GPIO_Point renames P17; HF1_Pin_2 : GPIO_Point renames P18; HF1_Pin_3 : GPIO_Point renames P19; -- Green LED HF1_Pin_4 : GPIO_Point renames P20; HF1_Pin_5 : GPIO_Point renames P21; -- Blue LED HF1_Pin_6 : GPIO_Point renames P22; -- Red LED HF1_Pin_7 : GPIO_Point renames P23; HF1_Pin_8 : GPIO_Point renames P00; HF1_Pin_9 : GPIO_Point renames P01; HF1_Pin_10 : GPIO_Point renames P02; HF1_Pin_11 : GPIO_Point renames P03; HF1_Pin_12 : GPIO_Point renames P04; HF1_Pin_13 : GPIO_Point renames P05; -- HF1_Pin_14 is not connected HF1_Pin_15 : GPIO_Point renames P09; HF1_Pin_16 : GPIO_Point renames P10; HF1_Pin_17 : GPIO_Point renames P11; HF1_Pin_18 : GPIO_Point renames P12; HF1_Pin_19 : GPIO_Point renames P13; end HiFive1;
Add pin definitions
HiFive1: Add pin definitions
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
ea03e30837d115558c3be63c404ff046dd705778
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Sequences; package body ADO.Sessions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class) is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is begin if Database.Impl = null then return ADO.Databases.CLOSED; end if; return Database.Impl.Database.Get_Status; end Get_Status; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); begin Log.Info ("Closing session"); if Database.Impl /= null then Database.Impl.Database.Close; Database.Impl.Counter := Database.Impl.Counter - 1; if Database.Impl.Counter = 0 then Free (Database.Impl); end if; -- -- if Database.Impl.Proxy /= null then -- Database.Impl.Proxy.Counter := Database.Impl.Proxy.Counter - 1; -- end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Get the database connection. -- ------------------------------ function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is begin Check_Session (Database); return Database.Impl.Database; end Get_Connection; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Query); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index); begin return Database.Impl.Database.Create_Statement (SQL); end; end Create_Statement; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Log.Info ("Begin transaction"); Check_Session (Database); Database.Impl.Database.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Log.Info ("Commit transaction"); Check_Session (Database); Database.Impl.Database.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Log.Info ("Rollback transaction"); Check_Session (Database); Database.Impl.Database.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Object.Impl.Counter := Object.Impl.Counter + 1; end if; end Adjust; overriding procedure Finalize (Object : in out Session) is begin if Object.Impl /= null then if Object.Impl.Counter = 1 then Object.Close; else Object.Impl.Counter := Object.Impl.Counter - 1; end if; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Sequences; package body ADO.Sessions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class) is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is begin if Database.Impl = null then return ADO.Databases.CLOSED; end if; return Database.Impl.Database.Get_Status; end Get_Status; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); begin Log.Info ("Closing session"); if Database.Impl /= null then Database.Impl.Database.Close; Database.Impl.Counter := Database.Impl.Counter - 1; if Database.Impl.Counter = 0 then Free (Database.Impl); end if; -- -- if Database.Impl.Proxy /= null then -- Database.Impl.Proxy.Counter := Database.Impl.Proxy.Counter - 1; -- end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Get the database connection. -- ------------------------------ function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is begin Check_Session (Database); return Database.Impl.Database; end Get_Connection; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Query); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index); Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Log.Info ("Begin transaction"); Check_Session (Database); Database.Impl.Database.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Log.Info ("Commit transaction"); Check_Session (Database); Database.Impl.Database.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Log.Info ("Rollback transaction"); Check_Session (Database); Database.Impl.Database.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Object.Impl.Counter := Object.Impl.Counter + 1; end if; end Adjust; overriding procedure Finalize (Object : in out Session) is begin if Object.Impl /= null then if Object.Impl.Counter = 1 then Object.Close; else Object.Impl.Counter := Object.Impl.Counter - 1; end if; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Fix parameters for XML queries - Set the query parameters for the XML query
Fix parameters for XML queries - Set the query parameters for the XML query
Ada
apache-2.0
Letractively/ada-ado
fa6ac3ac5ebe98f5900263da67c4f83428e9f8d8
awa/src/awa-audits-services.ads
awa/src/awa-audits-services.ads
----------------------------------------------------------------------- -- awa-audits-services -- AWA Audit Manager -- 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.Containers.Indefinite_Hashed_Maps; with ADO.Audits; with ADO.Sessions; package AWA.Audits.Services is -- ------------------------------ -- Event manager -- ------------------------------ -- The <b>Event_Manager</b> manages the dispatch of event to the right event queue -- or to the event action. The event manager holds a list of actions that must be -- triggered for a particular event/queue pair. Such list is created and initialized -- when the application is configured. It never changes. type Audit_Manager is limited new ADO.Audits.Audit_Manager with private; type Audit_Manager_Access is access all Audit_Manager'Class; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in ADO.Audits.Auditable_Object_Record'Class; Changes : in ADO.Audits.Audit_Array); -- Find the audit field identification number from the entity type and field name. function Get_Audit_Field (Manager : in Audit_Manager; Name : in String; Entity : in ADO.Entity_Type) return ADO.Identifier; private type Field_Key (Len : Natural) is record Entity : ADO.Entity_Type; Name : String (1 .. Len); end record; function Hash (Item : in Field_Key) return Ada.Containers.Hash_Type; package Audit_Field_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Field_Key, Element_Type => ADO.Identifier, Hash => Hash, Equivalent_Keys => "=", "=" => ADO."="); type Audit_Manager is limited new ADO.Audits.Audit_Manager with record Fields : Audit_Field_Maps.Map; end record; end AWA.Audits.Services;
----------------------------------------------------------------------- -- awa-audits-services -- AWA Audit Manager -- 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.Containers.Indefinite_Hashed_Maps; with ADO.Audits; with ADO.Sessions; limited with AWA.Applications; package AWA.Audits.Services is type Application_Access is access all AWA.Applications.Application'Class; -- ------------------------------ -- Event manager -- ------------------------------ -- The <b>Event_Manager</b> manages the dispatch of event to the right event queue -- or to the event action. The event manager holds a list of actions that must be -- triggered for a particular event/queue pair. Such list is created and initialized -- when the application is configured. It never changes. type Audit_Manager is limited new ADO.Audits.Audit_Manager with private; type Audit_Manager_Access is access all Audit_Manager'Class; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in ADO.Audits.Auditable_Object_Record'Class; Changes : in ADO.Audits.Audit_Array); -- Find the audit field identification number from the entity type and field name. function Get_Audit_Field (Manager : in Audit_Manager; Name : in String; Entity : in ADO.Entity_Type) return Integer; -- Initialize the audit manager. procedure Initialize (Manager : in out Audit_Manager; App : in Application_Access); private type Field_Key (Len : Natural) is record Entity : ADO.Entity_Type; Name : String (1 .. Len); end record; function Hash (Item : in Field_Key) return Ada.Containers.Hash_Type; package Audit_Field_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Field_Key, Element_Type => Integer, Hash => Hash, Equivalent_Keys => "="); type Audit_Manager is limited new ADO.Audits.Audit_Manager with record Fields : Audit_Field_Maps.Map; end record; end AWA.Audits.Services;
Declare the Initialize procedure to initialize the audit manager
Declare the Initialize procedure to initialize the audit manager
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5b0b4a558b5c3205044fb5a57dfa8417c61cfd26
src/asf-lifecycles-default.ads
src/asf-lifecycles-default.ads
----------------------------------------------------------------------- -- asf-lifecycles-default -- Default Lifecycle handler -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package ASF.Lifecycles.Default is type Lifecycle is new ASF.Lifecycles.Lifecycle with null record; -- Creates the phase controllers by invoking the <b>Set_Controller</b> -- procedure for each phase. This is called by <b>Initialize</b> to build -- the lifecycle handler. procedure Create_Phase_Controllers (Controller : in out Lifecycle); -- Initialize the the lifecycle handler. overriding procedure Initialize (Controller : in out Lifecycle; App : access ASF.Applications.Main.Application'Class); end ASF.Lifecycles.Default;
----------------------------------------------------------------------- -- asf-lifecycles-default -- Default Lifecycle handler -- Copyright (C) 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package ASF.Lifecycles.Default is type Lifecycle is new ASF.Lifecycles.Lifecycle with null record; -- Creates the phase controllers by invoking the <b>Set_Controller</b> -- procedure for each phase. This is called by <b>Initialize</b> to build -- the lifecycle handler. procedure Create_Phase_Controllers (Controller : in out Lifecycle); -- Initialize the the lifecycle handler. overriding procedure Initialize (Controller : in out Lifecycle; Views : access ASF.Applications.Views.View_Handler'Class); end ASF.Lifecycles.Default;
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f7e106b7fe405c1dd894289b87484ba25e5d59e0
src/security-oauth-clients.adb
src/security-oauth-clients.adb
----------------------------------------------------------------------- -- security-oauth-clients -- OAuth Client Security -- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Properties.JSON; with Util.Encoders.HMAC.SHA1; with Security.Random; package body Security.OAuth.Clients is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ Random_Generator : Security.Random.Generator; -- ------------------------------ -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. -- ------------------------------ function Create_Nonce (Bits : in Positive := 256) return String is begin -- Generate the random sequence. return Random_Generator.Generate (Bits); end Create_Nonce; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Get the id_token that was returned by the authentication process. -- ------------------------------ function Get_Id_Token (From : in OpenID_Token) return String is begin return From.Id_Token; end Get_Id_Token; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Grant_Type) return String is begin return To_String (From.Access_Token); end Get_Name; -- ------------------------------ -- Get the Authorization header to be used for accessing a protected resource. -- (See RFC 6749 7. Accessing Protected Resources) -- ------------------------------ function Get_Authorization (From : in Grant_Type) return String is begin return "Bearer " & To_String (From.Access_Token); end Get_Authorization; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Client_Id) & To_String (App.Callback); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Secret), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.STATE & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.GRANT_TYPE & "=authorization_code" & "&" & Security.OAuth.CODE & "=" & Code & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); begin Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return null; end if; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), "", "", Expires); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); return Application'Class (App).Create_Access_Token (P.Get ("access_token"), P.Get ("refresh_token", ""), P.Get ("id_token", ""), Expires); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ procedure Do_Request_Token (App : in Application; URI : in String; Data : in String; Cred : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); Cred.Access_Token := To_Unbounded_String (Content (Pos + 1 .. Last - 1)); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); Cred.Access_Token := P.Get ("access_token"); Cred.Refresh_Token := To_Unbounded_String (P.Get ("refresh_token", "")); Cred.Id_Token := To_Unbounded_String (P.Get ("id_token", "")); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return; end if; end; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end Do_Request_Token; -- ------------------------------ -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant -- ------------------------------ procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Data : constant String := Security.OAuth.GRANT_TYPE & "=password" & "&" & Security.OAuth.USERNAME & "=" & Username & "&" & Security.OAuth.PASSWORD & "=" & Password & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0} - resource owner password", URI); Do_Request_Token (App, URI, Data, Token); end Request_Token; -- ------------------------------ -- Refresh the access token. -- RFC 6749: 6. Refreshing an Access Token -- ------------------------------ procedure Refresh_Token (App : in Application; Scope : in String; Token : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Data : constant String := Security.OAuth.GRANT_TYPE & "=refresh_token" & "&" & Security.OAuth.REFRESH_TOKEN & "=" & To_String (Token.Refresh_Token) & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Refresh access token from {0}", URI); Do_Request_Token (App, URI, Data, Token); end Refresh_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin if Id_Token'Length > 0 then declare Result : constant OpenID_Token_Access := new OpenID_Token '(Len => Token'Length, Id_Len => Id_Token'Length, Refresh_Len => Refresh'Length, Access_Id => Token, Id_Token => Id_Token, Refresh_Token => Refresh); begin return Result.all'Access; end; else return new Access_Token '(Len => Token'Length, Access_Id => Token); end if; end Create_Access_Token; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth-clients -- OAuth Client Security -- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Properties.JSON; with Util.Encoders.HMAC.SHA1; with Security.Random; package body Security.OAuth.Clients is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ Random_Generator : Security.Random.Generator; -- ------------------------------ -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. -- ------------------------------ function Create_Nonce (Bits : in Positive := 256) return String is begin -- Generate the random sequence. return Random_Generator.Generate (Bits); end Create_Nonce; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Get the id_token that was returned by the authentication process. -- ------------------------------ function Get_Id_Token (From : in OpenID_Token) return String is begin return From.Id_Token; end Get_Id_Token; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Grant_Type) return String is begin return To_String (From.Access_Token); end Get_Name; -- ------------------------------ -- Get the Authorization header to be used for accessing a protected resource. -- (See RFC 6749 7. Accessing Protected Resources) -- ------------------------------ function Get_Authorization (From : in Grant_Type) return String is begin return "Bearer " & To_String (From.Access_Token); end Get_Authorization; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Client_Id) & To_String (App.Callback); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Secret), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.STATE & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.GRANT_TYPE & "=authorization_code" & "&" & Security.OAuth.CODE & "=" & Code & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); begin Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return null; end if; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), "", "", Expires); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); return Application'Class (App).Create_Access_Token (P.Get ("access_token"), P.Get ("refresh_token", ""), P.Get ("id_token", ""), Expires); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ procedure Do_Request_Token (App : in Application; URI : in String; Data : in Util.Http.Clients.Form_Data'Class; Cred : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); Cred.Access_Token := To_Unbounded_String (Content (Pos + 1 .. Last - 1)); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); Cred.Access_Token := P.Get ("access_token"); Cred.Refresh_Token := To_Unbounded_String (P.Get ("refresh_token", "")); Cred.Id_Token := To_Unbounded_String (P.Get ("id_token", "")); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return; end if; end; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end Do_Request_Token; -- ------------------------------ -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant -- ------------------------------ procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Data : constant String := Security.OAuth.GRANT_TYPE & "=password" & "&" & Security.OAuth.USERNAME & "=" & Username & "&" & Security.OAuth.PASSWORD & "=" & Password & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); Form : Util.Http.Clients.Form_Data; begin Log.Info ("Getting access token from {0} - resource owner password", URI); Form.Initialize (Size => 1024); Form.Write_Attribute (Security.OAuth.GRANT_TYPE, "password"); Form.Write_Attribute (Security.OAuth.CLIENT_ID, App.Client_Id); Form.Write_Attribute (Security.OAuth.CLIENT_SECRET, App.Secret); Form.Write_Attribute (Security.OAuth.USERNAME, Username); Form.Write_Attribute (Security.OAuth.PASSWORD, Password); Form.Write_Attribute (Security.OAuth.SCOPE, Scope); Do_Request_Token (App, URI, Form, Token); end Request_Token; -- ------------------------------ -- Refresh the access token. -- RFC 6749: 6. Refreshing an Access Token -- ------------------------------ procedure Refresh_Token (App : in Application; Scope : in String; Token : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); Form : Util.Http.Clients.Form_Data; begin Log.Info ("Refresh access token from {0}", URI); Form.Initialize (Size => 1024); Form.Write_Attribute (Security.OAuth.GRANT_TYPE, "refresh_token"); Form.Write_Attribute (Security.OAuth.REFRESH_TOKEN, Token.Refresh_Token); Form.Write_Attribute (Security.OAuth.CLIENT_ID, App.Client_Id); Form.Write_Attribute (Security.OAuth.SCOPE, Scope); Form.Write_Attribute (Security.OAuth.CLIENT_SECRET, App.Secret); Do_Request_Token (App, URI, Form, Token); end Refresh_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin if Id_Token'Length > 0 then declare Result : constant OpenID_Token_Access := new OpenID_Token '(Len => Token'Length, Id_Len => Id_Token'Length, Refresh_Len => Refresh'Length, Access_Id => Token, Id_Token => Id_Token, Refresh_Token => Refresh); begin return Result.all'Access; end; else return new Access_Token '(Len => Token'Length, Access_Id => Token); end if; end Create_Access_Token; end Security.OAuth.Clients;
Use the Util.Http.Clients.Form_Data to make a request
Use the Util.Http.Clients.Form_Data to make a request
Ada
apache-2.0
stcarrez/ada-security
8924e8e9085fde430c6e3b37be94586455e8ef6d
src/babel-files-maps.ads
src/babel-files-maps.ads
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Util.Strings; package Babel.Files.Maps is -- Babel.Base.Get_File_Map (Directory, File_Map); -- Babel.Base.Get_Directory_Map (Directory, Dir_Map); -- File_Map.Find (New_File); -- Dir_Map.Find (New_File); -- Hash string -> File package File_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => File_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype File_Map is File_Maps.Map; subtype File_Cursor is File_Maps.Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Cursor; -- Hash string -> Directory package Directory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => Directory_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype Directory_Map is Directory_Maps.Map; subtype Directory_Cursor is Directory_Maps.Cursor; type Differential_Container is new Babel.Files.File_Container with private; -- Add the file with the given name in the container. procedure Add_File (Into : in out Differential_Container; Element : in File_Type); -- Add the directory with the given name in the container. procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. function Create (Into : in Differential_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. function Create (Into : in Differential_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. function Find (From : in Differential_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. function Find (From : in Differential_Container; Name : in String) return Directory_Type; private type Differential_Container is new Babel.Files.File_Container with record Current : Directory_Type; Files : File_Map; Children : Directory_Map; end record; end Babel.Files.Maps;
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Util.Strings; package Babel.Files.Maps is -- Babel.Base.Get_File_Map (Directory, File_Map); -- Babel.Base.Get_Directory_Map (Directory, Dir_Map); -- File_Map.Find (New_File); -- Dir_Map.Find (New_File); -- Hash string -> File package File_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => File_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype File_Map is File_Maps.Map; subtype File_Cursor is File_Maps.Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Cursor; -- Hash string -> Directory package Directory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => Directory_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype Directory_Map is Directory_Maps.Map; subtype Directory_Cursor is Directory_Maps.Cursor; type Differential_Container is new Babel.Files.File_Container with private; -- Add the file with the given name in the container. overriding procedure Add_File (Into : in out Differential_Container; Element : in File_Type); -- Add the directory with the given name in the container. overriding procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. overriding function Find (From : in Differential_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. overriding function Find (From : in Differential_Container; Name : in String) return Directory_Type; private type Differential_Container is new Babel.Files.File_Container with record Current : Directory_Type; Files : File_Map; Children : Directory_Map; end record; end Babel.Files.Maps;
Mark the Differential_Container operation overriding
Mark the Differential_Container operation overriding
Ada
apache-2.0
stcarrez/babel
57bb608d1c3cca42857dc326d303c3ac204e54d1
samples/lzma_encrypt.adb
samples/lzma_encrypt.adb
----------------------------------------------------------------------- -- lzma_encrypt -- Compress and encrypt file using Util.Streams.AES -- Copyright (C) 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.Text_IO; with Ada.Command_Line; with Ada.Streams.Stream_IO; with Util.Streams.Files; with Util.Streams.AES; with Util.Streams.Buffered.Lzma; with Util.Encoders.AES; with Util.Encoders.KDF.PBKDF2_HMAC_SHA256; procedure Lzma_Encrypt is use Util.Encoders.KDF; procedure Crypt_File (Source : in String; Destination : in String; Password : in String); procedure Crypt_File (Source : in String; Destination : in String; Password : in String) is In_Stream : aliased Util.Streams.Files.File_Stream; Out_Stream : aliased Util.Streams.Files.File_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Compress : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Password_Key : constant Util.Encoders.Secret_Key := Util.Encoders.Create (Password); Salt : constant Util.Encoders.Secret_Key := Util.Encoders.Create ("fake-salt"); Key : Util.Encoders.Secret_Key (Length => Util.Encoders.AES.AES_256_Length); begin -- Generate a derived key from the password. PBKDF2_HMAC_SHA256 (Password => Password_Key, Salt => Salt, Counter => 20000, Result => Key); -- Setup file -> input and compress -> cipher -> output file streams. In_Stream.Open (Ada.Streams.Stream_IO.In_File, Source); Out_Stream.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Destination); Cipher.Produces (Output => Out_Stream'Access, Size => 32768); Cipher.Set_Key (Secret => Key, Mode => Util.Encoders.AES.ECB); Compress.Initialize (Output => Cipher'Access, Size => 4096); -- Copy input to output through the cipher. Util.Streams.Copy (From => In_Stream, Into => Compress); end Crypt_File; begin if Ada.Command_Line.Argument_Count /= 3 then Ada.Text_IO.Put_Line ("Usage: lzma_encrypt source password destination"); return; end if; Crypt_File (Source => Ada.Command_Line.Argument (1), Destination => Ada.Command_Line.Argument (3), Password => Ada.Command_Line.Argument (2)); end Lzma_Encrypt;
----------------------------------------------------------------------- -- lzma_encrypt -- Compress and encrypt file using Util.Streams.AES -- Copyright (C) 2019, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Streams.Stream_IO; with Util.Streams.Files; with Util.Streams.AES; with Util.Streams.Buffered.Lzma; with Util.Encoders.AES; with Util.Encoders.KDF.PBKDF2_HMAC_SHA256; procedure Lzma_Encrypt is use Util.Encoders.KDF; procedure Crypt_File (Source : in String; Destination : in String; Password : in String); procedure Crypt_File (Source : in String; Destination : in String; Password : in String) is In_Stream : aliased Util.Streams.Files.File_Stream; Out_Stream : aliased Util.Streams.Files.File_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Compress : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Password_Key : constant Util.Encoders.Secret_Key := Util.Encoders.Create (Password); Salt : constant Util.Encoders.Secret_Key := Util.Encoders.Create ("fake-salt"); Key : Util.Encoders.Secret_Key (Length => Util.Encoders.AES.AES_256_Length); begin -- Generate a derived key from the password. PBKDF2_HMAC_SHA256 (Password => Password_Key, Salt => Salt, Counter => 20000, Result => Key); -- Setup file -> input and compress -> cipher -> output file streams. In_Stream.Open (Ada.Streams.Stream_IO.In_File, Source); Out_Stream.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Destination); Cipher.Produces (Output => Out_Stream'Unchecked_Access, Size => 32768); Cipher.Set_Key (Secret => Key, Mode => Util.Encoders.AES.ECB); Compress.Initialize (Output => Cipher'Unchecked_Access, Size => 4096); -- Copy input to output through the cipher. Util.Streams.Copy (From => In_Stream, Into => Compress); end Crypt_File; begin if Ada.Command_Line.Argument_Count /= 3 then Ada.Text_IO.Put_Line ("Usage: lzma_encrypt source password destination"); return; end if; Crypt_File (Source => Ada.Command_Line.Argument (1), Destination => Ada.Command_Line.Argument (3), Password => Ada.Command_Line.Argument (2)); end Lzma_Encrypt;
Fix wrong 'Access usage (it was correct with previous versions of the GNAT compiler!)
Fix wrong 'Access usage (it was correct with previous versions of the GNAT compiler!)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ee8e97e2438351dfac7874b59603a6914b3be614
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-policies-roles -- Role based 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 Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return "role"; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based 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 Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return "role"; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
Implement Finalize to cleanup the security policy
Implement Finalize to cleanup the security policy
Ada
apache-2.0
stcarrez/ada-security
4dd6367c31fe8ee9e3831547f7b71d8178bb6dff
tools/druss-commands-status.adb
tools/druss-commands-status.adb
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- 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.Properties; with Util.Strings; with Druss.Gateways; package body Druss.Commands.Status is -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; N : Natural := 0; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Console.Start_Row; Console.Print_Field (F_IP_ADDR, Gateway.Ip); Console.Print_Field (F_WAN_IP, Gateway.Wan.Get ("wan.ip.address", " ")); Print_Status (Console, F_INTERNET, Gateway.Wan.Get ("wan.internet.state", " ")); Console.Print_Field (F_VOIP, Gateway.Voip.Get ("voip.0.status", " ")); Print_On_Off (Console, F_WIFI, Gateway.Wifi.Get ("wireless.radio.24.enable", " ")); if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then Console.Print_Field (F_WIFI5, ""); else Print_On_Off (Console, F_WIFI5, Gateway.Wifi.Get ("wireless.radio.5.enable", " ")); end if; Console.Print_Field (F_ACCESS_CONTROL, Gateway.IPtv.Get ("iptv.length", "x")); Console.Print_Field (F_DEVICES, Gateway.Hosts.Get ("hosts.list.length", "")); Print_Uptime (Console, F_UPTIME, Gateway.Device.Get ("device.uptime", "")); Console.End_Row; N := N + 1; Gateway.Hosts.Save_Properties ("sum-" & Util.Strings.Image (N) & ".properties"); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_IP_ADDR, "LAN IP", 16); Console.Print_Title (F_WAN_IP, "WAN IP", 16); Console.Print_Title (F_INTERNET, "Internet", 9); Console.Print_Title (F_VOIP, "VoIP", 6); Console.Print_Title (F_WIFI, "Wifi 2.4G", 10); Console.Print_Title (F_WIFI5, "Wifi 5G", 10); Console.Print_Title (F_ACCESS_CONTROL, "Parental", 10); Console.Print_Title (F_DYNDNS, "DynDNS", 10); Console.Print_Title (F_DEVICES, "Devices", 12); Console.Print_Title (F_UPTIME, "Uptime", 12); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Status; -- ------------------------------ -- Execute a status command to report information about the Bbox. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin Command.Do_Status (Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "status: give information about the Bbox status"); Console.Notice (N_HELP, "Usage: wifi {<action>} [<parameters>]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " status [IP]... Give information about the Bbox status"); end Help; end Druss.Commands.Status;
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- 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.Properties; with Util.Strings; with Druss.Gateways; package body Druss.Commands.Status is -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; N : Natural := 0; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Console.Start_Row; Console.Print_Field (F_IP_ADDR, Gateway.Ip); Console.Print_Field (F_WAN_IP, Gateway.Wan.Get ("wan.ip.address", " ")); Print_Status (Console, F_INTERNET, Gateway.Wan.Get ("wan.internet.state", " ")); Console.Print_Field (F_VOIP, Gateway.Voip.Get ("voip.0.status", " ")); Print_On_Off (Console, F_WIFI, Gateway.Wifi.Get ("wireless.radio.24.enable", " ")); if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then Console.Print_Field (F_WIFI5, ""); else Print_On_Off (Console, F_WIFI5, Gateway.Wifi.Get ("wireless.radio.5.enable", " ")); end if; Console.Print_Field (F_ACCESS_CONTROL, Gateway.IPtv.Get ("iptv.length", "x")); Console.Print_Field (F_DEVICES, Gateway.Hosts.Get ("hosts.list.length", "")); Print_Uptime (Console, F_UPTIME, Gateway.Device.Get ("device.uptime", "")); Console.End_Row; N := N + 1; Gateway.Hosts.Save_Properties ("sum-" & Util.Strings.Image (N) & ".properties"); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_IP_ADDR, "LAN IP", 16); Console.Print_Title (F_WAN_IP, "WAN IP", 16); Console.Print_Title (F_INTERNET, "Internet", 9); Console.Print_Title (F_VOIP, "VoIP", 6); Console.Print_Title (F_WIFI, "Wifi 2.4G", 10); Console.Print_Title (F_WIFI5, "Wifi 5G", 10); Console.Print_Title (F_ACCESS_CONTROL, "Parental", 10); Console.Print_Title (F_DYNDNS, "DynDNS", 10); Console.Print_Title (F_DEVICES, "Devices", 12); Console.Print_Title (F_UPTIME, "Uptime", 12); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Status; -- ------------------------------ -- Execute a status command to report information about the Bbox. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin Command.Do_Status (Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "status: give information about the Bbox status"); Console.Notice (N_HELP, "Usage: wifi {<action>} [<parameters>]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " status [IP]... Give information about the Bbox status"); end Help; end Druss.Commands.Status;
Change Help command to accept in out command
Change Help command to accept in out command
Ada
apache-2.0
stcarrez/bbox-ada-api
5902de519794d740af8590093555d73720d075b2
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Contexts.Faces; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with ASF.Streams; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; App : Applications.Main.Application; Conf : Applications.Config; begin loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin -- if Pos > 0 then -- Variables.Set_Variable (Value (1 .. Pos - 1), -- To_Object (Value (Pos + 1 .. Value'Last))); -- else -- Variables.Set_Variable (Value, To_Object(True)); -- end if; null; end; when others => exit; end case; end loop; Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); declare View_Name : constant String := Get_Argument; Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin App.Initialize (Conf); App.Dispatch (Page => View_Name, Request => Req, Response => Reply); Reply.Read_Content (Content); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content)); exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with EL.Objects; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use EL.Objects; Factory : ASF.Applications.Main.Application_Factory; App : Applications.Main.Application; Conf : Applications.Config; begin Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); App.Initialize (Conf, Factory); loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin if Pos > 0 then App.Set_Global (Name => Value (1 .. Pos - 1), Value => To_Object (Value (Pos + 1 .. Value'Last))); else App.Set_Global (Name => Value (1 .. Pos - 1), Value => To_Object(True)); end if; end; when others => exit; end case; end loop; declare View_Name : constant String := Get_Argument; Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin App.Dispatch (Page => View_Name, Request => Req, Response => Reply); Reply.Read_Content (Content); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content)); exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
Update the render example
Update the render example
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
9ad52988d37c619304521b3965f6c6be6bfb7f74
src/babel-files-maps.adb
src/babel-files-maps.adb
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Babel.Files.Maps is -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ procedure Add_File (Into : in out Differential_Container; Element : in File_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return File_Type is begin return Find (From.Known_Files, Name); end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return Directory_Type is begin return Find (From.Known_Dirs, Name); end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type) is begin Default_Container (Into).Set_Directory (Directory); Into.Known_Files.Clear; Into.Known_Dirs.Clear; end Set_Directory; -- ------------------------------ -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. -- ------------------------------ procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)) is begin Update (Container.Known_Files, Container.Known_Dirs); end Prepare; end Babel.Files.Maps;
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Babel.Files.Maps is -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Type is Pos : constant File_Cursor := From.Find (Key => Name'Unrestricted_Access); begin if File_Maps.Has_Element (Pos) then return File_Maps.Element (Pos); else return NO_FILE; end if; end Find; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ procedure Add_File (Into : in out Differential_Container; Element : in File_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return File_Type is begin return Find (From.Known_Files, Name); end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return Directory_Type is begin return Find (From.Known_Dirs, Name); end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type) is begin Default_Container (Into).Set_Directory (Directory); Into.Known_Files.Clear; Into.Known_Dirs.Clear; end Set_Directory; -- ------------------------------ -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. -- ------------------------------ procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)) is begin Update (Container.Known_Files, Container.Known_Dirs); end Prepare; end Babel.Files.Maps;
Implement the Find operation to retrieve a File_Type instance
Implement the Find operation to retrieve a File_Type instance
Ada
apache-2.0
stcarrez/babel
a6c8b4a353516852445daabb73f47d509e707b0c
src/util-files.adb
src/util-files.adb
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001, 2002, 2003, 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 Ada.Directories; with Ada.Strings.Fixed; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Text_IO; with Util.Strings.Tokenizers; package body Util.Files is -- ------------------------------ -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. -- ------------------------------ procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0) is use Ada.Streams; use Ada.Streams.Stream_IO; F : File_Type; Buffer : Stream_Element_Array (1 .. 10_000); Pos : Positive_Count := 1; Last : Stream_Element_Offset; Space : Natural; begin if Max_Size = 0 then Space := Natural'Last; else Space := Max_Size; end if; Open (Name => Path, File => F, Mode => In_File); loop Read (File => F, Item => Buffer, From => Pos, Last => Last); if Natural (Last) > Space then Last := Stream_Element_Offset (Space); end if; for I in 1 .. Last loop Append (Into, Character'Val (Buffer (I))); end loop; exit when Last < Buffer'Length; Pos := Pos + Positive_Count (Last); end loop; Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. -- ------------------------------ procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Open (File => File, Mode => Ada.Text_IO.In_File, Name => Path); while not Ada.Text_IO.End_Of_File (File) loop Process (Ada.Text_IO.Get_Line (File)); end loop; Ada.Text_IO.Close (File); end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. -- ------------------------------ procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector) is procedure Append (Line : in String); procedure Append (Line : in String) is begin Into.Append (Line); end Append; begin Read_File (Path, Append'Access); end Read_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in String) is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; F : File_Type; Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First) .. Stream_Element_Offset (Content'Last)); Dir : constant String := Containing_Directory (Path); begin if not Exists (Dir) then Create_Path (Dir); end if; Create (File => F, Name => Path); for I in Content'Range loop Buffer (Stream_Element_Offset (I)) := Stream_Element (Character'Pos (Content (I))); end loop; Write (F, Buffer); Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Write_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in Unbounded_String) is begin Write_File (Path, Ada.Strings.Unbounded.To_String (Content)); end Write_File; -- ------------------------------ -- Iterate over the search directories defined in <b>Paths</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is begin Util.Strings.Tokenizers.Iterate_Tokens (Content => Path, Pattern => ";", Process => Process, Going => Going); end Iterate_Path; -- ------------------------------ -- Find the file in one of the search directories. Each search directory -- is separated by ';' (yes, even on Unix). -- Returns the path to be used for reading the file. -- ------------------------------ function Find_File_Path (Name : String; Paths : String) return String is use Ada.Strings.Fixed; Sep_Pos : Natural; Pos : Positive := Paths'First; Last : constant Natural := Paths'Last; begin while Pos <= Last loop Sep_Pos := Index (Paths, ";", Pos); if Sep_Pos = 0 then Sep_Pos := Last; else Sep_Pos := Sep_Pos - 1; end if; declare use Ada.Directories; Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name); begin if Exists (Path) and then Kind (Path) = Ordinary_File then return Path; end if; exception when Name_Error => null; end; Pos := Sep_Pos + 2; end loop; return Name; end Find_File_Path; -- ------------------------------ -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is procedure Find_Files (Dir : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Find_Files (Dir : in String; Done : out Boolean) is use Ada.Directories; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Ent : Directory_Entry_Type; Search : Search_Type; begin Done := False; Start_Search (Search, Directory => Dir, Pattern => Pattern, Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); begin Process (Name, File_Path, Done); exit when Done; end; end loop; end Find_Files; begin Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going); end Iterate_Files_Path; -- ------------------------------ -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. -- ------------------------------ procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map) is procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean) is begin if not Into.Contains (Name) then Into.Insert (Name, File_Path); end if; Done := False; end Add_File; begin Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access); end Find_Files_Path; -- ------------------------------ -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';'. -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. -- ------------------------------ function Compose_Path (Paths : in String; Name : in String) return String is procedure Compose (Dir : in String; Done : out Boolean); Result : Unbounded_String; -- ------------------------------ -- Build the new path by checking if <b>Name</b> exists in <b>Dir</b> -- and appending the new path in the <b>Result</b>. -- ------------------------------ procedure Compose (Dir : in String; Done : out Boolean) is use Ada.Directories; Path : constant String := Util.Files.Compose (Dir, Name); begin Done := False; if Exists (Path) and then Kind (Path) = Directory then if Length (Result) > 0 then Append (Result, ';'); end if; Append (Result, Path); end if; exception when Name_Error => null; end Compose; begin Iterate_Path (Path => Paths, Process => Compose'Access); return To_String (Result); end Compose_Path; -- ------------------------------ -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Name'Length = 0 then return Directory; elsif Directory'Length = 0 then return Name; elsif Directory = "." or else Directory = "./" then if Name (Name'First) = '/' then return Compose (Directory, Name (Name'First + 1 .. Name'Last)); else return Name; end if; elsif Directory (Directory'Last) = '/' and then Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or else Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. -- ------------------------------ function Get_Relative_Path (From : in String; To : in String) return String is Result : Unbounded_String; Last : Natural := 0; begin for I in From'Range loop if I > To'Last or else From (I) /= To (I) then -- Nothing in common, return the absolute path <b>To</b>. if Last <= From'First + 1 then return To; end if; for J in Last .. From'Last - 1 loop if From (J) = '/' or From (J) = '\' then Append (Result, "../"); end if; end loop; if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then Append (Result, "../"); Append (Result, To (Last .. To'Last)); end if; return To_String (Result); elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then Last := I + 1; end if; end loop; if To'Last = From'Last or (To'Last = From'Last + 1 and (To (To'Last) = '/' or To (To'Last) = '\')) then return "."; elsif Last = 0 then return To; elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then return To (From'Last + 2 .. To'Last); else return To (Last .. To'Last); end if; end Get_Relative_Path; end Util.Files;
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001, 2002, 2003, 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 Ada.Directories; with Ada.Strings.Fixed; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Text_IO; with Util.Strings.Tokenizers; package body Util.Files is -- ------------------------------ -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. -- ------------------------------ procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0) is use Ada.Streams; use Ada.Streams.Stream_IO; F : File_Type; Buffer : Stream_Element_Array (1 .. 10_000); Pos : Positive_Count := 1; Last : Stream_Element_Offset; Space : Natural; begin if Max_Size = 0 then Space := Natural'Last; else Space := Max_Size; end if; Open (Name => Path, File => F, Mode => In_File); loop Read (File => F, Item => Buffer, From => Pos, Last => Last); if Natural (Last) > Space then Last := Stream_Element_Offset (Space); end if; for I in 1 .. Last loop Append (Into, Character'Val (Buffer (I))); end loop; exit when Last < Buffer'Length; Pos := Pos + Positive_Count (Last); end loop; Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. -- ------------------------------ procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Open (File => File, Mode => Ada.Text_IO.In_File, Name => Path); while not Ada.Text_IO.End_Of_File (File) loop Process (Ada.Text_IO.Get_Line (File)); end loop; Ada.Text_IO.Close (File); end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. -- ------------------------------ procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector) is procedure Append (Line : in String); procedure Append (Line : in String) is begin Into.Append (Line); end Append; begin Read_File (Path, Append'Access); end Read_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in String) is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; F : File_Type; Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First) .. Stream_Element_Offset (Content'Last)); Dir : constant String := Containing_Directory (Path); begin if not Exists (Dir) then Create_Path (Dir); end if; Create (File => F, Name => Path); for I in Content'Range loop Buffer (Stream_Element_Offset (I)) := Stream_Element (Character'Pos (Content (I))); end loop; Write (F, Buffer); Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Write_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in Unbounded_String) is begin Write_File (Path, Ada.Strings.Unbounded.To_String (Content)); end Write_File; -- ------------------------------ -- Iterate over the search directories defined in <b>Paths</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is begin Util.Strings.Tokenizers.Iterate_Tokens (Content => Path, Pattern => ";", Process => Process, Going => Going); end Iterate_Path; -- ------------------------------ -- Find the file in one of the search directories. Each search directory -- is separated by ';' (yes, even on Unix). -- Returns the path to be used for reading the file. -- ------------------------------ function Find_File_Path (Name : String; Paths : String) return String is use Ada.Strings.Fixed; Sep_Pos : Natural; Pos : Positive := Paths'First; Last : constant Natural := Paths'Last; begin while Pos <= Last loop Sep_Pos := Index (Paths, ";", Pos); if Sep_Pos = 0 then Sep_Pos := Last; else Sep_Pos := Sep_Pos - 1; end if; declare use Ada.Directories; Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name); begin if Exists (Path) and then Kind (Path) = Ordinary_File then return Path; end if; exception when Name_Error => null; end; Pos := Sep_Pos + 2; end loop; return Name; end Find_File_Path; -- ------------------------------ -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is procedure Find_Files (Dir : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Find_Files (Dir : in String; Done : out Boolean) is use Ada.Directories; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Ent : Directory_Entry_Type; Search : Search_Type; begin Done := False; Start_Search (Search, Directory => Dir, Pattern => Pattern, Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); begin Process (Name, File_Path, Done); exit when Done; end; end loop; end Find_Files; begin Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going); end Iterate_Files_Path; -- ------------------------------ -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. -- ------------------------------ procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map) is procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean) is begin if not Into.Contains (Name) then Into.Insert (Name, File_Path); end if; Done := False; end Add_File; begin Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access); end Find_Files_Path; -- ------------------------------ -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';'. -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. -- ------------------------------ function Compose_Path (Paths : in String; Name : in String) return String is procedure Compose (Dir : in String; Done : out Boolean); Result : Unbounded_String; -- ------------------------------ -- Build the new path by checking if <b>Name</b> exists in <b>Dir</b> -- and appending the new path in the <b>Result</b>. -- ------------------------------ procedure Compose (Dir : in String; Done : out Boolean) is use Ada.Directories; Path : constant String := Util.Files.Compose (Dir, Name); begin Done := False; if Exists (Path) and then Kind (Path) = Directory then if Length (Result) > 0 then Append (Result, ';'); end if; Append (Result, Path); end if; exception when Name_Error => null; end Compose; begin Iterate_Path (Path => Paths, Process => Compose'Access); return To_String (Result); end Compose_Path; -- ------------------------------ -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Name'Length = 0 then return Directory; elsif Directory'Length = 0 then return Name; elsif Directory = "." or else Directory = "./" then if Name (Name'First) = '/' then return Compose (Directory, Name (Name'First + 1 .. Name'Last)); else return Name; end if; elsif Directory (Directory'Last) = '/' and then Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or else Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. -- ------------------------------ function Get_Relative_Path (From : in String; To : in String) return String is Result : Unbounded_String; Last : Natural := 0; begin for I in From'Range loop if I > To'Last or else From (I) /= To (I) then -- Nothing in common, return the absolute path <b>To</b>. if Last <= From'First + 1 then return To; end if; for J in Last .. From'Last - 1 loop if From (J) = '/' or From (J) = '\' then Append (Result, "../"); end if; end loop; if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then Append (Result, "../"); Append (Result, To (Last .. To'Last)); end if; return To_String (Result); elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then Last := I + 1; end if; end loop; if To'Last = From'Last or (To'Last = From'Last + 1 and (To (To'Last) = '/' or To (To'Last) = '\')) then return "."; elsif Last = 0 then return To; elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then return To (From'Last + 2 .. To'Last); else return To (Last .. To'Last); end if; end Get_Relative_Path; end Util.Files;
Fix style compilation warning
Fix style compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1ef37526ed5dac344c48d4e30f675ead5f89c5e0
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for storage service -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Security.Contexts; with ASF.Contexts.Faces; with ASF.Contexts.Faces.Mockup; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Questions.Modules; with AWA.Questions.Beans; with AWA.Votes.Beans; with AWA.Tests.Helpers.Users; package body AWA.Questions.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list", Test_List_Questions'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean", Test_Question_Vote'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)", Test_Question_Vote'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Manager; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I append strings in Ada?"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do?"); T.Manager.Save_Question (Q); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do? " & "This is a stupid question for someone who reads this file. " & "But I need some long text for the unit test."); T.Manager.Save_Question (Q); end Test_Create_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is use AWA.Questions.Models; use type Util.Beans.Basic.Readonly_Bean_Access; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Module : AWA.Questions.Modules.Question_Module_Access; List : Util.Beans.Basic.Readonly_Bean_Access; Bean : Util.Beans.Objects.Object; Count : Natural; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Module := AWA.Questions.Modules.Get_Question_Module; List := AWA.Questions.Beans.Create_Question_List_Bean (Module); T.Assert (List /= null, "The Create_Question_List_Bean returned null"); Bean := Util.Beans.Objects.To_Object (List); T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null"); Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count; T.Assert (Count > 0, "The list of question is empty"); end Test_List_Questions; -- ------------------------------ -- Do a vote on a question through the question vote bean. -- ------------------------------ procedure Do_Vote (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context; Outcome : Ada.Strings.Unbounded.Unbounded_String; Bean : Util.Beans.Basic.Readonly_Bean_Access; Vote : AWA.Votes.Beans.Vote_Bean_Access; begin Bean := Context.Get_Bean ("questionVote"); T.Assert (Bean /= null, "The questionVote bean was not created"); T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class, "The questionVote is not a Vote_Bean"); Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access; Vote.Rating := 1; Vote.Entity_Id := 1; Vote.Vote_Up (Outcome); end Do_Vote; -- ------------------------------ -- Test anonymous user voting for a question. -- ------------------------------ procedure Test_Question_Vote_Anonymous (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Do_Vote (T); T.Fail ("Anonymous users should not be allowed to vote"); exception when AWA.Permissions.NO_PERMISSION => null; end Test_Question_Vote_Anonymous; -- ------------------------------ -- Test voting for a question. -- ------------------------------ procedure Test_Question_Vote (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Do_Vote (T); end Test_Question_Vote; end AWA.Questions.Services.Tests;
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for storage service -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Security.Contexts; with ASF.Contexts.Faces; with ASF.Contexts.Faces.Mockup; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Questions.Modules; with AWA.Questions.Beans; with AWA.Votes.Beans; with AWA.Tests.Helpers.Users; package body AWA.Questions.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list", Test_List_Questions'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean", Test_Question_Vote'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)", Test_Question_Vote'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Manager; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I append strings in Ada?"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do?"); T.Manager.Save_Question (Q); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do? " & "This is a stupid question for someone who reads this file. " & "But I need some long text for the unit test."); T.Manager.Save_Question (Q); end Test_Create_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is use AWA.Questions.Models; use type Util.Beans.Basic.Readonly_Bean_Access; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Module : AWA.Questions.Modules.Question_Module_Access; List : Util.Beans.Basic.Readonly_Bean_Access; Bean : Util.Beans.Objects.Object; Count : Natural; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Module := AWA.Questions.Modules.Get_Question_Module; List := AWA.Questions.Beans.Create_Question_List_Bean (Module); T.Assert (List /= null, "The Create_Question_List_Bean returned null"); Bean := Util.Beans.Objects.To_Object (List); T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null"); Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count; T.Assert (Count > 0, "The list of question is empty"); end Test_List_Questions; -- ------------------------------ -- Do a vote on a question through the question vote bean. -- ------------------------------ procedure Do_Vote (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context; Outcome : Ada.Strings.Unbounded.Unbounded_String; Bean : Util.Beans.Basic.Readonly_Bean_Access; Vote : AWA.Votes.Beans.Vote_Bean_Access; begin Context.Set_Parameter ("id", "1"); Bean := Context.Get_Bean ("questionVote"); T.Assert (Bean /= null, "The questionVote bean was not created"); T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class, "The questionVote is not a Vote_Bean"); Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access; Vote.Rating := 1; Vote.Entity_Id := 1; Vote.Vote_Up (Outcome); end Do_Vote; -- ------------------------------ -- Test anonymous user voting for a question. -- ------------------------------ procedure Test_Question_Vote_Anonymous (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Do_Vote (T); T.Fail ("Anonymous users should not be allowed to vote"); exception when AWA.Permissions.NO_PERMISSION => null; end Test_Question_Vote_Anonymous; -- ------------------------------ -- Test voting for a question. -- ------------------------------ procedure Test_Question_Vote (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Do_Vote (T); end Test_Question_Vote; end AWA.Questions.Services.Tests;
Add the request parameter to simulate the ajax vote action
Add the request parameter to simulate the ajax vote action
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
011b6a73a45691fb321f84e08209b782cc0ee42d
src/babel_main.adb
src/babel_main.adb
with GNAT.IO; use GNAT.IO; with Babel; with Babel.Files; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Encoders; with Util.Encoders.Base16; with Babel.Filters; with Babel.Files.Buffers; with Babel.Stores.Local; with Babel.Strategies.Default; with Babel.Strategies.Workers; procedure babel_main is use Ada.Strings.Unbounded; Dir : Babel.Files.Directory_Type; Hex_Encoder : Util.Encoders.Base16.Encoder; Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type; Local : aliased Babel.Stores.Local.Local_Store_Type; Backup : aliased Babel.Strategies.Default.Default_Strategy_Type; Buffers : aliased Babel.Files.Buffers.Buffer_Pools.Pool; Store : aliased Babel.Stores.Local.Local_Store_Type; -- -- procedure Print_Sha (Path : in String; -- File : in out Babel.Files.File) is -- Sha : constant String := Hex_Encoder.Transform (File.SHA1); -- begin -- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha); -- end Print_Sha; procedure Do_Backup (Count : in Positive) is Workers : Babel.Strategies.Workers.Worker_Type (Count); begin Babel.Strategies.Workers.Start (Workers, Backup'Unchecked_Access); Backup.Scan ("."); end Do_Backup; begin Exclude.Add_Exclude (".svn"); Exclude.Add_Exclude ("obj"); Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 1_000_000); Store.Set_Root_Directory ("/tmp/babel-store"); Local.Set_Root_Directory ("."); Backup.Set_Filters (Exclude'Unchecked_Access); Backup.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access); Backup.Set_Buffers (Buffers'Unchecked_Access); Put_Line ("Size: " & Natural'Image (Ada.Directories.File_Size'Size)); Do_Backup (2); -- Bkp.Files.Scan (".", Dir); -- Bkp.Files.Iterate_Files (".", Dir, 10, Print_Sha'Access); -- Put_Line ("Total size: " & Ada.Directories.File_Size'Image (Dir.Tot_Size)); -- Put_Line ("File count: " & Natural'Image (Dir.Tot_Files)); -- Put_Line ("Dir count: " & Natural'Image (Dir.Tot_Dirs)); end babel_main;
with GNAT.IO; use GNAT.IO; with Babel; with Babel.Files; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Encoders; with Util.Encoders.Base16; with Babel.Filters; with Babel.Files.Buffers; with Babel.Files.Queues; with Babel.Stores.Local; with Babel.Strategies.Default; with Babel.Strategies.Workers; procedure babel_main is use Ada.Strings.Unbounded; Dir : Babel.Files.Directory_Type; Hex_Encoder : Util.Encoders.Base16.Encoder; Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type; Local : aliased Babel.Stores.Local.Local_Store_Type; Backup : aliased Babel.Strategies.Default.Default_Strategy_Type; Buffers : aliased Babel.Files.Buffers.Buffer_Pools.Pool; Store : aliased Babel.Stores.Local.Local_Store_Type; -- -- procedure Print_Sha (Path : in String; -- File : in out Babel.Files.File) is -- Sha : constant String := Hex_Encoder.Transform (File.SHA1); -- begin -- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha); -- end Print_Sha; procedure Do_Backup (Count : in Positive) is Workers : Babel.Strategies.Workers.Worker_Type (Count); Container : Babel.Files.Default_Container; Queue : Babel.Files.Queues.Directory_Queue; begin Babel.Files.Queues.Add_Directory (Queue, Dir); Babel.Strategies.Workers.Start (Workers, Backup'Unchecked_Access); Backup.Scan (Queue, Container); end Do_Backup; begin Dir := Babel.Files.Allocate (Name => ".", Dir => Babel.Files.NO_DIRECTORY); Exclude.Add_Exclude (".svn"); Exclude.Add_Exclude ("obj"); Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 1_000_000); Store.Set_Root_Directory ("/tmp/babel-store"); Local.Set_Root_Directory ("."); Backup.Set_Filters (Exclude'Unchecked_Access); Backup.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access); Backup.Set_Buffers (Buffers'Unchecked_Access); Put_Line ("Size: " & Natural'Image (Ada.Directories.File_Size'Size)); Do_Backup (2); -- Bkp.Files.Scan (".", Dir); -- Bkp.Files.Iterate_Files (".", Dir, 10, Print_Sha'Access); -- Put_Line ("Total size: " & Ada.Directories.File_Size'Image (Dir.Tot_Size)); -- Put_Line ("File count: " & Natural'Image (Dir.Tot_Files)); -- Put_Line ("Dir count: " & Natural'Image (Dir.Tot_Dirs)); end babel_main;
Update to use the new Scan procedure
Update to use the new Scan procedure
Ada
apache-2.0
stcarrez/babel
b34039535072741f3e573c925ec92938c8f13100
matp/src/mat-targets-probes.adb
matp/src/mat-targets-probes.adb
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Bfd; with ELF; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type) is use type MAT.Types.Target_Addr; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Event.Addr := Heap.Start_Addr; Event.Size := Heap.Size; Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); Probe.Target.Process.Endian := MAT.Readers.Get_Endian (Msg); end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; Offset : MAT.Types.Target_Addr; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; if Ada.Strings.Unbounded.Length (Path) = 0 then Region.Path := Probe.Target.Process.Path; Offset := 0; else Region.Path := Path; Offset := Region.Start_Addr; end if; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); -- When auto-symbol loading is enabled, load the symbols associated with the -- shared libraries used by the program. if Probe.Target.Options.Load_Symbols then begin Probe.Target.Process.Symbols.Value.Load_Symbols (Region, Offset); exception when Bfd.OPEN_ERROR => Probe.Target.Console.Error ("Cannot open symbol library file '" & Ada.Strings.Unbounded.To_String (Region.Path) & "'"); end; end if; end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Target_Event_Type) is use type MAT.Events.Probe_Index_Type; begin if Event.Index = MAT.Events.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in out MAT.Events.Target_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Bfd; with ELF; with MAT.Formats; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type) is use type MAT.Types.Target_Addr; use type MAT.Events.Attribute_Type; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Event.Addr := Heap.Start_Addr; Event.Size := Heap.Size; Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); Probe.Target.Process.Endian := MAT.Readers.Get_Endian (Msg); if Probe.Manager.Get_Address_Size = MAT.Events.T_UINT32 then MAT.Formats.Set_Address_Size (8); else MAT.Formats.Set_Address_Size (16); end if; end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Target_Event_Type) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; Offset : MAT.Types.Target_Addr; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; if Ada.Strings.Unbounded.Length (Path) = 0 then Region.Path := Probe.Target.Process.Path; Offset := 0; else Region.Path := Path; Offset := Region.Start_Addr; end if; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); -- When auto-symbol loading is enabled, load the symbols associated with the -- shared libraries used by the program. if Probe.Target.Options.Load_Symbols then begin Probe.Target.Process.Symbols.Value.Load_Symbols (Region, Offset); exception when Bfd.OPEN_ERROR => Probe.Target.Console.Error ("Cannot open symbol library file '" & Ada.Strings.Unbounded.To_String (Region.Path) & "'"); end; end if; end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Target_Event_Type) is use type MAT.Events.Probe_Index_Type; begin if Event.Index = MAT.Events.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in out MAT.Events.Target_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
Configure the address format after we know addresses are 32-bit or 64-bit wide
Configure the address format after we know addresses are 32-bit or 64-bit wide
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2b4819786e04c60bc5360c9d7ffd34f6f2d22452
src/asm-intrinsic/util-concurrent-counters.adb
src/asm-intrinsic/util-concurrent-counters.adb
----------------------------------------------------------------------- -- util-concurrent -- Concurrent Counters -- Copyright (C) 2009, 2010, 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. ----------------------------------------------------------------------- package body Util.Concurrent.Counters is function Sync_Sub_And_Fetch (Ptr : access Interfaces.Unsigned_32; Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32; pragma Import (Intrinsic, Sync_Sub_And_Fetch, External_Name => "__sync_sub_and_fetch_4"); function Sync_Fetch_And_Add (Ptr : access Interfaces.Unsigned_32; Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32; pragma Import (Intrinsic, Sync_Fetch_And_Add, External_Name => "__sync_fetch_and_add_4"); procedure Sync_Add (Ptr : access Interfaces.Unsigned_32; Value : in Interfaces.Unsigned_32); pragma Import (Intrinsic, Sync_Add, External_Name => "__sync_add_and_fetch_4"); procedure Sync_Sub (Ptr : access Interfaces.Unsigned_32; Value : in Interfaces.Unsigned_32); pragma Import (Intrinsic, Sync_Sub, External_Name => "__sync_sub_and_fetch_4"); -- ------------------------------ -- Increment the counter atomically. -- ------------------------------ procedure Increment (C : in out Counter) is begin Sync_Add (C.Value'Unrestricted_Access, 1); end Increment; -- ------------------------------ -- Increment the counter atomically and return the value before increment. -- ------------------------------ procedure Increment (C : in out Counter; Value : out Integer) is begin Value := Integer (Sync_Fetch_And_Add (C.Value'Unrestricted_Access, 1)); end Increment; -- ------------------------------ -- Decrement the counter atomically. -- ------------------------------ procedure Decrement (C : in out Counter) is use type Interfaces.Unsigned_32; begin Sync_Sub (C.Value'Unrestricted_Access, 1); end Decrement; -- ------------------------------ -- Decrement the counter atomically and return a status. -- ------------------------------ procedure Decrement (C : in out Counter; Is_Zero : out Boolean) is use type Interfaces.Unsigned_32; Value : Interfaces.Unsigned_32; begin Value := Sync_Sub_And_Fetch (C.Value'Unrestricted_Access, 1); Is_Zero := Value = 0; end Decrement; -- ------------------------------ -- Get the counter value -- ------------------------------ function Value (C : in Counter) return Integer is begin return Integer (C.Value); end Value; end Util.Concurrent.Counters;
----------------------------------------------------------------------- -- util-concurrent -- Concurrent Counters -- Copyright (C) 2009, 2010, 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. ----------------------------------------------------------------------- package body Util.Concurrent.Counters is function Sync_Sub_And_Fetch (Ptr : access Interfaces.Unsigned_32; Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32; pragma Import (Intrinsic, Sync_Sub_And_Fetch, External_Name => "__sync_sub_and_fetch_4"); function Sync_Fetch_And_Add (Ptr : access Interfaces.Unsigned_32; Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32; pragma Import (Intrinsic, Sync_Fetch_And_Add, External_Name => "__sync_fetch_and_add_4"); procedure Sync_Add (Ptr : access Interfaces.Unsigned_32; Value : in Interfaces.Unsigned_32); pragma Import (Intrinsic, Sync_Add, External_Name => "__sync_add_and_fetch_4"); procedure Sync_Sub (Ptr : access Interfaces.Unsigned_32; Value : in Interfaces.Unsigned_32); pragma Import (Intrinsic, Sync_Sub, External_Name => "__sync_sub_and_fetch_4"); -- ------------------------------ -- Increment the counter atomically. -- ------------------------------ procedure Increment (C : in out Counter) is begin Sync_Add (C.Value'Unrestricted_Access, 1); end Increment; -- ------------------------------ -- Increment the counter atomically and return the value before increment. -- ------------------------------ procedure Increment (C : in out Counter; Value : out Integer) is begin Value := Integer (Sync_Fetch_And_Add (C.Value'Unrestricted_Access, 1)); end Increment; -- ------------------------------ -- Decrement the counter atomically. -- ------------------------------ procedure Decrement (C : in out Counter) is begin Sync_Sub (C.Value'Unrestricted_Access, 1); end Decrement; -- ------------------------------ -- Decrement the counter atomically and return a status. -- ------------------------------ procedure Decrement (C : in out Counter; Is_Zero : out Boolean) is use type Interfaces.Unsigned_32; Value : Interfaces.Unsigned_32; begin Value := Sync_Sub_And_Fetch (C.Value'Unrestricted_Access, 1); Is_Zero := Value = 0; end Decrement; -- ------------------------------ -- Get the counter value -- ------------------------------ function Value (C : in Counter) return Integer is begin return Integer (C.Value); end Value; end Util.Concurrent.Counters;
Remove unecessary use type clause in Decrement
Remove unecessary use type clause in Decrement
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
99f23b45f6ac03ee7252ae3d1c5379178d782ce9
regtests/ado-schemas-tests.adb
regtests/ado-schemas-tests.adb
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- 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 Util.Test_Caller; with Util.Strings.Transforms; with ADO.Sessions; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 15, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; end ADO.Schemas.Tests;
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- 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 Util.Test_Caller; with Util.Strings.Vectors; with Util.Strings.Transforms; with ADO.Configs; with ADO.Schemas.Databases; with ADO.Sessions; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database", Test_Create_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 15, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Msg : Util.Strings.Vectors.Vector; Cfg : constant Configs.Configuration := Configs.Configuration (Regtests.Get_Controller); Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Cfg.Get_Driver & ".sql"; begin ADO.Schemas.Databases.Create_Database (Session => S, Config => Cfg, Schema_Path => Path, Messages => Msg); end Test_Create_Schema; end ADO.Schemas.Tests;
Implement Test_Create_Schema procedure and register the new test to check the Create_Database operation
Implement Test_Create_Schema procedure and register the new test to check the Create_Database operation
Ada
apache-2.0
stcarrez/ada-ado
77ea637fc006e2e31b0c665a4fb3e8aba0385645
regtests/el-contexts-tests.ads
regtests/el-contexts-tests.ads
----------------------------------------------------------------------- -- el-contexts-tests - Tests the EL contexts -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package EL.Contexts.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Context_Properties (T : in out Test); end EL.Contexts.Tests;
----------------------------------------------------------------------- -- el-contexts-tests - Tests the EL contexts -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package EL.Contexts.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Context_Properties (T : in out Test); -- Test the thread local EL context. procedure Test_Context_TLS (T : in out Test); end EL.Contexts.Tests;
Declare the Test_Context_TLS procedure
Declare the Test_Context_TLS procedure
Ada
apache-2.0
stcarrez/ada-el
ff4fccf549d4d357a404c92072633a4df55f49d5
src/babel-files-signatures.adb
src/babel-files-signatures.adb
----------------------------------------------------------------------- -- babel-files-signatures -- Signatures calculation -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; package body Babel.Files.Signatures is -- ------------------------------ -- Compute the SHA1 signature of the data stored in the buffer. -- ------------------------------ procedure Sha1 (Buffer : in Babel.Files.Buffers.Buffer; Result : out Util.Encoders.SHA1.Hash_Array) is Ctx : Util.Encoders.SHA1.Context; begin Util.Encoders.SHA1.Update (Ctx, Buffer.Data (Buffer.Data'First .. Buffer.Last)); Util.Encoders.SHA1.Finish (Ctx, Result); end Sha1; -- ------------------------------ -- Write the SHA1 checksum for the files stored in the map. -- ------------------------------ procedure Save_Checksum (Path : in String; Files : in Babel.Files.Maps.File_Map) is Checksum : Ada.Text_IO.File_Type; procedure Write_Checksum (Position : in Babel.Files.Maps.File_Cursor) is File : constant Babel.Files.File_Type := Babel.Files.Maps.File_Maps.Element (Position); SHA1 : constant String := Babel.Files.Get_SHA1 (File); Path : constant String := Babel.Files.Get_Path (File); begin Ada.Text_IO.Put (Checksum, Path); Ada.Text_IO.Put (Checksum, ": "); Ada.Text_IO.Put_Line (Checksum, SHA1); end Write_Checksum; begin Ada.Text_IO.Create (File => Checksum, Name => Path); Files.Iterate (Write_Checksum'Access); Ada.Text_IO.Close (File => Checksum); end Save_Checksum; end Babel.Files.Signatures;
----------------------------------------------------------------------- -- babel-files-signatures -- Signatures calculation -- Copyright (C) 2014 , 2015, 2016 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; package body Babel.Files.Signatures is -- ------------------------------ -- Compute the SHA1 signature of the data stored in the buffer. -- ------------------------------ procedure Sha1 (Buffer : in Babel.Files.Buffers.Buffer; Result : out Util.Encoders.SHA1.Hash_Array) is Ctx : Util.Encoders.SHA1.Context; begin Util.Encoders.SHA1.Update (Ctx, Buffer.Data (Buffer.Data'First .. Buffer.Last)); Util.Encoders.SHA1.Finish (Ctx, Result); end Sha1; -- ------------------------------ -- Compute the SHA1 signature of the file stream. -- ------------------------------ procedure Sha1 (Stream : in Babel.Streams.Refs.Stream_Ref; Result : out Util.Encoders.SHA1.Hash_Array) is use type Babel.Files.Buffers.Buffer_Access; From_Stream : constant Babel.Streams.Stream_Access := Stream.Value; Buffer : Babel.Files.Buffers.Buffer_Access; Ctx : Util.Encoders.SHA1.Context; begin From_Stream.Rewind; loop From_Stream.Read (Buffer); exit when Buffer = null; Util.Encoders.SHA1.Update (Ctx, Buffer.Data (Buffer.Data'First .. Buffer.Last)); end loop; Util.Encoders.SHA1.Finish (Ctx, Result); end Sha1; -- ------------------------------ -- Write the SHA1 checksum for the files stored in the map. -- ------------------------------ procedure Save_Checksum (Path : in String; Files : in Babel.Files.Maps.File_Map) is Checksum : Ada.Text_IO.File_Type; procedure Write_Checksum (Position : in Babel.Files.Maps.File_Cursor) is File : constant Babel.Files.File_Type := Babel.Files.Maps.File_Maps.Element (Position); SHA1 : constant String := Babel.Files.Get_SHA1 (File); Path : constant String := Babel.Files.Get_Path (File); begin Ada.Text_IO.Put (Checksum, Path); Ada.Text_IO.Put (Checksum, ": "); Ada.Text_IO.Put_Line (Checksum, SHA1); end Write_Checksum; begin Ada.Text_IO.Create (File => Checksum, Name => Path); Files.Iterate (Write_Checksum'Access); Ada.Text_IO.Close (File => Checksum); end Save_Checksum; end Babel.Files.Signatures;
Implement the Sha1 procedure with a stream
Implement the Sha1 procedure with a stream
Ada
apache-2.0
stcarrez/babel
8ab02f21c55268f7c3344b7ce5cdf3b0f7738c92
src/asf-filters.ads
src/asf-filters.ads
----------------------------------------------------------------------- -- asf.filters -- ASF Filters -- Copyright (C) 2010, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Servlets; -- The <b>ASF.Filters</b> package defines the servlet filter -- interface described in Java Servlet Specification, JSR 315, 6. Filtering. -- package ASF.Filters is -- ------------------------------ -- Filter interface -- ------------------------------ -- The <b>Filter</b> interface defines one mandatory procedure through -- which the request/response pair are passed. -- -- The <b>Filter</b> instance must be registered in the <b>Servlet_Registry</b> -- by using the <b>Add_Filter</b> procedure. The same filter instance is used -- to process multiple requests possibly at the same time. type Filter is limited interface; type Filter_Access is access all Filter'Class; type Filter_List is array (Natural range <>) of Filter_Access; type Filter_List_Access is access all Filter_List; -- The Do_Filter method of the Filter is called by the container each time -- a request/response pair is passed through the chain due to a client request -- for a resource at the end of the chain. The Filter_Chain passed in to this -- method allows the Filter to pass on the request and response to the next -- entity in the chain. -- -- A typical implementation of this method would follow the following pattern: -- 1. Examine the request -- 2. Optionally wrap the request object with a custom implementation to -- filter content or headers for input filtering -- 3. Optionally wrap the response object with a custom implementation to -- filter content or headers for output filtering -- 4. Either invoke the next entity in the chain using the FilterChain -- object (chain.Do_Filter()), -- or, not pass on the request/response pair to the next entity in the -- filter chain to block the request processing -- 5. Directly set headers on the response after invocation of the next -- entity in the filter chain. procedure Do_Filter (F : in Filter; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is abstract; -- Called by the servlet container to indicate to a filter that the filter -- instance is being placed into service. procedure Initialize (Server : in out Filter; Context : in ASF.Servlets.Servlet_Registry'Class) is null; end ASF.Filters;
----------------------------------------------------------------------- -- asf.filters -- ASF Filters -- Copyright (C) 2010, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Servlets; -- The <b>ASF.Filters</b> package defines the servlet filter -- interface described in Java Servlet Specification, JSR 315, 6. Filtering. -- package ASF.Filters is -- ------------------------------ -- Filter interface -- ------------------------------ -- The <b>Filter</b> interface defines one mandatory procedure through -- which the request/response pair are passed. -- -- The <b>Filter</b> instance must be registered in the <b>Servlet_Registry</b> -- by using the <b>Add_Filter</b> procedure. The same filter instance is used -- to process multiple requests possibly at the same time. type Filter is limited interface; type Filter_Access is access all Filter'Class; type Filter_List is array (Natural range <>) of Filter_Access; type Filter_List_Access is access all Filter_List; -- The Do_Filter method of the Filter is called by the container each time -- a request/response pair is passed through the chain due to a client request -- for a resource at the end of the chain. The Filter_Chain passed in to this -- method allows the Filter to pass on the request and response to the next -- entity in the chain. -- -- A typical implementation of this method would follow the following pattern: -- 1. Examine the request -- 2. Optionally wrap the request object with a custom implementation to -- filter content or headers for input filtering -- 3. Optionally wrap the response object with a custom implementation to -- filter content or headers for output filtering -- 4. Either invoke the next entity in the chain using the FilterChain -- object (chain.Do_Filter()), -- or, not pass on the request/response pair to the next entity in the -- filter chain to block the request processing -- 5. Directly set headers on the response after invocation of the next -- entity in the filter chain. procedure Do_Filter (F : in Filter; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is abstract; -- Called by the servlet container to indicate to a filter that the filter -- instance is being placed into service. procedure Initialize (Server : in out Filter; Config : in ASF.Servlets.Filter_Config) is null; end ASF.Filters;
Change the Initialize procedure to use a Filter_Config parameter type (this is much conform to the Java Servlet Specification, JSR 315, 6. Filtering)
Change the Initialize procedure to use a Filter_Config parameter type (this is much conform to the Java Servlet Specification, JSR 315, 6. Filtering)
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
0ef0850d3383ed5df4ba03346066e8499a25394b
awa/src/awa-applications.adb
awa/src/awa-applications.adb
----------------------------------------------------------------------- -- awa-applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ADO.Drivers; with ADO.Sessions.Sources; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with Security.Policies; with ASF.Server; with ASF.Servlets; with AWA.Services.Contexts; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; with AWA.Helpers.Selectors; with AWA.Permissions.Services; with AWA.Permissions.Beans; package body AWA.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Initializing application"); Ctx.Set_Context (App'Unchecked_Access, null); AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); -- Load the application configuration before any module. Application'Class (App).Load_Configuration (App.Get_Config (P_Config_File.P)); -- Register the application modules and load their configuration. Application'Class (App).Initialize_Modules; -- Load the plugin application configuration after the module are configured. Application'Class (App).Load_Configuration (App.Get_Config (P_Plugin_Config_File.P)); end Initialize; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is Connection : ADO.Sessions.Sources.Data_Source; begin Log.Info ("Initializing configuration"); if Conf.Get ("app.modules.dir", "") = "" then Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}"); end if; if Conf.Get ("bundle.dir", "") = "" then Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}"); end if; if Conf.Get ("ado.queries.paths", "") = "" then Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}"); end if; ASF.Applications.Main.Application (App).Initialize_Config (Conf); ADO.Drivers.Initialize (Conf); Connection.Set_Connection (Conf.Get (P_Database.P)); Connection.Set_Property ("ado.queries.paths", Conf.Get ("ado.queries.paths", "")); Connection.Set_Property ("ado.queries.load", Conf.Get ("ado.queries.load", "")); App.DB_Factory.Create (Connection); App.DB_Factory.Set_Audit_Manager (App.Audits'Unchecked_Access); App.Events.Initialize (App'Unchecked_Access); AWA.Modules.Initialize (App.Modules, Conf); App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean", AWA.Helpers.Selectors.Create_Select_List_Bean'Access); App.Register_Class ("AWA.Permissions.Beans.Permission_Bean", AWA.Permissions.Beans.Create_Permission_Bean'Access); end Initialize_Config; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Application) is begin Log.Info ("Initializing application servlets"); ASF.Applications.Main.Application (App).Initialize_Servlets; end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin Log.Info ("Initializing application filters"); ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is procedure Register_Functions is new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions); begin Log.Info ("Initializing application components"); ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); Register_Functions (App); end Initialize_Components; -- ------------------------------ -- Read the application configuration file <b>awa.xml</b>. This is called after the servlets -- and filters have been registered in the application but before the module registration. -- ------------------------------ procedure Load_Configuration (App : in out Application; Files : in String) is procedure Load_Config (File : in String; Done : out Boolean); Paths : constant String := App.Get_Config (P_Module_Dir.P); Ctx : aliased EL.Contexts.Default.Default_Context; procedure Load_Config (File : in String; Done : out Boolean) is Path : constant String := Util.Files.Find_File_Path (File, Paths); begin Done := False; AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access, True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Config; begin Util.Files.Iterate_Path (Files, Load_Config'Access); end Load_Configuration; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Start the application. This is called by the server container when the server is started. -- ------------------------------ overriding procedure Start (App : in out Application) is Manager : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager; begin -- Start the security manager. AWA.Permissions.Services.Permission_Manager'Class (Manager.all).Start; -- Start the event service. App.Events.Start; -- Start the application. ASF.Applications.Main.Application (App).Start; -- Dump the route and filters to help in configuration issues. App.Dump_Routes (Util.Log.INFO_LEVEL); end Start; -- ------------------------------ -- Close the application. -- ------------------------------ overriding procedure Close (App : in out Application) is begin App.Events.Stop; ASF.Applications.Main.Application (App).Close; end Close; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is begin AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); end Register; -- ------------------------------ -- Send the event in the application event queues. -- ------------------------------ procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class) is begin App.Events.Send (Event); end Send_Event; -- ------------------------------ -- Execute the <tt>Process</tt> procedure with the event manager used by the application. -- ------------------------------ procedure Do_Event_Manager (App : in out Application; Process : access procedure (Events : in out AWA.Events.Services.Event_Manager)) is begin Process (App.Events); end Do_Event_Manager; -- ------------------------------ -- Initialize the parser represented by <b>Parser</b> to recognize the configuration -- that are specific to the plugins that have been registered so far. -- ------------------------------ procedure Initialize_Parser (App : in out Application'Class; Parser : in out Util.Serialize.IO.Parser'Class) is procedure Process (Module : in out AWA.Modules.Module'Class); procedure Process (Module : in out AWA.Modules.Module'Class) is begin Module.Initialize_Parser (Parser); end Process; begin AWA.Modules.Iterate (App.Modules, Process'Access); end Initialize_Parser; -- ------------------------------ -- Get the current application from the servlet context or service context. -- ------------------------------ function Current return Application_Access is use type AWA.Services.Contexts.Service_Context_Access; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; begin if Ctx /= null then return Ctx.Get_Application; end if; -- If there is no service context, look in the servlet current context. declare use type ASF.Servlets.Servlet_Registry_Access; Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current; begin if Ctx = null then Log.Warn ("There is no service context"); return null; end if; if not (Ctx.all in AWA.Applications.Application'Class) then Log.Warn ("The servlet context is not an application"); return null; end if; return AWA.Applications.Application'Class (Ctx.all)'Access; end; end Current; end AWA.Applications;
----------------------------------------------------------------------- -- awa-applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ADO.Drivers; with ADO.Sessions.Sources; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with Security.Policies; with ASF.Server; with ASF.Servlets; with AWA.Services.Contexts; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; with AWA.Helpers.Selectors; with AWA.Permissions.Services; with AWA.Permissions.Beans; package body AWA.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Initializing application"); Ctx.Set_Context (App'Unchecked_Access, null); AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); -- Load the application configuration before any module. Application'Class (App).Load_Configuration (App.Get_Config (P_Config_File.P)); -- Register the application modules and load their configuration. Application'Class (App).Initialize_Modules; -- Load the plugin application configuration after the module are configured. Application'Class (App).Load_Configuration (App.Get_Config (P_Plugin_Config_File.P)); end Initialize; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is Connection : ADO.Sessions.Sources.Data_Source; begin Log.Info ("Initializing configuration"); if Conf.Get ("app.modules.dir", "") = "" then Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}"); end if; if Conf.Get ("bundle.dir", "") = "" then Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}"); end if; if Conf.Get ("ado.queries.paths", "") = "" then Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}"); end if; ASF.Applications.Main.Application (App).Initialize_Config (Conf); ADO.Drivers.Initialize (Conf); Connection.Set_Connection (Conf.Get (P_Database.P)); Connection.Set_Property ("ado.queries.paths", Conf.Get ("ado.queries.paths", "")); Connection.Set_Property ("ado.queries.load", Conf.Get ("ado.queries.load", "")); App.DB_Factory.Create (Connection); App.DB_Factory.Set_Audit_Manager (App.Audits'Unchecked_Access); App.Audits.Initialize (App'Unchecked_Access); App.Events.Initialize (App'Unchecked_Access); AWA.Modules.Initialize (App.Modules, Conf); App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean", AWA.Helpers.Selectors.Create_Select_List_Bean'Access); App.Register_Class ("AWA.Permissions.Beans.Permission_Bean", AWA.Permissions.Beans.Create_Permission_Bean'Access); end Initialize_Config; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Application) is begin Log.Info ("Initializing application servlets"); ASF.Applications.Main.Application (App).Initialize_Servlets; end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin Log.Info ("Initializing application filters"); ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is procedure Register_Functions is new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions); begin Log.Info ("Initializing application components"); ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); Register_Functions (App); end Initialize_Components; -- ------------------------------ -- Read the application configuration file <b>awa.xml</b>. This is called after the servlets -- and filters have been registered in the application but before the module registration. -- ------------------------------ procedure Load_Configuration (App : in out Application; Files : in String) is procedure Load_Config (File : in String; Done : out Boolean); Paths : constant String := App.Get_Config (P_Module_Dir.P); Ctx : aliased EL.Contexts.Default.Default_Context; procedure Load_Config (File : in String; Done : out Boolean) is Path : constant String := Util.Files.Find_File_Path (File, Paths); begin Done := False; AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access, True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Config; begin Util.Files.Iterate_Path (Files, Load_Config'Access); end Load_Configuration; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Start the application. This is called by the server container when the server is started. -- ------------------------------ overriding procedure Start (App : in out Application) is Manager : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager; begin -- Start the security manager. AWA.Permissions.Services.Permission_Manager'Class (Manager.all).Start; -- Start the event service. App.Events.Start; -- Start the application. ASF.Applications.Main.Application (App).Start; -- Dump the route and filters to help in configuration issues. App.Dump_Routes (Util.Log.INFO_LEVEL); end Start; -- ------------------------------ -- Close the application. -- ------------------------------ overriding procedure Close (App : in out Application) is begin App.Events.Stop; ASF.Applications.Main.Application (App).Close; end Close; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is begin AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); end Register; -- ------------------------------ -- Send the event in the application event queues. -- ------------------------------ procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class) is begin App.Events.Send (Event); end Send_Event; -- ------------------------------ -- Execute the <tt>Process</tt> procedure with the event manager used by the application. -- ------------------------------ procedure Do_Event_Manager (App : in out Application; Process : access procedure (Events : in out AWA.Events.Services.Event_Manager)) is begin Process (App.Events); end Do_Event_Manager; -- ------------------------------ -- Initialize the parser represented by <b>Parser</b> to recognize the configuration -- that are specific to the plugins that have been registered so far. -- ------------------------------ procedure Initialize_Parser (App : in out Application'Class; Parser : in out Util.Serialize.IO.Parser'Class) is procedure Process (Module : in out AWA.Modules.Module'Class); procedure Process (Module : in out AWA.Modules.Module'Class) is begin Module.Initialize_Parser (Parser); end Process; begin AWA.Modules.Iterate (App.Modules, Process'Access); end Initialize_Parser; -- ------------------------------ -- Get the current application from the servlet context or service context. -- ------------------------------ function Current return Application_Access is use type AWA.Services.Contexts.Service_Context_Access; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; begin if Ctx /= null then return Ctx.Get_Application; end if; -- If there is no service context, look in the servlet current context. declare use type ASF.Servlets.Servlet_Registry_Access; Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current; begin if Ctx = null then Log.Warn ("There is no service context"); return null; end if; if not (Ctx.all in AWA.Applications.Application'Class) then Log.Warn ("The servlet context is not an application"); return null; end if; return AWA.Applications.Application'Class (Ctx.all)'Access; end; end Current; end AWA.Applications;
Initialize the audit manager
Initialize the audit manager
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
97296fb4354bee0712d708e92baa4739becd40c2
src/natools-smaz_implementations-base_64.adb
src/natools-smaz_implementations-base_64.adb
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Implementations.Base_64 is package Tools renames Natools.Smaz_Implementations.Base_64_Tools; use type Ada.Streams.Stream_Element_Offset; use type Tools.Base_64_Digit; ---------------------- -- Public Interface -- ---------------------- procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Verbatim_Length : out Natural; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Ignored : String (1 .. 2); Offset_Backup : Ada.Streams.Stream_Element_Offset; begin Tools.Next_Digit (Input, Offset, Code); if Code <= Last_Code then Verbatim_Length := 0; elsif Variable_Length_Verbatim then Verbatim_Length := 64 - Natural (Code); Code := 0; elsif Code = 63 then Tools.Next_Digit (Input, Offset, Code); Verbatim_Length := Natural (Code) * 3 + 3; Code := 0; elsif Code = 62 then Offset_Backup := Offset; Tools.Decode_Single (Input, Offset, Ignored (1), Code); Verbatim_Length := Natural (Code) * 3 + 1; Offset := Offset_Backup; Code := 0; else Offset_Backup := Offset; Verbatim_Length := (61 - Natural (Code)) * 4; Tools.Decode_Double (Input, Offset, Ignored, Code); Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2; Offset := Offset_Backup; Code := 0; end if; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is Ignored : Tools.Base_64_Digit; Output_Index : Natural := Output'First - 1; begin if Output'Length mod 3 = 1 then Tools.Decode_Single (Input, Offset, Output (Output_Index + 1), Ignored); Output_Index := Output_Index + 1; elsif Output'Length mod 3 = 2 then Tools.Decode_Double (Input, Offset, Output (Output_Index + 1 .. Output_Index + 2), Ignored); Output_Index := Output_Index + 2; end if; if Output_Index < Output'Last then Tools.Decode (Input, Offset, Output (Output_Index + 1 .. Output'Last)); end if; end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is Code : Tools.Base_64_Digit; begin for I in 1 .. Tools.Image_Length (Verbatim_Length) loop Tools.Next_Digit (Input, Offset, Code); end loop; end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Run_Count : constant Positive := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; begin return Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 1) + Tools.Image_Length (Last_Run_Size) + 1; end; elsif Input_Length mod 3 = 0 then declare Largest_Run : constant Positive := 64 * 3; Run_Count : constant Positive := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; begin return Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 2; end; elsif Input_Length mod 3 = 1 then declare Largest_Final_Run : constant Positive := 15 * 3 + 1; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; elsif Input_Length mod 3 = 2 then declare Largest_Final_Run : constant Positive := ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; else raise Program_Error with "Condition unreachable"; end if; end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is begin Output (Offset) := Tools.Image (Code); Offset := Offset + 1; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Index : Positive := Input'First; begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Length, Last : Positive; begin while Index in Input'Range loop Length := Positive'Min (Largest_Run, Input'Last + 1 - Index); Last := Index + Length - 1; Output (Offset) := Tools.Image (63 - Tools.Base_64_Digit (Length - 1)); Offset := Offset + 1; Tools.Encode (Input (Index .. Last), Output, Offset); Index := Last + 1; end loop; end; else if Input'Length mod 3 = 1 then declare Extra_Blocks : constant Natural := Natural'Min (15, Input'Length / 3); begin Output (Offset) := Tools.Image (62); Offset := Offset + 1; Tools.Encode_Single (Input (Index), Tools.Single_Byte_Padding (Extra_Blocks), Output, Offset); Index := Index + 1; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; elsif Input'Length mod 3 = 2 then declare Extra_Blocks : constant Natural := Natural'Min (Input'Length / 3, (62 - Natural (Last_Code)) * 4 - 1); begin Output (Offset) := Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4)); Offset := Offset + 1; Tools.Encode_Double (Input (Index .. Index + 1), Tools.Double_Byte_Padding (Extra_Blocks mod 4), Output, Offset); Index := Index + 1; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; end if; pragma Assert ((Input'Last + 1 - Index) mod 3 = 0); while Index <= Input'Last loop declare Block_Count : constant Natural := Natural'Min (64, (Input'Last + 1 - Index) / 3); begin Output (Offset) := Tools.Image (63); Output (Offset + 1) := Tools.Image (Tools.Base_64_Digit (Block_Count - 1)); Offset := Offset + 2; Tools.Encode (Input (Index .. Index + Block_Count * 3 - 1), Output, Offset); Index := Index + Block_Count * 3; end; end loop; end if; end Write_Verbatim; end Natools.Smaz_Implementations.Base_64;
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Implementations.Base_64 is package Tools renames Natools.Smaz_Implementations.Base_64_Tools; use type Ada.Streams.Stream_Element_Offset; use type Tools.Base_64_Digit; ---------------------- -- Public Interface -- ---------------------- procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Verbatim_Length : out Natural; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Ignored : String (1 .. 2); Offset_Backup : Ada.Streams.Stream_Element_Offset; begin Tools.Next_Digit (Input, Offset, Code); if Code <= Last_Code then Verbatim_Length := 0; elsif Variable_Length_Verbatim then Verbatim_Length := 64 - Natural (Code); Code := 0; elsif Code = 63 then Tools.Next_Digit (Input, Offset, Code); Verbatim_Length := Natural (Code) * 3 + 3; Code := 0; elsif Code = 62 then Offset_Backup := Offset; Tools.Decode_Single (Input, Offset, Ignored (1), Code); Verbatim_Length := Natural (Code) * 3 + 1; Offset := Offset_Backup; Code := 0; else Offset_Backup := Offset; Verbatim_Length := (61 - Natural (Code)) * 4; Tools.Decode_Double (Input, Offset, Ignored, Code); Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2; Offset := Offset_Backup; Code := 0; end if; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is Ignored : Tools.Base_64_Digit; Output_Index : Natural := Output'First - 1; begin if Output'Length mod 3 = 1 then Tools.Decode_Single (Input, Offset, Output (Output_Index + 1), Ignored); Output_Index := Output_Index + 1; elsif Output'Length mod 3 = 2 then Tools.Decode_Double (Input, Offset, Output (Output_Index + 1 .. Output_Index + 2), Ignored); Output_Index := Output_Index + 2; end if; if Output_Index < Output'Last then Tools.Decode (Input, Offset, Output (Output_Index + 1 .. Output'Last)); end if; end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is Code : Tools.Base_64_Digit; begin for I in 1 .. Tools.Image_Length (Verbatim_Length) loop Tools.Next_Digit (Input, Offset, Code); end loop; end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Run_Count : constant Positive := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; begin return Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 1) + Tools.Image_Length (Last_Run_Size) + 1; end; elsif Input_Length mod 3 = 0 then declare Largest_Run : constant Positive := 64 * 3; Run_Count : constant Positive := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; begin return Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 2; end; elsif Input_Length mod 3 = 1 then declare Largest_Final_Run : constant Positive := 15 * 3 + 1; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; elsif Input_Length mod 3 = 2 then declare Largest_Final_Run : constant Positive := ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; else raise Program_Error with "Condition unreachable"; end if; end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is begin Output (Offset) := Tools.Image (Code); Offset := Offset + 1; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Index : Positive := Input'First; begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Length, Last : Positive; begin while Index in Input'Range loop Length := Positive'Min (Largest_Run, Input'Last + 1 - Index); Last := Index + Length - 1; Output (Offset) := Tools.Image (63 - Tools.Base_64_Digit (Length - 1)); Offset := Offset + 1; Tools.Encode (Input (Index .. Last), Output, Offset); Index := Last + 1; end loop; end; else if Input'Length mod 3 = 1 then declare Extra_Blocks : constant Natural := Natural'Min (15, Input'Length / 3); begin Output (Offset) := Tools.Image (62); Offset := Offset + 1; Tools.Encode_Single (Input (Index), Tools.Single_Byte_Padding (Extra_Blocks), Output, Offset); Index := Index + 1; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; elsif Input'Length mod 3 = 2 then declare Extra_Blocks : constant Natural := Natural'Min (Input'Length / 3, (62 - Natural (Last_Code)) * 4 - 1); begin Output (Offset) := Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4)); Offset := Offset + 1; Tools.Encode_Double (Input (Index .. Index + 1), Tools.Double_Byte_Padding (Extra_Blocks mod 4), Output, Offset); Index := Index + 2; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; end if; pragma Assert ((Input'Last + 1 - Index) mod 3 = 0); while Index <= Input'Last loop declare Block_Count : constant Natural := Natural'Min (64, (Input'Last + 1 - Index) / 3); begin Output (Offset) := Tools.Image (63); Output (Offset + 1) := Tools.Image (Tools.Base_64_Digit (Block_Count - 1)); Offset := Offset + 2; Tools.Encode (Input (Index .. Index + Block_Count * 3 - 1), Output, Offset); Index := Index + Block_Count * 3; end; end loop; end if; end Write_Verbatim; end Natools.Smaz_Implementations.Base_64;
fix index update in encoding 3n+2 vrbtim
smaz_implementations-base_64: fix index update in encoding 3n+2 vrbtim
Ada
isc
faelys/natools
c630d44c83fa9e552a17d3f5e8e33fd586ec0736
src/asf-converters-sizes.adb
src/asf-converters-sizes.adb
----------------------------------------------------------------------- -- asf-converters-sizes -- Size converter -- 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.Exceptions; with Ada.Strings.Unbounded; with Util.Locales; with Util.Strings; with Util.Properties.Bundles; with ASF.Locales; with ASF.Utils; with ASF.Applications.Main; package body ASF.Converters.Sizes is ONE_KB : constant Long_Long_Integer := 1_024; ONE_MB : constant Long_Long_Integer := ONE_KB * 1_024; ONE_GB : constant Long_Long_Integer := ONE_MB * 1_024; UNIT_GB : aliased constant String := "size_giga_bytes"; UNIT_MB : aliased constant String := "size_mega_bytes"; UNIT_KB : aliased constant String := "size_kilo_bytes"; UNIT_B : aliased constant String := "size_bytes"; -- ------------------------------ -- 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. -- ------------------------------ function To_String (Convert : in Size_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 pragma Unreferenced (Convert); Bundle : ASF.Locales.Bundle; Locale : constant Util.Locales.Locale := Context.Get_Locale; begin begin Context.Get_Application.Load_Bundle (Name => "sizes", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); exception when E : Util.Properties.Bundles.NO_BUNDLE => Component.Log_Error ("Cannot localize sizes: {0}", Ada.Exceptions.Exception_Message (E)); end; -- Convert the value as an integer here so that we can raise -- the Invalid_Conversion exception. declare Size : constant Long_Long_Integer := Util.Beans.Objects.To_Long_Long_Integer (Value); Val : Integer; Values : ASF.Utils.Object_Array (1 .. 1); Result : Ada.Strings.Unbounded.Unbounded_String; Unit : Util.Strings.Name_Access; begin if Size >= ONE_GB then Val := Integer ((Size + ONE_GB / 2) / ONE_GB); Unit := UNIT_GB'Access; elsif Size >= ONE_MB then Val := Integer ((Size + ONE_MB / 2) / ONE_MB); Unit := UNIT_MB'Access; elsif Size >= ONE_KB then Val := Integer ((Size + ONE_KB / 2) / ONE_KB); Unit := UNIT_KB'Access; else Val := Integer (Size); Unit := UNIT_B'Access; end if; Values (1) := Util.Beans.Objects.To_Object (Val); ASF.Utils.Formats.Format (Bundle.Get (Unit.all), Values, Result); 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; -- ------------------------------ -- Convert the date string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- ------------------------------ function To_Object (Convert : in Size_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Convert, Context, Value); begin Component.Log_Error ("Conversion of string to a size is not implemented"); raise ASF.Converters.Invalid_Conversion with "Not implemented"; return Util.Beans.Objects.Null_Object; end To_Object; end ASF.Converters.Sizes;
----------------------------------------------------------------------- -- asf-converters-sizes -- Size converter -- 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.Exceptions; with Ada.Strings.Unbounded; with Util.Locales; with Util.Strings; with Util.Properties.Bundles; with ASF.Locales; with ASF.Utils; with ASF.Applications.Main; package body ASF.Converters.Sizes is ONE_KB : constant Long_Long_Integer := 1_024; ONE_MB : constant Long_Long_Integer := ONE_KB * 1_024; ONE_GB : constant Long_Long_Integer := ONE_MB * 1_024; UNIT_GB : aliased constant String := "size_giga_bytes"; UNIT_MB : aliased constant String := "size_mega_bytes"; UNIT_KB : aliased constant String := "size_kilo_bytes"; UNIT_B : aliased constant String := "size_bytes"; -- ------------------------------ -- 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. -- ------------------------------ function To_String (Convert : in Size_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 pragma Unreferenced (Convert); Bundle : ASF.Locales.Bundle; Locale : constant Util.Locales.Locale := Context.Get_Locale; begin begin ASF.Applications.Main.Load_Bundle (Context.Get_Application.all, Name => "sizes", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); exception when E : Util.Properties.Bundles.NO_BUNDLE => Component.Log_Error ("Cannot localize sizes: {0}", Ada.Exceptions.Exception_Message (E)); end; -- Convert the value as an integer here so that we can raise -- the Invalid_Conversion exception. declare Size : constant Long_Long_Integer := Util.Beans.Objects.To_Long_Long_Integer (Value); Val : Integer; Values : ASF.Utils.Object_Array (1 .. 1); Result : Ada.Strings.Unbounded.Unbounded_String; Unit : Util.Strings.Name_Access; begin if Size >= ONE_GB then Val := Integer ((Size + ONE_GB / 2) / ONE_GB); Unit := UNIT_GB'Access; elsif Size >= ONE_MB then Val := Integer ((Size + ONE_MB / 2) / ONE_MB); Unit := UNIT_MB'Access; elsif Size >= ONE_KB then Val := Integer ((Size + ONE_KB / 2) / ONE_KB); Unit := UNIT_KB'Access; else Val := Integer (Size); Unit := UNIT_B'Access; end if; Values (1) := Util.Beans.Objects.To_Object (Val); ASF.Utils.Formats.Format (Bundle.Get (Unit.all), Values, Result); 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; -- ------------------------------ -- Convert the date string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- ------------------------------ function To_Object (Convert : in Size_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Convert, Context, Value); begin Component.Log_Error ("Conversion of string to a size is not implemented"); raise ASF.Converters.Invalid_Conversion with "Not implemented"; return Util.Beans.Objects.Null_Object; end To_Object; end ASF.Converters.Sizes;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
884f95e6e62ae91de2864204f95f626bd0cf47a6
src/wiki-filters-variables.ads
src/wiki-filters-variables.ads
----------------------------------------------------------------------- -- wiki-filters-variables -- Expand variables in text and links -- 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. ----------------------------------------------------------------------- private with Ada.Containers.Indefinite_Hashed_Maps; -- === Variables Filters === -- The `Wiki.Filters.Variables` package defines a filter that replaces variables -- in the text, links, quotes. Variables are represented as `$name`, `$(name)` -- or `${name}`. When a variable is not found, the original string is not modified. -- The list of variables is either configured programatically through the -- `Add_Variable` procedures but it can also be set from the Wiki text by using -- the `Wiki.Plugins.Variables` plugin. package Wiki.Filters.Variables is pragma Preelaborate; type Variable_Filter is new Filter_Type with private; type Variable_Filter_Access is access all Variable_Filter'Class; -- Add a variable to replace the given name by its value. procedure Add_Variable (Filter : in out Variable_Filter; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); procedure Add_Variable (Filter : in out Variable_Filter; Name : in String; Value : in Wiki.Strings.WString); procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Add a section header with the given level in the document. overriding procedure Add_Header (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Add a text content with the given format to the document. Replace variables -- that are contained in the text. overriding procedure Add_Text (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a link. overriding procedure Add_Link (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. overriding procedure Add_Quote (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Expand the variables contained in the text. function Expand (Filter : in Variable_Filter; Text : in Wiki.Strings.WString) return Wiki.Strings.WString; -- Iterate over the filter variables. procedure Iterate (Filter : in Variable_Filter; Process : not null access procedure (Name, Value : in Strings.WString)); private package Variable_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Strings.WString, Element_Type => Strings.WString, Hash => Strings.Hash, Equivalent_Keys => "=", "=" => "="); subtype Variable_Map is Variable_Maps.Map; subtype Variable_Cursor is Variable_Maps.Cursor; type Variable_Filter is new Filter_Type with record Variables : Variable_Map; end record; end Wiki.Filters.Variables;
----------------------------------------------------------------------- -- wiki-filters-variables -- Expand variables in text and links -- 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. ----------------------------------------------------------------------- private with Ada.Containers.Indefinite_Ordered_Maps; -- === Variables Filters === -- The `Wiki.Filters.Variables` package defines a filter that replaces variables -- in the text, links, quotes. Variables are represented as `$name`, `$(name)` -- or `${name}`. When a variable is not found, the original string is not modified. -- The list of variables is either configured programatically through the -- `Add_Variable` procedures but it can also be set from the Wiki text by using -- the `Wiki.Plugins.Variables` plugin. package Wiki.Filters.Variables is pragma Preelaborate; type Variable_Filter is new Filter_Type with private; type Variable_Filter_Access is access all Variable_Filter'Class; -- Add a variable to replace the given name by its value. procedure Add_Variable (Filter : in out Variable_Filter; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); procedure Add_Variable (Filter : in out Variable_Filter; Name : in String; Value : in Wiki.Strings.WString); procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Add a section header with the given level in the document. overriding procedure Add_Header (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Add a text content with the given format to the document. Replace variables -- that are contained in the text. overriding procedure Add_Text (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a link. overriding procedure Add_Link (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. overriding procedure Add_Quote (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Expand the variables contained in the text. function Expand (Filter : in Variable_Filter; Text : in Wiki.Strings.WString) return Wiki.Strings.WString; -- Iterate over the filter variables. procedure Iterate (Filter : in Variable_Filter; Process : not null access procedure (Name, Value : in Strings.WString)); procedure Iterate (Chain : in Wiki.Filters.Filter_Chain; Process : not null access procedure (Name, Value : in Strings.WString)); private package Variable_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Strings.WString, Element_Type => Strings.WString); subtype Variable_Map is Variable_Maps.Map; subtype Variable_Cursor is Variable_Maps.Cursor; type Variable_Filter is new Filter_Type with record Variables : Variable_Map; end record; end Wiki.Filters.Variables;
Add Iterate procedure with a Filter_Chain and change the map to use an Ordered_Maps so that listing the variables is sorted on their name
Add Iterate procedure with a Filter_Chain and change the map to use an Ordered_Maps so that listing the variables is sorted on their name
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
73a4600edf4920e4c94be30a4d59283a015f501f
src/ado-sessions-factory.ads
src/ado-sessions-factory.ads
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Databases; with ADO.Schemas.Entities; with ADO.Sequences; -- === Session Factory === -- The session factory is the entry point to obtain a database session. -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. -- -- with ADO.Sessions.Factory; -- ... -- Sess_Factory : ADO.Sessions.Factory; -- -- The session factory can be initialized by using the <tt>Create</tt> operation and -- by giving a URI string that identifies the driver and the information to connect -- to the database. The session factory is created only once when the application starts. -- -- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test"); -- -- Having a session factory, one can get a database by using the <tt>Get_Session</tt> or -- <tt>Get_Master_Session</tt> function. Each time this operation is called, a new session -- is returned. The session is released when the session variable is finalized. -- -- DB : ADO.Sessions.Session := Sess_Factory.Get_Session; -- package ADO.Sessions.Factory is pragma Elaborate_Body; -- ------------------------------ -- 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.Databases.DataSource); -- 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.Databases.DataSource; 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; 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.Databases; with ADO.Schemas.Entities; with ADO.Sequences; with ADO.Caches; -- === Session Factory === -- The session factory is the entry point to obtain a database session. -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. -- -- with ADO.Sessions.Factory; -- ... -- Sess_Factory : ADO.Sessions.Factory; -- -- The session factory can be initialized by using the <tt>Create</tt> operation and -- by giving a URI string that identifies the driver and the information to connect -- to the database. The session factory is created only once when the application starts. -- -- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test"); -- -- Having a session factory, one can get a database by using the <tt>Get_Session</tt> or -- <tt>Get_Master_Session</tt> function. Each time this operation is called, a new session -- is returned. The session is released when the session variable is finalized. -- -- DB : ADO.Sessions.Session := Sess_Factory.Get_Session; -- 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.Databases.DataSource); -- 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.Databases.DataSource; Sequences : Factory_Access := null; Seq_Factory : aliased ADO.Sequences.Factory; -- Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache; Entities : ADO.Sessions.Entity_Cache_Access := null; Cache : aliased ADO.Caches.Cache_Manager; Cache_Values : ADO.Caches.Cache_Manager_Access; end record; -- Initialize the sequence factory associated with the session factory. procedure Initialize_Sequences (Factory : in out Session_Factory); end ADO.Sessions.Factory;
Add a cache to the factory object Define the entity_type cache group name
Add a cache to the factory object Define the entity_type cache group name
Ada
apache-2.0
stcarrez/ada-ado
ec8549b253f2d8e85ba5e4147813641510e6010c
awa/plugins/awa-votes/src/awa-votes-modules.adb
awa/plugins/awa-votes/src/awa-votes-modules.adb
----------------------------------------------------------------------- -- awa-votes-modules -- Module votes -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.Permissions; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Votes.Beans; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Votes.Models; with ADO.Sessions; with ADO.Statements; with ADO.Sessions.Entities; package body AWA.Votes.Modules is use AWA.Services; use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module"); package Register is new AWA.Modules.Beans (Module => Vote_Module, Module_Access => Vote_Module_Access); -- ------------------------------ -- Initialize the votes module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the votes module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Votes.Beans.Votes_Bean", Handler => AWA.Votes.Beans.Create_Vote_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the votes module. -- ------------------------------ function Get_Vote_Module return Vote_Module_Access is function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME); begin return Get; end Get_Vote_Module; -- ------------------------------ -- Vote for the given element. -- ------------------------------ procedure Vote_For (Model : in Vote_Module; Id : in ADO.Identifier; Entity_Type : in String; Permission : in String; Rating : in Integer) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; begin Log.Info ("User {0} votes for {1} rating {2}", ADO.Identifier'Image (User), Entity_Type & ADO.Identifier'Image (Id), Integer'Image (Rating)); Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); -- Check that the user has the vote permission on the given object. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Id); declare Stmt : ADO.Statements.Insert_Statement := DB.Create_Statement (AWA.Votes.Models.VOTE_TABLE); Result : Integer; begin Stmt.Save_Field (Name => "for_entity_id", Value => Id); Stmt.Save_Field (Name => "user_id", Value => User); Stmt.Save_Field (Name => "rating", Value => Rating); Stmt.Save_Field (Name => "for_entity_type", Value => Kind); Stmt.Execute (Result); if Result /= 1 then declare Update : ADO.Statements.Update_Statement := DB.Create_Statement (AWA.Votes.Models.VOTE_TABLE); begin Update.Save_Field (Name => "rating", Value => Rating); Update.Set_Filter ("for_entity_id = :id and user_id = :user " & "and for_entity_type = :type"); Update.Bind_Param ("id", Id); Update.Bind_Param ("user", User); Update.Bind_Param ("type", Kind); Update.Execute (Result); end; end if; end; Ctx.Commit; end Vote_For; end AWA.Votes.Modules;
----------------------------------------------------------------------- -- awa-votes-modules -- Module votes -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.Permissions; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Votes.Beans; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Votes.Models; with ADO.SQL; with ADO.Sessions; with ADO.Statements; with ADO.Sessions.Entities; package body AWA.Votes.Modules is use AWA.Services; use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module"); package Register is new AWA.Modules.Beans (Module => Vote_Module, Module_Access => Vote_Module_Access); -- ------------------------------ -- Initialize the votes module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the votes module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Votes.Beans.Votes_Bean", Handler => AWA.Votes.Beans.Create_Vote_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the votes module. -- ------------------------------ function Get_Vote_Module return Vote_Module_Access is function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME); begin return Get; end Get_Vote_Module; -- ------------------------------ -- Vote for the given element and return the total vote for that element. -- ------------------------------ procedure Vote_For (Model : in Vote_Module; Id : in ADO.Identifier; Entity_Type : in String; Permission : in String; Value : in Integer; Total : out Integer) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; Rating : AWA.Votes.Models.Rating_Ref; Vote : AWA.Votes.Models.Vote_Ref; Query : ADO.SQL.Query; Found : Boolean; begin Log.Info ("User {0} votes for {1} rating {2}", ADO.Identifier'Image (User.Get_Id), Entity_Type & ADO.Identifier'Image (Id), Integer'Image (Value)); Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); -- Check that the user has the vote permission on the given object. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Id); -- Get the vote associated with the object for the user. Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id"); Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type " & "and o.user_id = :user_id"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Query.Bind_Param ("user_id", User.Get_Id); Vote.Find (DB, Query, Found); if not Found then Query.Clear; -- Get the rating associated with the object. Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Rating.Find (DB, Query, Found); -- Create it if it does not exist. if not Found then Rating.Set_For_Entity_Id (Id); Rating.Set_For_Entity_Type (Kind); Rating.Set_Rating (Value); Rating.Set_Vote_Count (1); else Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1); Rating.Set_Rating (Value + Rating.Get_Rating); end if; Rating.Save (DB); Vote.Set_User (User); Vote.Set_Entity (Rating); else Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity); Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating); Rating.Save (DB); end if; Vote.Set_Rating (Value); Vote.Save (DB); -- Return the total rating for the element. Total := Rating.Get_Rating; Ctx.Commit; end Vote_For; end AWA.Votes.Modules;
Update the vote and the rating table associated with the vote
Update the vote and the rating table associated with the vote
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3c30bbdfe70aac16e331c43a0782568a36b3f9ca
src/util-encoders-base64.ads
src/util-encoders-base64.ads
----------------------------------------------------------------------- -- util-encoders-base64 -- Encode/Decode a stream in Base64 -- 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.Streams; with Interfaces; -- The <b>Util.Encodes.Base64</b> packages encodes and decodes streams -- in Base64 (See rfc4648: The Base16, Base32, and Base64 Data Encodings). package Util.Encoders.Base64 is -- ------------------------------ -- Base64 encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- a Base64 ascii stream. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- the a base64 output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Delete the encoder object. overriding procedure Delete (E : access Encoder); -- ------------------------------ -- Base64 decoder -- ------------------------------ -- The <b>Decoder</b> decodes a Base64 ascii stream into a binary stream. type Decoder is new Util.Encoders.Transformer with private; -- Decodes the base64 input stream represented by <b>Data</b> into -- the binary output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in Decoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Delete the decoder object. overriding procedure Delete (E : access Decoder); private type Alphabet is array (Interfaces.Unsigned_8 range 0 .. 63) of Ada.Streams.Stream_Element; type Alphabet_Access is not null access constant Alphabet; BASE64_ALPHABET : aliased constant Alphabet := (Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'), Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'), Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'), Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'), Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'), Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'), Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'), Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'), Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'), Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'), Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'), Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'), Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'), Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'), Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'), Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/')); BASE64_URL_ALPHABET : aliased constant Alphabet := (Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'), Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'), Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'), Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'), Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'), Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'), Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'), Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'), Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'), Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'), Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'), Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'), Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'), Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'), Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'), Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/')); type Encoder is new Util.Encoders.Transformer with record Alphabet : Alphabet_Access := BASE64_ALPHABET'Access; end record; type Alphabet_Values is array (Ada.Streams.Stream_Element) of Interfaces.Unsigned_8; type Alphabet_Values_Access is not null access constant Alphabet_Values; BASE64_VALUES : aliased constant Alphabet_Values := (Character'Pos ('A') => 0, Character'Pos ('B') => 1, Character'Pos ('C') => 2, Character'Pos ('D') => 3, Character'Pos ('E') => 4, Character'Pos ('F') => 5, Character'Pos ('G') => 6, Character'Pos ('H') => 7, Character'Pos ('I') => 8, Character'Pos ('J') => 9, Character'Pos ('K') => 10, Character'Pos ('L') => 11, Character'Pos ('M') => 12, Character'Pos ('N') => 13, Character'Pos ('O') => 14, Character'Pos ('P') => 15, Character'Pos ('Q') => 16, Character'Pos ('R') => 17, Character'Pos ('S') => 18, Character'Pos ('T') => 19, Character'Pos ('U') => 20, Character'Pos ('V') => 21, Character'Pos ('W') => 22, Character'Pos ('X') => 23, Character'Pos ('Y') => 24, Character'Pos ('Z') => 25, Character'Pos ('a') => 26, Character'Pos ('b') => 27, Character'Pos ('c') => 28, Character'Pos ('d') => 29, Character'Pos ('e') => 30, Character'Pos ('f') => 31, Character'Pos ('g') => 32, Character'Pos ('h') => 33, Character'Pos ('i') => 34, Character'Pos ('j') => 35, Character'Pos ('k') => 35, Character'Pos ('l') => 37, Character'Pos ('m') => 38, Character'Pos ('n') => 39, Character'Pos ('o') => 40, Character'Pos ('p') => 41, Character'Pos ('q') => 42, Character'Pos ('r') => 43, Character'Pos ('s') => 44, Character'Pos ('t') => 45, Character'Pos ('u') => 46, Character'Pos ('v') => 47, Character'Pos ('w') => 48, Character'Pos ('x') => 49, Character'Pos ('y') => 50, Character'Pos ('z') => 51, Character'Pos ('0') => 52, Character'Pos ('1') => 53, Character'Pos ('2') => 54, Character'Pos ('3') => 55, Character'Pos ('4') => 56, Character'Pos ('5') => 57, Character'Pos ('6') => 58, Character'Pos ('7') => 59, Character'Pos ('8') => 60, Character'Pos ('9') => 61, Character'Pos ('+') => 62, Character'Pos ('/') => 63, others => 16#FF#); BASE64_URL_VALUES : aliased constant Alphabet_Values := (Character'Pos ('A') => 0, Character'Pos ('B') => 1, Character'Pos ('C') => 2, Character'Pos ('D') => 3, Character'Pos ('E') => 4, Character'Pos ('F') => 5, Character'Pos ('G') => 6, Character'Pos ('H') => 7, Character'Pos ('I') => 8, Character'Pos ('J') => 9, Character'Pos ('K') => 10, Character'Pos ('L') => 11, Character'Pos ('M') => 12, Character'Pos ('N') => 13, Character'Pos ('O') => 14, Character'Pos ('P') => 15, Character'Pos ('Q') => 16, Character'Pos ('R') => 17, Character'Pos ('S') => 18, Character'Pos ('T') => 19, Character'Pos ('U') => 20, Character'Pos ('V') => 21, Character'Pos ('W') => 22, Character'Pos ('X') => 23, Character'Pos ('Y') => 24, Character'Pos ('Z') => 25, Character'Pos ('a') => 26, Character'Pos ('b') => 27, Character'Pos ('c') => 28, Character'Pos ('d') => 29, Character'Pos ('e') => 30, Character'Pos ('f') => 31, Character'Pos ('g') => 32, Character'Pos ('h') => 33, Character'Pos ('i') => 34, Character'Pos ('j') => 35, Character'Pos ('k') => 35, Character'Pos ('l') => 37, Character'Pos ('m') => 38, Character'Pos ('n') => 39, Character'Pos ('o') => 40, Character'Pos ('p') => 41, Character'Pos ('q') => 42, Character'Pos ('r') => 43, Character'Pos ('s') => 44, Character'Pos ('t') => 45, Character'Pos ('u') => 46, Character'Pos ('v') => 47, Character'Pos ('w') => 48, Character'Pos ('x') => 49, Character'Pos ('y') => 50, Character'Pos ('z') => 51, Character'Pos ('0') => 52, Character'Pos ('1') => 53, Character'Pos ('2') => 54, Character'Pos ('3') => 55, Character'Pos ('4') => 56, Character'Pos ('5') => 57, Character'Pos ('6') => 58, Character'Pos ('7') => 59, Character'Pos ('8') => 60, Character'Pos ('9') => 61, Character'Pos ('-') => 62, Character'Pos ('_') => 63, others => 16#FF#); type Decoder is new Util.Encoders.Transformer with record Values : Alphabet_Values_Access := BASE64_VALUES'Access; end record; end Util.Encoders.Base64;
----------------------------------------------------------------------- -- util-encoders-base64 -- Encode/Decode a stream in Base64 -- 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.Streams; with Interfaces; -- The <b>Util.Encodes.Base64</b> packages encodes and decodes streams -- in Base64 (See rfc4648: The Base16, Base32, and Base64 Data Encodings). package Util.Encoders.Base64 is -- ------------------------------ -- Base64 encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- a Base64 ascii stream. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- the a base64 output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Delete the encoder object. overriding procedure Delete (E : access Encoder); -- ------------------------------ -- Base64 decoder -- ------------------------------ -- The <b>Decoder</b> decodes a Base64 ascii stream into a binary stream. type Decoder is new Util.Encoders.Transformer with private; -- Decodes the base64 input stream represented by <b>Data</b> into -- the binary output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in Decoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Delete the decoder object. overriding procedure Delete (E : access Decoder); private type Alphabet is array (Interfaces.Unsigned_8 range 0 .. 63) of Ada.Streams.Stream_Element; type Alphabet_Access is not null access constant Alphabet; BASE64_ALPHABET : aliased constant Alphabet := (Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'), Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'), Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'), Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'), Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'), Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'), Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'), Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'), Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'), Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'), Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'), Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'), Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'), Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'), Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'), Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/')); BASE64_URL_ALPHABET : aliased constant Alphabet := (Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'), Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'), Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'), Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'), Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'), Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'), Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'), Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'), Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'), Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'), Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'), Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'), Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'), Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'), Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'), Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/')); type Encoder is new Util.Encoders.Transformer with record Alphabet : Alphabet_Access := BASE64_ALPHABET'Access; end record; type Alphabet_Values is array (Ada.Streams.Stream_Element) of Interfaces.Unsigned_8; type Alphabet_Values_Access is not null access constant Alphabet_Values; BASE64_VALUES : aliased constant Alphabet_Values := (Character'Pos ('A') => 0, Character'Pos ('B') => 1, Character'Pos ('C') => 2, Character'Pos ('D') => 3, Character'Pos ('E') => 4, Character'Pos ('F') => 5, Character'Pos ('G') => 6, Character'Pos ('H') => 7, Character'Pos ('I') => 8, Character'Pos ('J') => 9, Character'Pos ('K') => 10, Character'Pos ('L') => 11, Character'Pos ('M') => 12, Character'Pos ('N') => 13, Character'Pos ('O') => 14, Character'Pos ('P') => 15, Character'Pos ('Q') => 16, Character'Pos ('R') => 17, Character'Pos ('S') => 18, Character'Pos ('T') => 19, Character'Pos ('U') => 20, Character'Pos ('V') => 21, Character'Pos ('W') => 22, Character'Pos ('X') => 23, Character'Pos ('Y') => 24, Character'Pos ('Z') => 25, Character'Pos ('a') => 26, Character'Pos ('b') => 27, Character'Pos ('c') => 28, Character'Pos ('d') => 29, Character'Pos ('e') => 30, Character'Pos ('f') => 31, Character'Pos ('g') => 32, Character'Pos ('h') => 33, Character'Pos ('i') => 34, Character'Pos ('j') => 35, Character'Pos ('k') => 36, Character'Pos ('l') => 37, Character'Pos ('m') => 38, Character'Pos ('n') => 39, Character'Pos ('o') => 40, Character'Pos ('p') => 41, Character'Pos ('q') => 42, Character'Pos ('r') => 43, Character'Pos ('s') => 44, Character'Pos ('t') => 45, Character'Pos ('u') => 46, Character'Pos ('v') => 47, Character'Pos ('w') => 48, Character'Pos ('x') => 49, Character'Pos ('y') => 50, Character'Pos ('z') => 51, Character'Pos ('0') => 52, Character'Pos ('1') => 53, Character'Pos ('2') => 54, Character'Pos ('3') => 55, Character'Pos ('4') => 56, Character'Pos ('5') => 57, Character'Pos ('6') => 58, Character'Pos ('7') => 59, Character'Pos ('8') => 60, Character'Pos ('9') => 61, Character'Pos ('+') => 62, Character'Pos ('/') => 63, others => 16#FF#); BASE64_URL_VALUES : aliased constant Alphabet_Values := (Character'Pos ('A') => 0, Character'Pos ('B') => 1, Character'Pos ('C') => 2, Character'Pos ('D') => 3, Character'Pos ('E') => 4, Character'Pos ('F') => 5, Character'Pos ('G') => 6, Character'Pos ('H') => 7, Character'Pos ('I') => 8, Character'Pos ('J') => 9, Character'Pos ('K') => 10, Character'Pos ('L') => 11, Character'Pos ('M') => 12, Character'Pos ('N') => 13, Character'Pos ('O') => 14, Character'Pos ('P') => 15, Character'Pos ('Q') => 16, Character'Pos ('R') => 17, Character'Pos ('S') => 18, Character'Pos ('T') => 19, Character'Pos ('U') => 20, Character'Pos ('V') => 21, Character'Pos ('W') => 22, Character'Pos ('X') => 23, Character'Pos ('Y') => 24, Character'Pos ('Z') => 25, Character'Pos ('a') => 26, Character'Pos ('b') => 27, Character'Pos ('c') => 28, Character'Pos ('d') => 29, Character'Pos ('e') => 30, Character'Pos ('f') => 31, Character'Pos ('g') => 32, Character'Pos ('h') => 33, Character'Pos ('i') => 34, Character'Pos ('j') => 35, Character'Pos ('k') => 35, Character'Pos ('l') => 37, Character'Pos ('m') => 38, Character'Pos ('n') => 39, Character'Pos ('o') => 40, Character'Pos ('p') => 41, Character'Pos ('q') => 42, Character'Pos ('r') => 43, Character'Pos ('s') => 44, Character'Pos ('t') => 45, Character'Pos ('u') => 46, Character'Pos ('v') => 47, Character'Pos ('w') => 48, Character'Pos ('x') => 49, Character'Pos ('y') => 50, Character'Pos ('z') => 51, Character'Pos ('0') => 52, Character'Pos ('1') => 53, Character'Pos ('2') => 54, Character'Pos ('3') => 55, Character'Pos ('4') => 56, Character'Pos ('5') => 57, Character'Pos ('6') => 58, Character'Pos ('7') => 59, Character'Pos ('8') => 60, Character'Pos ('9') => 61, Character'Pos ('-') => 62, Character'Pos ('_') => 63, others => 16#FF#); type Decoder is new Util.Encoders.Transformer with record Values : Alphabet_Values_Access := BASE64_VALUES'Access; end record; end Util.Encoders.Base64;
Fix the base64 alphabet
Fix the base64 alphabet
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
55cd0381824fa6cdd23a01e75ac97092ab3c27cc
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; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; limited with Security.Controllers; limited with Security.Contexts; -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- package Security.Permissions is 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;
Remove the unused types and operations
Remove the unused types and operations
Ada
apache-2.0
stcarrez/ada-security
0f34aa6fa66c4621ae5cec3a7cd5e2c2c9104bcd
tests/natools-cron-tests.adb
tests/natools-cron-tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Cron.Tests is -------------------- -- Test Callbacks -- -------------------- overriding procedure Run (Self : in out Test_Callback) is begin Append (Self.Backend.all, Self.Symbol); end Run; overriding procedure Run (Self : in out Long_Callback) is begin Append (Self.Backend.all, Self.Open); delay Self.Wait; Append (Self.Backend.all, Self.Close); end Run; -------------------- -- Bounded String -- -------------------- procedure Append (S : in out Bounded_String; C : Character) is begin S.Size := S.Size + 1; S.Data (S.Size) := C; end Append; function Get (S : Bounded_String) return String is begin return S.Data (1 .. S.Size); end Get; procedure Reset (S : in out Bounded_String) is begin S.Size := 0; end Reset; ----------------- -- Test Helper -- ----------------- function Quote (Data : String) return String is ('"' & Data & '"'); procedure Check is new NT.Generic_Check (String, "=", Quote, False); ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Basic_Usage (Report); Delete_While_Busy (Report); Insert_While_Busy (Report); Time_Collision (Report); end All_Tests; ----------------------- -- Inidividual Tests -- ----------------------- procedure Basic_Usage (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Basic black-box usage"); Total : constant Duration := 1.0; Tick : constant Duration := Total / 10; Half_Tick : constant Duration := Tick / 2; Log : aliased Bounded_String (256); begin declare Beat : constant Cron_Entry := Create (Tick, Test_Callback'(Backend => Log'Access, Symbol => '.')); pragma Unreferenced (Beat); Test_Entry : Cron_Entry; begin delay Half_Tick; Test_Entry.Set (Tick, Test_Callback'(Backend => Log'Access, Symbol => '1')); delay 3 * Tick + Half_Tick; Test_Entry.Reset; delay Half_Tick; end; Append (Log, '|'); delay Tick / 10; declare use type Ada.Calendar.Time; Beat : constant Cron_Entry := Create ((Origin => Ada.Calendar.Clock + Half_Tick, Period => Tick), Test_Callback'(Backend => Log'Access, Symbol => '.')); pragma Unreferenced (Beat); Slow, Fast : Cron_Entry; begin Slow.Set (2 * Tick, Test_Callback'(Backend => Log'Access, Symbol => 's')); delay 2 * Tick; Fast.Set (Tick / 5, Test_Callback'(Backend => Log'Access, Symbol => 'f')); delay Tick + Half_Tick; Fast.Reset; delay Tick + Half_Tick; end; -- Timeline, in ticks: -- Beat: set at 0.0, finalized at 4.5, run at 1.0, 2.0, 3.0, 4.0. -- Test_Entry: set at 0.5, reset at 4.0, run at 1.5, 2.5, 3.5. -- Beat: set at 4.5, finalized at 9.5, run at 5.0, 6.0, 7.0, 8.0, 9.0. -- Slow: set at 4.5, finalized at 9.5, run at 6.5, 8.5. -- Fast: set at 6.5, reset at 8.0, -- run at 6.7, 6.9, 7.1, 7.3, 7.5, 7.7, 7.9 Check (Test, Get (Log), ".1.1.1.|..sff.fffff.s."); exception when Error : others => Test.Report_Exception (Error); end Basic_Usage; procedure Delete_While_Busy (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Delete entry while callback is running"); Total : constant Duration := 0.01; Log : aliased Bounded_String (256); begin declare Test_Entry : Cron_Entry; begin Test_Entry.Set (Total / 8, Long_Callback' (Backend => Log'Access, Open => '(', Close => ')', Wait => Total / 4)); delay Total / 4; end; Check (Test, Get (Log), "(", "Before wait"); delay Total / 2; Check (Test, Get (Log), "()", "After wait"); exception when Error : others => Test.Report_Exception (Error); end Delete_While_Busy; procedure Insert_While_Busy (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Insert entry while callback is running"); Total : constant Duration := 0.1; Log : aliased Bounded_String (256); begin declare Long, Short : Cron_Entry; begin Long.Set (Total / 8, Long_Callback' (Backend => Log'Access, Open => '(', Close => ')', Wait => Total / 5)); delay Total / 8 + Total / 16; Short.Set (Total / 8, Test_Callback'(Backend => Log'Access, Symbol => '.')); delay Total / 2 + Total / 8; end; -- Timeline: 0 . 1/8 . 1/4 . 3/8 . 1/2 . 5/8 . 3/4 . 7/8 . 1 -- Set: L S -- Finalize: * -- Ticks: L L S L S L S L S L -- Run: <----L---->S <----L---->S <----L----> delay Total / 8; Check (Test, Get (Log), "().().()"); exception when Error : others => Test.Report_Exception (Error); end Insert_While_Busy; procedure Time_Collision (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Simultaneous activation of events"); Total : constant Duration := 0.01; Tick : constant Duration := Total / 4; Log : aliased Bounded_String (256); begin declare use type Ada.Calendar.Time; Common : constant Periodic_Time := (Ada.Calendar.Clock + Tick, Tick); First, Second, Third : Cron_Entry; begin First.Set (Common, Test_Callback'(Backend => Log'Access, Symbol => '1')); Second.Set (Common, Test_Callback'(Backend => Log'Access, Symbol => '2')); Third.Set ((Origin => Common.Origin, Period => 2 * Common.Period), Test_Callback'(Backend => Log'Access, Symbol => '3')); delay Total - Tick / 2; end; Check (Test, Get (Log), "12312123"); exception when Error : others => Test.Report_Exception (Error); end Time_Collision; end Natools.Cron.Tests;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Cron.Tests is -------------------- -- Test Callbacks -- -------------------- overriding procedure Run (Self : in out Test_Callback) is begin Append (Self.Backend.all, Self.Symbol); end Run; overriding procedure Run (Self : in out Long_Callback) is begin Append (Self.Backend.all, Self.Open); delay Self.Wait; Append (Self.Backend.all, Self.Close); end Run; -------------------- -- Bounded String -- -------------------- procedure Append (S : in out Bounded_String; C : Character) is begin S.Size := S.Size + 1; S.Data (S.Size) := C; end Append; function Get (S : Bounded_String) return String is begin return S.Data (1 .. S.Size); end Get; procedure Reset (S : in out Bounded_String) is begin S.Size := 0; end Reset; ----------------- -- Test Helper -- ----------------- function Quote (Data : String) return String is ('"' & Data & '"'); procedure Check is new NT.Generic_Check (String, "=", Quote, False); ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Basic_Usage (Report); Delete_While_Busy (Report); Insert_While_Busy (Report); Time_Collision (Report); end All_Tests; ----------------------- -- Inidividual Tests -- ----------------------- procedure Basic_Usage (Report : in out NT.Reporter'Class) is use type Ada.Calendar.Time; Test : NT.Test := Report.Item ("Basic black-box usage"); Total : constant Duration := 10.0; Tick : constant Duration := Total / 10; Half_Tick : constant Duration := Tick / 2; Log : aliased Bounded_String (256); begin declare Beat : constant Cron_Entry := Create (Tick, Test_Callback'(Backend => Log'Access, Symbol => '.')); pragma Unreferenced (Beat); One_Time_Entry : constant Cron_Entry := Create (Ada.Calendar.Clock + Half_Tick, Test_Callback'(Backend => Log'Access, Symbol => 'o')); pragma Unreferenced (One_Time_Entry); Test_Entry : Cron_Entry; begin delay Half_Tick; Test_Entry.Set (Tick, Test_Callback'(Backend => Log'Access, Symbol => '1')); delay 3 * Tick + Half_Tick; Test_Entry.Reset; delay Half_Tick; end; Append (Log, '|'); delay Tick / 10; declare Beat : constant Cron_Entry := Create ((Origin => Ada.Calendar.Clock + Half_Tick, Period => Tick), Test_Callback'(Backend => Log'Access, Symbol => '.')); pragma Unreferenced (Beat); One_Time_Entry : constant Cron_Entry := Create ((Origin => Ada.Calendar.Clock + Tick, Period => -Half_Tick), Test_Callback'(Backend => Log'Access, Symbol => 'O')); pragma Unreferenced (One_Time_Entry); Slow, Fast : Cron_Entry; begin Slow.Set (2 * Tick, Test_Callback'(Backend => Log'Access, Symbol => 's')); delay 2 * Tick; Fast.Set (Tick / 5, Test_Callback'(Backend => Log'Access, Symbol => 'f')); delay Tick + Half_Tick; Fast.Reset; delay Tick + Half_Tick; end; -- Timeline, in ticks: -- Beat: set at 0.0, finalized at 4.5, run at 1.0, 2.0, 3.0, 4.0. -- Test_Entry: set at 0.5, reset at 4.0, run at 1.5, 2.5, 3.5. -- Beat: set at 4.5, finalized at 9.5, run at 5.0, 6.0, 7.0, 8.0, 9.0. -- Slow: set at 4.5, finalized at 9.5, run at 6.5, 8.5. -- Fast: set at 6.5, reset at 8.0, -- run at 6.7, 6.9, 7.1, 7.3, 7.5, 7.7, 7.9 Check (Test, Get (Log), "o.1.1.1.|.O.sff.fffff.s."); exception when Error : others => Test.Report_Exception (Error); end Basic_Usage; procedure Delete_While_Busy (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Delete entry while callback is running"); Total : constant Duration := 0.01; Log : aliased Bounded_String (256); begin declare Test_Entry : Cron_Entry; begin Test_Entry.Set (Total / 8, Long_Callback' (Backend => Log'Access, Open => '(', Close => ')', Wait => Total / 4)); delay Total / 4; end; Check (Test, Get (Log), "(", "Before wait"); delay Total / 2; Check (Test, Get (Log), "()", "After wait"); exception when Error : others => Test.Report_Exception (Error); end Delete_While_Busy; procedure Insert_While_Busy (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Insert entry while callback is running"); Total : constant Duration := 0.1; Log : aliased Bounded_String (256); begin declare Long, Short : Cron_Entry; begin Long.Set (Total / 8, Long_Callback' (Backend => Log'Access, Open => '(', Close => ')', Wait => Total / 5)); delay Total / 8 + Total / 16; Short.Set (Total / 8, Test_Callback'(Backend => Log'Access, Symbol => '.')); delay Total / 2 + Total / 8; end; -- Timeline: 0 . 1/8 . 1/4 . 3/8 . 1/2 . 5/8 . 3/4 . 7/8 . 1 -- Set: L S -- Finalize: * -- Ticks: L L S L S L S L S L -- Run: <----L---->S <----L---->S <----L----> delay Total / 8; Check (Test, Get (Log), "().().()"); exception when Error : others => Test.Report_Exception (Error); end Insert_While_Busy; procedure Time_Collision (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Simultaneous activation of events"); Total : constant Duration := 0.01; Tick : constant Duration := Total / 4; Log : aliased Bounded_String (256); begin declare use type Ada.Calendar.Time; Common : constant Periodic_Time := (Ada.Calendar.Clock + Tick, Tick); First, Second, Third : Cron_Entry; begin First.Set (Common, Test_Callback'(Backend => Log'Access, Symbol => '1')); Second.Set (Common, Test_Callback'(Backend => Log'Access, Symbol => '2')); Third.Set ((Origin => Common.Origin, Period => 2 * Common.Period), Test_Callback'(Backend => Log'Access, Symbol => '3')); delay Total - Tick / 2; end; Check (Test, Get (Log), "12312123"); exception when Error : others => Test.Report_Exception (Error); end Time_Collision; end Natools.Cron.Tests;
test the new one-time events
cron-tests: test the new one-time events
Ada
isc
faelys/natools
b3e4ec04aa1ce6b5b7f35da46d91fa9c63f54445
regtests/util-log-tests.adb
regtests/util-log-tests.adb
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Directories; with Util.Test_Caller; with Util.Log; with Util.Log.Loggers; with Util.Properties; with Util.Measures; package body Util.Log.Tests is use Util; Log : constant Loggers.Logger := Loggers.Create ("util.log.test"); procedure Test_Log (T : in out Test) is pragma Unreferenced (T); L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin L.Set_Level (DEBUG_LEVEL); Log.Info ("My log message"); Log.Error ("My error message"); Log.Debug ("A debug message Not printed"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); end Test_Log; -- Test configuration and creation of file procedure Test_File_Appender (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); end; end Test_File_Appender; procedure Test_Log_Perf (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); for I in 1 .. 1000 loop declare S : Util.Measures.Stamp; begin Util.Measures.Report (S, "Util.Measures.Report", 1000); end; end loop; declare L : Loggers.Logger := Loggers.Create ("util.log.test.perf"); S : Util.Measures.Stamp; begin L.Set_Level (DEBUG_LEVEL); for I in 1 .. 1000 loop L.Info ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Info message (output)", 1000); L.Set_Level (INFO_LEVEL); for I in 1 .. 10_000 loop L.Debug ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Debug message (no output)", 10_000); end; end Test_Log_Perf; -- ------------------------------ -- Test appending the log on several log files -- ------------------------------ procedure Test_List_Appender (T : in out Test) is use Ada.Strings; use Ada.Directories; Props : Util.Properties.Manager; begin for I in 1 .. 10 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Name : constant String := "log4j.appender.test" & Id; begin Props.Set (Name, "File"); Props.Set (Name & ".File", "test" & Id & ".log"); Props.Set (Name & ".layout", "date-level-message"); if I > 5 then Props.Set (Name & ".level", "INFO"); end if; end; end loop; Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); end; -- Check that we have non empty log files (up to test8.log). for I in 1 .. 8 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := "test" & Id & ".log"; begin T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); if I > 5 then T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty"); else T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty"); end if; end; end loop; end Test_List_Appender; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_File_Appender_Modes (T : in out Test) is use Ada.Directories; Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test-append.log"); Props.Set ("log4j.appender.test.append", "true"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.appender.test_global", "File"); Props.Set ("log4j.appender.test_global.File", "test-append-global.log"); Props.Set ("log4j.appender.test_global.append", "false"); Props.Set ("log4j.appender.test_global.immediateFlush", "false"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG"); Props.Set ("log4j.rootCategory", "DEBUG,test_global,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Error ("This is the error test message"); end; Props.Set ("log4j.appender.test_append", "File"); Props.Set ("log4j.appender.test_append.File", "test-append2.log"); Props.Set ("log4j.appender.test_append.append", "true"); Props.Set ("log4j.appender.test_append.immediateFlush", "true"); Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global"); Util.Log.Loggers.Initialize (Props); declare L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file"); begin L1.Info ("L1-1 Writing a info message"); L2.Info ("L2-2 {0}: {1}", "Parameter", "Value"); L1.Info ("L1-3 Done"); L2.Error ("L2-4 This is the error test2 message"); end; Props.Set ("log4j.appender.test_append.append", "plop"); Props.Set ("log4j.appender.test_append.immediateFlush", "falsex"); Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Util.Log.Loggers.Initialize (Props); T.Assert (Ada.Directories.Size ("test-append.log") > 100, "Log file test-append.log is empty"); T.Assert (Ada.Directories.Size ("test-append2.log") > 100, "Log file test-append2.log is empty"); T.Assert (Ada.Directories.Size ("test-append-global.log") > 100, "Log file test-append.log is empty"); end Test_File_Appender_Modes; package Caller is new Util.Test_Caller (Test, "Log"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender", Test_File_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)", Test_File_Appender_Modes'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender", Test_List_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)", Test_Log_Perf'Access); end Add_Tests; end Util.Log.Tests;
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Directories; with Util.Test_Caller; with Util.Log; with Util.Log.Loggers; with Util.Properties; with Util.Measures; package body Util.Log.Tests is Log : constant Loggers.Logger := Loggers.Create ("util.log.test"); procedure Test_Log (T : in out Test) is pragma Unreferenced (T); L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin L.Set_Level (DEBUG_LEVEL); Log.Info ("My log message"); Log.Error ("My error message"); Log.Debug ("A debug message Not printed"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); end Test_Log; -- Test configuration and creation of file procedure Test_File_Appender (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); end; end Test_File_Appender; procedure Test_Log_Perf (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); for I in 1 .. 1000 loop declare S : Util.Measures.Stamp; begin Util.Measures.Report (S, "Util.Measures.Report", 1000); end; end loop; declare L : Loggers.Logger := Loggers.Create ("util.log.test.perf"); S : Util.Measures.Stamp; begin L.Set_Level (DEBUG_LEVEL); for I in 1 .. 1000 loop L.Info ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Info message (output)", 1000); L.Set_Level (INFO_LEVEL); for I in 1 .. 10_000 loop L.Debug ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Debug message (no output)", 10_000); end; end Test_Log_Perf; -- ------------------------------ -- Test appending the log on several log files -- ------------------------------ procedure Test_List_Appender (T : in out Test) is use Ada.Strings; use Ada.Directories; Props : Util.Properties.Manager; begin for I in 1 .. 10 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Name : constant String := "log4j.appender.test" & Id; begin Props.Set (Name, "File"); Props.Set (Name & ".File", "test" & Id & ".log"); Props.Set (Name & ".layout", "date-level-message"); if I > 5 then Props.Set (Name & ".level", "INFO"); end if; end; end loop; Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); end; -- Check that we have non empty log files (up to test8.log). for I in 1 .. 8 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := "test" & Id & ".log"; begin T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); if I > 5 then T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty"); else T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty"); end if; end; end loop; end Test_List_Appender; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_File_Appender_Modes (T : in out Test) is use Ada.Directories; Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test-append.log"); Props.Set ("log4j.appender.test.append", "true"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.appender.test_global", "File"); Props.Set ("log4j.appender.test_global.File", "test-append-global.log"); Props.Set ("log4j.appender.test_global.append", "false"); Props.Set ("log4j.appender.test_global.immediateFlush", "false"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG"); Props.Set ("log4j.rootCategory", "DEBUG,test_global,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Error ("This is the error test message"); end; Props.Set ("log4j.appender.test_append", "File"); Props.Set ("log4j.appender.test_append.File", "test-append2.log"); Props.Set ("log4j.appender.test_append.append", "true"); Props.Set ("log4j.appender.test_append.immediateFlush", "true"); Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global"); Util.Log.Loggers.Initialize (Props); declare L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file"); begin L1.Info ("L1-1 Writing a info message"); L2.Info ("L2-2 {0}: {1}", "Parameter", "Value"); L1.Info ("L1-3 Done"); L2.Error ("L2-4 This is the error test2 message"); end; Props.Set ("log4j.appender.test_append.append", "plop"); Props.Set ("log4j.appender.test_append.immediateFlush", "falsex"); Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Util.Log.Loggers.Initialize (Props); T.Assert (Ada.Directories.Size ("test-append.log") > 100, "Log file test-append.log is empty"); T.Assert (Ada.Directories.Size ("test-append2.log") > 100, "Log file test-append2.log is empty"); T.Assert (Ada.Directories.Size ("test-append-global.log") > 100, "Log file test-append.log is empty"); end Test_File_Appender_Modes; package Caller is new Util.Test_Caller (Test, "Log"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender", Test_File_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)", Test_File_Appender_Modes'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender", Test_List_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)", Test_Log_Perf'Access); end Add_Tests; end Util.Log.Tests;
Remove unused use clause
Remove unused use clause
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b261d6bfda275eaab62bbb868f936cb1630094e4
awa/plugins/awa-changelogs/regtests/awa-changelogs-modules-tests.adb
awa/plugins/awa-changelogs/regtests/awa-changelogs-modules-tests.adb
----------------------------------------------------------------------- -- awa-changelogs-tests -- Tests for changelogs -- 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.Tests; with Util.Test_Caller; with Security.Contexts; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Tests.Helpers.Users; package body AWA.Changelogs.Modules.Tests is package Caller is new Util.Test_Caller (Test, "AWA.Changelogs"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Changelogs.Add_Log", Test_Add_Log'Access); end Add_Tests; procedure Test_Add_Log (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Change_Manager : constant Changelog_Module_Access := Get_Changelog_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Total : Integer; begin T.Assert (Change_Manager /= null, "There is no changelog module"); Change_Manager.Add_Log (User.Get_Id, "awa_user", "A first changelog for the user"); end; end Test_Add_Log; end AWA.Changelogs.Modules.Tests;
----------------------------------------------------------------------- -- awa-changelogs-tests -- Tests for changelogs -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Security.Contexts; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Tests.Helpers.Users; package body AWA.Changelogs.Modules.Tests is package Caller is new Util.Test_Caller (Test, "AWA.Changelogs"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Changelogs.Add_Log", Test_Add_Log'Access); end Add_Tests; procedure Test_Add_Log (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Change_Manager : constant Changelog_Module_Access := Get_Changelog_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; begin T.Assert (Change_Manager /= null, "There is no changelog module"); Change_Manager.Add_Log (User.Get_Id, "awa_user", "A first changelog for the user"); end; end Test_Add_Log; end AWA.Changelogs.Modules.Tests;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4bc43c85705f495ec626905c838fb49d7e2f2b2c
src/gen-artifacts-xmi.ads
src/gen-artifacts-xmi.ads
----------------------------------------------------------------------- -- gen-artifacts-xmi -- UML-XMI artifact for Code Generator -- 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 DOM.Core; with Gen.Model.Packages; with Gen.Model.XMI; -- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code -- from an UML XMI description. package Gen.Artifacts.XMI is -- ------------------------------ -- UML XMI artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. overriding procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Context : in out Generator'Class); -- Read the UML configuration files that define the pre-defined types, stereotypes -- and other components used by a model. These files are XMI files as well. -- All the XMI files in the UML config directory are read. procedure Read_UML_Configuration (Handler : in out Artifact; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with record Nodes : aliased Gen.Model.XMI.UML_Model; Has_Config : Boolean := False; -- Stereotype which triggers the generation of database table. Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; -- Tag definitions which control the generation. Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; -- Stereotype which triggers the generation of AWA bean types. Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; end record; end Gen.Artifacts.XMI;
----------------------------------------------------------------------- -- gen-artifacts-xmi -- UML-XMI artifact for Code Generator -- 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 DOM.Core; with Gen.Model.Packages; with Gen.Model.XMI; -- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code -- from an UML XMI description. package Gen.Artifacts.XMI is -- ------------------------------ -- UML XMI artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. overriding procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Context : in out Generator'Class); -- Read the UML configuration files that define the pre-defined types, stereotypes -- and other components used by a model. These files are XMI files as well. -- All the XMI files in the UML config directory are read. procedure Read_UML_Configuration (Handler : in out Artifact; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with record Nodes : aliased Gen.Model.XMI.UML_Model; Has_Config : Boolean := False; -- Stereotype which triggers the generation of database table. Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; -- Tag definitions which control the generation. Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; -- Stereotype which triggers the generation of AWA bean types. Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; end record; end Gen.Artifacts.XMI;
Add the use foreign key stereotype
Add the use foreign key stereotype
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
cbc2cf4f8e34ded9efd8980d48c593930c4a8c3b
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; 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;
----------------------------------------------------------------------- -- 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; Log.Debug ("Read message size {0}", Natural'Image (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; Buffer.Buffer := Reader.Data; Reader.Stream.Read (Reader.Data (0 .. 0), 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;
Fix reading the header of event probe streams
Fix reading the header of event probe streams
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
73137f02d51d3417d8422a71d9e68ce4bd98dcf3
mat/src/mat-targets-readers.adb
mat/src/mat-targets-readers.adb
----------------------------------------------------------------------- -- mat-targets-readers - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers"); MSG_BEGIN : constant MAT.Events.Internal_Reference := 0; MSG_END : constant MAT.Events.Internal_Reference := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref) is begin For_Servant.Target.Create_Process (Pid => Pid, Process => For_Servant.Process); MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory, Reader => For_Servant.Reader.all); end Create_Process; procedure Probe_Begin (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg.Buffer); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; For_Servant.Create_Process (Pid); For_Servant.Reader.Read_Message (Msg); For_Servant.Reader.Read_Event_Definitions (Msg); end Probe_Begin; overriding procedure Dispatch (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is begin case Id is when MSG_BEGIN => For_Servant.Probe_Begin (Id, Params.all, Frame, Msg); when MSG_END => null; when others => null; end case; end Dispatch; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access) is begin Reader.Reader := Into'Unchecked_Access; Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Reader (Reader.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is Process_Reader : constant Process_Reader_Access := new Process_Servant; begin Process_Reader.Target := Target'Unrestricted_Access; Register (Reader, Process_Reader); end Initialize; end MAT.Targets.Readers;
----------------------------------------------------------------------- -- mat-targets-readers - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers"); MSG_BEGIN : constant MAT.Events.Internal_Reference := 0; MSG_END : constant MAT.Events.Internal_Reference := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin For_Servant.Target.Create_Process (Pid => Pid, Path => Path, Process => For_Servant.Process); MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory, Reader => For_Servant.Reader.all); end Create_Process; procedure Probe_Begin (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg.Buffer); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; For_Servant.Create_Process (Pid, Path); For_Servant.Reader.Read_Message (Msg); For_Servant.Reader.Read_Event_Definitions (Msg); end Probe_Begin; overriding procedure Dispatch (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is begin case Id is when MSG_BEGIN => For_Servant.Probe_Begin (Id, Params.all, Frame, Msg); when MSG_END => null; when others => null; end case; end Dispatch; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access) is begin Reader.Reader := Into'Unchecked_Access; Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Reader (Reader.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is Process_Reader : constant Process_Reader_Access := new Process_Servant; begin Process_Reader.Target := Target'Unrestricted_Access; Register (Reader, Process_Reader); end Initialize; end MAT.Targets.Readers;
Update the Create_Process procedure call to add the executable path
Update the Create_Process procedure call to add the executable path
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
cbdffd1b9ca8869644df6290003e6d37c413cbf2
arch/RISC-V/SiFive/drivers/fe310.adb
arch/RISC-V/SiFive/drivers/fe310.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017-2018, AdaCore and other contributors -- -- -- -- See github.com/AdaCore/Ada_Drivers_Library/graphs/contributors -- -- for more information -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with FE310.Time; use FE310.Time; with FE310_SVD.CLINT; use FE310_SVD.CLINT; with FE310_SVD.OTP_Mem; use FE310_SVD.OTP_Mem; with FE310_SVD.PRIC; use FE310_SVD.PRIC; with FE310_SVD.SPI; use FE310_SVD.SPI; package body FE310 is Crystal_Frequency : constant := 16_000_000; HFROSC_Frequency : constant := 72_000_000; -- High frequency internal oscillator ------------------- -- CPU_Frequency -- ------------------- function CPU_Frequency return UInt32 is Freq : UInt32; begin if PRIC_Periph.PLLCFG.SEL = Internal then Freq := HFROSC_Frequency / (UInt32 (PRIC_Periph.HFROSCCFG.DIV) + 1); else if PRIC_Periph.PLLCFG.REFSEL = Crystal then Freq := Crystal_Frequency; else Freq := HFROSC_Frequency; end if; if PRIC_Periph.PLLCFG.BYPASS = False then Freq := Freq / (UInt32 (PRIC_Periph.PLLCFG.R) + 1) * (2 * (UInt32 (PRIC_Periph.PLLCFG.F) + 1)) / (2**(Natural (PRIC_Periph.PLLCFG.Q))); end if; if PRIC_Periph.PLLOUTDIV.DIV_BY_1 = False then Freq := Freq / (2 * (UInt32 (PRIC_Periph.PLLOUTDIV.DIV) + 1)); end if; end if; return Freq; end CPU_Frequency; ----------------------------------------- -- Load_Internal_Oscilator_Calibration -- ----------------------------------------- procedure Load_Internal_Oscilator_Calibration is begin PRIC_Periph.HFROSCCFG.TRIM := OTP_Mem_Periph.HFROSC_TRIM.VALUE - 1; end Load_Internal_Oscilator_Calibration; ---------------------------- -- Use_Crystal_Oscillator -- ---------------------------- procedure Use_Crystal_Oscillator (Divider : PLL_Output_Divider := 1) is begin -- Use internal oscillator during switch PRIC_Periph.HFROSCCFG.DIV := 4; -- Divide by 5, Freq = 14.4 MHz PRIC_Periph.HFROSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFROSCCFG.READY; end loop; PRIC_Periph.PLLCFG.SEL := Internal; -- Start the crystal oscillator PRIC_Periph.HFXOSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFXOSCCFG.READY; end loop; -- Configure the final divider if Divider = 1 then PRIC_Periph.PLLOUTDIV.DIV_BY_1 := True; else PRIC_Periph.PLLOUTDIV.DIV_BY_1 := False; PRIC_Periph.PLLOUTDIV.DIV := PLLOUTDIV_DIV_Field ((Divider / 2) - 1); end if; -- Switch to crystal oscillator PRIC_Periph.PLLCFG.REFSEL := Crystal; PRIC_Periph.PLLCFG.BYPASS := True; PRIC_Periph.PLLCFG.SEL := Pll; -- Disable internal oscillator PRIC_Periph.HFROSCCFG.ENABLE := False; end Use_Crystal_Oscillator; ----------------------------- -- Use_Internal_Oscillator -- ----------------------------- procedure Use_Internal_Oscillator (Divider : Internal_Oscillator_Divider := 5) is begin PRIC_Periph.HFROSCCFG.DIV := HFROSCCFG_DIV_Field (Divider - 1); PRIC_Periph.HFROSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFROSCCFG.READY; end loop; PRIC_Periph.PLLCFG.SEL := Internal; -- Disable crystal oscillator and PLL PRIC_Periph.HFXOSCCFG.ENABLE := False; PRIC_Periph.PLLCFG.BYPASS := True; end Use_Internal_Oscillator; ------------ -- Use_PLL-- ------------ procedure Use_PLL (Reference : PLL_Reference; Internal_Osc_Div : Internal_Oscillator_Divider := 5; R_Div : PLL_R; F_Mul : PLL_F; Q_Div : PLL_Q; Output_Div : PLL_Output_Divider) is begin -- Use internal oscillator during switch PRIC_Periph.HFROSCCFG.DIV := HFROSCCFG_DIV_Field (Internal_Osc_Div - 1); PRIC_Periph.HFROSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFROSCCFG.READY; end loop; PRIC_Periph.PLLCFG.SEL := Internal; if Reference = Crystal then -- Start the crystal oscillator PRIC_Periph.HFXOSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFXOSCCFG.READY; end loop; else PRIC_Periph.HFXOSCCFG.ENABLE := False; end if; -- Configure the PLL PRIC_Periph.PLLCFG.REFSEL := PLLCFG_REFSEL_Field (Reference); PRIC_Periph.PLLCFG.R := PLLCFG_R_Field (R_Div - 1); PRIC_Periph.PLLCFG.F := PLLCFG_F_Field ((F_Mul / 2) - 1); PRIC_Periph.PLLCFG.Q := PLLCFG_Q_Field (PLL_Q'Enum_Rep (Q_Div)); -- Configure the final divider if Output_Div = 1 then PRIC_Periph.PLLOUTDIV.DIV_BY_1 := True; else PRIC_Periph.PLLOUTDIV.DIV_BY_1 := False; PRIC_Periph.PLLOUTDIV.DIV := PLLOUTDIV_DIV_Field ((Output_Div / 2) - 1); end if; -- Start the PLL PRIC_Periph.PLLCFG.BYPASS := False; Delay_Us (150); loop exit when PRIC_Periph.PLLCFG.LOCK; end loop; -- Switch to PLL PRIC_Periph.PLLCFG.SEL := Pll; -- Disable internal oscillator if the crystal reference is used if Reference = Crystal then PRIC_Periph.HFROSCCFG.ENABLE := False; end if; end Use_PLL; --------------------------------- -- Set_SPI_Flash_Clock_Divider -- --------------------------------- procedure Set_SPI_Flash_Clock_Divider (Divider : SPI_Clock_Divider) is begin QSPI0_Periph.SCKDIV.SCALE := (UInt12 (Divider) / 2) - 1; end Set_SPI_Flash_Clock_Divider; ----------------------------- -- SPI_Flash_Clock_Divider -- ----------------------------- function SPI_Flash_Clock_Divider return SPI_Clock_Divider is begin return 2 * (Integer (QSPI0_Periph.SCKDIV.SCALE) + 1); end SPI_Flash_Clock_Divider; end FE310;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017-2018, AdaCore and other contributors -- -- -- -- See github.com/AdaCore/Ada_Drivers_Library/graphs/contributors -- -- for more information -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with FE310.Time; use FE310.Time; with FE310_SVD.OTP_Mem; use FE310_SVD.OTP_Mem; with FE310_SVD.PRIC; use FE310_SVD.PRIC; with FE310_SVD.SPI; use FE310_SVD.SPI; package body FE310 is Crystal_Frequency : constant := 16_000_000; HFROSC_Frequency : constant := 72_000_000; -- High frequency internal oscillator ------------------- -- CPU_Frequency -- ------------------- function CPU_Frequency return UInt32 is Freq : UInt32; begin if PRIC_Periph.PLLCFG.SEL = Internal then Freq := HFROSC_Frequency / (UInt32 (PRIC_Periph.HFROSCCFG.DIV) + 1); else if PRIC_Periph.PLLCFG.REFSEL = Crystal then Freq := Crystal_Frequency; else Freq := HFROSC_Frequency; end if; if PRIC_Periph.PLLCFG.BYPASS = False then Freq := Freq / (UInt32 (PRIC_Periph.PLLCFG.R) + 1) * (2 * (UInt32 (PRIC_Periph.PLLCFG.F) + 1)) / (2**(Natural (PRIC_Periph.PLLCFG.Q))); end if; if PRIC_Periph.PLLOUTDIV.DIV_BY_1 = False then Freq := Freq / (2 * (UInt32 (PRIC_Periph.PLLOUTDIV.DIV) + 1)); end if; end if; return Freq; end CPU_Frequency; ----------------------------------------- -- Load_Internal_Oscilator_Calibration -- ----------------------------------------- procedure Load_Internal_Oscilator_Calibration is begin PRIC_Periph.HFROSCCFG.TRIM := OTP_Mem_Periph.HFROSC_TRIM.VALUE - 1; end Load_Internal_Oscilator_Calibration; ---------------------------- -- Use_Crystal_Oscillator -- ---------------------------- procedure Use_Crystal_Oscillator (Divider : PLL_Output_Divider := 1) is begin -- Use internal oscillator during switch PRIC_Periph.HFROSCCFG.DIV := 4; -- Divide by 5, Freq = 14.4 MHz PRIC_Periph.HFROSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFROSCCFG.READY; end loop; PRIC_Periph.PLLCFG.SEL := Internal; -- Start the crystal oscillator PRIC_Periph.HFXOSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFXOSCCFG.READY; end loop; -- Configure the final divider if Divider = 1 then PRIC_Periph.PLLOUTDIV.DIV_BY_1 := True; else PRIC_Periph.PLLOUTDIV.DIV_BY_1 := False; PRIC_Periph.PLLOUTDIV.DIV := PLLOUTDIV_DIV_Field ((Divider / 2) - 1); end if; -- Switch to crystal oscillator PRIC_Periph.PLLCFG.REFSEL := Crystal; PRIC_Periph.PLLCFG.BYPASS := True; PRIC_Periph.PLLCFG.SEL := Pll; -- Disable internal oscillator PRIC_Periph.HFROSCCFG.ENABLE := False; end Use_Crystal_Oscillator; ----------------------------- -- Use_Internal_Oscillator -- ----------------------------- procedure Use_Internal_Oscillator (Divider : Internal_Oscillator_Divider := 5) is begin PRIC_Periph.HFROSCCFG.DIV := HFROSCCFG_DIV_Field (Divider - 1); PRIC_Periph.HFROSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFROSCCFG.READY; end loop; PRIC_Periph.PLLCFG.SEL := Internal; -- Disable crystal oscillator and PLL PRIC_Periph.HFXOSCCFG.ENABLE := False; PRIC_Periph.PLLCFG.BYPASS := True; end Use_Internal_Oscillator; ------------ -- Use_PLL-- ------------ procedure Use_PLL (Reference : PLL_Reference; Internal_Osc_Div : Internal_Oscillator_Divider := 5; R_Div : PLL_R; F_Mul : PLL_F; Q_Div : PLL_Q; Output_Div : PLL_Output_Divider) is begin -- Use internal oscillator during switch PRIC_Periph.HFROSCCFG.DIV := HFROSCCFG_DIV_Field (Internal_Osc_Div - 1); PRIC_Periph.HFROSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFROSCCFG.READY; end loop; PRIC_Periph.PLLCFG.SEL := Internal; if Reference = Crystal then -- Start the crystal oscillator PRIC_Periph.HFXOSCCFG.ENABLE := True; loop exit when PRIC_Periph.HFXOSCCFG.READY; end loop; else PRIC_Periph.HFXOSCCFG.ENABLE := False; end if; -- Configure the PLL PRIC_Periph.PLLCFG.REFSEL := PLLCFG_REFSEL_Field (Reference); PRIC_Periph.PLLCFG.R := PLLCFG_R_Field (R_Div - 1); PRIC_Periph.PLLCFG.F := PLLCFG_F_Field ((F_Mul / 2) - 1); PRIC_Periph.PLLCFG.Q := PLLCFG_Q_Field (PLL_Q'Enum_Rep (Q_Div)); -- Configure the final divider if Output_Div = 1 then PRIC_Periph.PLLOUTDIV.DIV_BY_1 := True; else PRIC_Periph.PLLOUTDIV.DIV_BY_1 := False; PRIC_Periph.PLLOUTDIV.DIV := PLLOUTDIV_DIV_Field ((Output_Div / 2) - 1); end if; -- Start the PLL PRIC_Periph.PLLCFG.BYPASS := False; Delay_Us (150); loop exit when PRIC_Periph.PLLCFG.LOCK; end loop; -- Switch to PLL PRIC_Periph.PLLCFG.SEL := Pll; -- Disable internal oscillator if the crystal reference is used if Reference = Crystal then PRIC_Periph.HFROSCCFG.ENABLE := False; end if; end Use_PLL; --------------------------------- -- Set_SPI_Flash_Clock_Divider -- --------------------------------- procedure Set_SPI_Flash_Clock_Divider (Divider : SPI_Clock_Divider) is begin QSPI0_Periph.SCKDIV.SCALE := (UInt12 (Divider) / 2) - 1; end Set_SPI_Flash_Clock_Divider; ----------------------------- -- SPI_Flash_Clock_Divider -- ----------------------------- function SPI_Flash_Clock_Divider return SPI_Clock_Divider is begin return 2 * (Integer (QSPI0_Periph.SCKDIV.SCALE) + 1); end SPI_Flash_Clock_Divider; end FE310;
Remove useless with
FE310: Remove useless with
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
d0c0f691986dcb51bcedcb4c5e73cef9fe918362
samples/mapping.ads
samples/mapping.ads
----------------------------------------------------------------------- -- mapping -- Example of serialization mappings -- 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.Strings.Unbounded; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.Mappers.Vector_Mapper; with Util.Serialize.Mappers; with Ada.Containers.Vectors; with Util.Serialize.Contexts; package Mapping is use Ada.Strings.Unbounded; type Property is record Name : Unbounded_String; Value : Unbounded_String; end record; type Address is record City : Unbounded_String; Street : Unbounded_String; Country : Unbounded_String; Zip : Natural := 0; Info : Property; end record; type Person is record Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Username : Unbounded_String; Gender : Unbounded_String; Link : Unbounded_String; Age : Natural := 0; Addr : Address; Id : Long_Long_Integer := 0; end record; type Person_Access is access all Person; type Person_Fields is (FIELD_FIRST_NAME, FIELD_LAST_NAME, FIELD_AGE, FIELD_NAME, FIELD_USER_NAME, FIELD_GENDER, FIELD_LINK, FIELD_ID); -- Set the name/value pair on the current object. procedure Set_Member (P : in out Person; Field : in Person_Fields; Value : in Util.Beans.Objects.Object); function Get_Person_Member (From : in Person; Field : in Person_Fields) return Util.Beans.Objects.Object; package Person_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Person, Element_Type_Access => Person_Access, Fields => Person_Fields, Set_Member => Set_Member); subtype Person_Context is Person_Mapper.Element_Data; package Person_Vector is new Ada.Containers.Vectors (Element_Type => Person, Index_Type => Natural); package Person_Vector_Mapper is new Util.Serialize.Mappers.Vector_Mapper (Vectors => Person_Vector, Element_Mapper => Person_Mapper); subtype Person_Vector_Context is Person_Vector_Mapper.Vector_Data; -- Get the address mapper which describes how to load an Address. function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access; -- Get the person mapper which describes how to load a Person. function Get_Person_Mapper return Person_Mapper.Mapper_Access; -- Get the person vector mapper which describes how to load a list of Person. function Get_Person_Vector_Mapper return Person_Vector_Mapper.Mapper_Access; end Mapping;
----------------------------------------------------------------------- -- mapping -- Example of serialization mappings -- Copyright (C) 2010, 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.Mappers; with Ada.Containers.Vectors; package Mapping is use Ada.Strings.Unbounded; type Property is record Name : Unbounded_String; Value : Unbounded_String; end record; type Address is record City : Unbounded_String; Street : Unbounded_String; Country : Unbounded_String; Zip : Natural := 0; Info : Property; end record; type Person is record Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Username : Unbounded_String; Gender : Unbounded_String; Link : Unbounded_String; Age : Natural := 0; Addr : Address; Id : Long_Long_Integer := 0; end record; type Person_Access is access all Person; type Person_Fields is (FIELD_FIRST_NAME, FIELD_LAST_NAME, FIELD_AGE, FIELD_NAME, FIELD_USER_NAME, FIELD_GENDER, FIELD_LINK, FIELD_ID); -- Set the name/value pair on the current object. procedure Set_Member (P : in out Person; Field : in Person_Fields; Value : in Util.Beans.Objects.Object); function Get_Person_Member (From : in Person; Field : in Person_Fields) return Util.Beans.Objects.Object; package Person_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Person, Element_Type_Access => Person_Access, Fields => Person_Fields, Set_Member => Set_Member); subtype Person_Context is Person_Mapper.Element_Data; package Person_Vector is new Ada.Containers.Vectors (Element_Type => Person, Index_Type => Natural); -- Get the address mapper which describes how to load an Address. function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access; -- Get the person mapper which describes how to load a Person. function Get_Person_Mapper return Person_Mapper.Mapper_Access; end Mapping;
Remove the Person_Vector_Mapper instantiation so that we don't depend on the Vector_Mapper generic package
Remove the Person_Vector_Mapper instantiation so that we don't depend on the Vector_Mapper generic package
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
aaaa75be715a3efe69b313721c01e921f25c04f4
src/sys/encoders/util-encoders-hmac-sha256.ads
src/sys/encoders/util-encoders-hmac-sha256.ads
----------------------------------------------------------------------- -- util-encoders-hmac-sha256 -- Compute HMAC-SHA256 authentication code -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Util.Encoders.SHA256; -- The <b>Util.Encodes.HMAC.SHA256</b> package generates HMAC-SHA256 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package Util.Encoders.HMAC.SHA256 is HASH_SIZE : constant := Util.Encoders.SHA256.HASH_SIZE; -- Sign the data string with the key and return the HMAC-SHA256 code in binary. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Hash_Array; -- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Digest; -- Sign the data array with the key and return the HMAC-SHA256 code in the result. procedure Sign (Key : in Ada.Streams.Stream_Element_Array; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array); -- Sign the data string with the key and return the HMAC-SHA256 code as base64 string. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. function Sign_Base64 (Key : in String; Data : in String; URL : in Boolean := False) return Util.Encoders.SHA256.Base64_Digest; -- ------------------------------ -- HMAC-SHA256 Context -- ------------------------------ type Context is limited private; -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. procedure Set_Key (E : in out Context; Key : in String); -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. procedure Set_Key (E : in out Context; Key : in Ada.Streams.Stream_Element_Array); -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA256.Hash_Array); -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA256.Digest); -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. procedure Finish_Base64 (E : in out Context; Hash : out Util.Encoders.SHA256.Base64_Digest; URL : in Boolean := False); private type Context is new Ada.Finalization.Limited_Controlled with record SHA : Util.Encoders.SHA256.Context; Key : Ada.Streams.Stream_Element_Array (0 .. 63); Key_Len : Ada.Streams.Stream_Element_Offset; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.HMAC.SHA256;
----------------------------------------------------------------------- -- util-encoders-hmac-sha256 -- Compute HMAC-SHA256 authentication code -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Util.Encoders.SHA256; -- The <b>Util.Encodes.HMAC.SHA256</b> package generates HMAC-SHA256 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package Util.Encoders.HMAC.SHA256 is HASH_SIZE : constant := Util.Encoders.SHA256.HASH_SIZE; -- Sign the data string with the key and return the HMAC-SHA256 code in binary. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Hash_Array; -- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Digest; -- Sign the data array with the key and return the HMAC-SHA256 code in the result. procedure Sign (Key : in Ada.Streams.Stream_Element_Array; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array); procedure Sign (Key : in Secret_Key; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array); -- Sign the data string with the key and return the HMAC-SHA256 code as base64 string. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. function Sign_Base64 (Key : in String; Data : in String; URL : in Boolean := False) return Util.Encoders.SHA256.Base64_Digest; -- ------------------------------ -- HMAC-SHA256 Context -- ------------------------------ type Context is limited private; -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. procedure Set_Key (E : in out Context; Key : in String); -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. procedure Set_Key (E : in out Context; Key : in Ada.Streams.Stream_Element_Array); -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA256.Hash_Array); -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA256.Digest); -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. procedure Finish_Base64 (E : in out Context; Hash : out Util.Encoders.SHA256.Base64_Digest; URL : in Boolean := False); private type Context is new Ada.Finalization.Limited_Controlled with record SHA : Util.Encoders.SHA256.Context; Key : Ada.Streams.Stream_Element_Array (0 .. 63); Key_Len : Ada.Streams.Stream_Element_Offset; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.HMAC.SHA256;
Add a Sign procedure that uses a Secret_Key for the Key parameter
Add a Sign procedure that uses a Secret_Key for the Key parameter
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
509e0e1a796c071e0ad8f0a58b1afc8534e5eb71
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; rootdir : String) return Boolean is passed_check : Boolean := True; namebase : constant String := specification.get_namebase; begin directory_list.Clear; dossier_list.Clear; LOG.log_phase_begin (log_handle, phase_name); TIO.Put_Line (log_handle, "====> Checking for package manifest issues"); if not ingest_manifests (specification, log_handle, seq_id, namebase, rootdir) then passed_check := False; end if; if orphaned_directories_detected (log_handle, namebase, rootdir) then passed_check := False; end if; if missing_directories_detected (log_handle) then passed_check := False; end if; if orphaned_files_detected (log_handle, namebase, rootdir) then passed_check := False; end if; if missing_files_detected (log_handle) 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; seq_id : port_id; namebase : String; rootdir : String) return Boolean is procedure eat_plist (position : subpackage_crate.Cursor); result : Boolean := True; 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, "@dir ") then declare dir : String := line (line'First + 5 .. line'Last); dir_text : HT.Text := HT.SUS (dir); begin if directory_list.Contains (dir_text) then result := False; declare spkg : String := HT.USS (dossier_list.Element (line_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; else directory_list.Insert (dir_text, new_rec); end if; end; else declare modline : String := modify_file_if_necessary (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); dir_text : HT.Text := HT.SUS (plistdir); begin if not directory_list.Contains (dir_text) then directory_list.Insert (dir_text, new_rec); end if; 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 (candidate : String) return Boolean is -- mandatory candidate has ${STAGEDIR}/ stripped (no leading slash) rawlbase : constant String := HT.USS (PM.configuration.dir_localbase); localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last); lblen : constant Natural := localbase'Length; begin if candidate = localbase then return True; end if; if not HT.leads (candidate, localbase & "/") then -- This should never happen return False; end if; declare shortcan : String := candidate (candidate'First + lblen + 1 .. candidate'Last); 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 := candidate (candidate'First + lblen + 7 .. candidate'Last); 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; namebase : String; rootdir : String) return Boolean is rawlbase : constant String := HT.USS (PM.configuration.dir_localbase); localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last); 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); line_text : HT.Text := HT.SUS (line); begin if line /= "" then if HT.leads (line, localbase) then declare plist_dir : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last)); begin 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 (line) then TIO.Put_Line (log_handle, errprefix & line); result := True; end if; end if; end; else if directory_list.Contains (line_text) then directory_list.Update_Element (Position => directory_list.Find (line_text), Process => mark_verified'Access); else TIO.Put_Line (log_handle, errprefix & line); 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) 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) 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; namebase : String; rootdir : String) return Boolean is rawlbase : constant String := HT.USS (PM.configuration.dir_localbase); localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last); 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); line_text : HT.Text := HT.SUS (line); begin if line /= "" then if HT.leads (line, localbase) then declare plist_file : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last)); begin 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; else if dossier_list.Contains (line_text) then dossier_list.Update_Element (Position => dossier_list.Find (line_text), Process => mark_verified'Access); else TIO.Put_Line (log_handle, errprefix & line); result := True; end if; end if; end if; end; end loop; return result; end orphaned_files_detected; -------------------------------------------------------------------------------------------- -- modify_file_if_necessary -------------------------------------------------------------------------------------------- function modify_file_if_necessary (original : String) return String is function strip_raw_localbase (wrkstr : String) return String; function strip_raw_localbase (wrkstr : String) return String is rawlbase : constant String := HT.USS (PM.configuration.dir_localbase) & "/"; begin if HT.leads (wrkstr, rawlbase) then return wrkstr (wrkstr'First + rawlbase'Length .. wrkstr'Last); else return wrkstr; end if; end strip_raw_localbase; begin if HT.leads (original, "@info ") then return strip_raw_localbase (original (original'First + 6 .. original 'Last)); else return original; end if; end modify_file_if_necessary; 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; rootdir : String) return Boolean is passed_check : Boolean := True; namebase : constant String := specification.get_namebase; begin directory_list.Clear; dossier_list.Clear; LOG.log_phase_begin (log_handle, phase_name); TIO.Put_Line (log_handle, "====> Checking for package manifest issues"); if not ingest_manifests (specification, log_handle, seq_id, namebase, rootdir) then passed_check := False; end if; if orphaned_directories_detected (log_handle, namebase, rootdir) then passed_check := False; end if; if missing_directories_detected (log_handle) then passed_check := False; end if; if orphaned_files_detected (log_handle, namebase, rootdir) then passed_check := False; end if; if missing_files_detected (log_handle) 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; seq_id : port_id; namebase : 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, "@dir ") then declare dir : String := line (line'First + 5 .. line'Last); dir_text : HT.Text := HT.SUS (dir); begin if directory_list.Contains (dir_text) then result := False; declare spkg : String := HT.USS (dossier_list.Element (line_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; else insert_directory (dir, subpackage); end if; end; else declare modline : String := modify_file_if_necessary (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 (candidate : String) return Boolean is -- mandatory candidate has ${STAGEDIR}/ stripped (no leading slash) rawlbase : constant String := HT.USS (PM.configuration.dir_localbase); localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last); lblen : constant Natural := localbase'Length; begin if candidate = localbase then return True; end if; if not HT.leads (candidate, localbase & "/") then -- This should never happen return False; end if; declare shortcan : String := candidate (candidate'First + lblen + 1 .. candidate'Last); 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 := candidate (candidate'First + lblen + 7 .. candidate'Last); 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; namebase : String; rootdir : String) return Boolean is rawlbase : constant String := HT.USS (PM.configuration.dir_localbase); localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last); 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); line_text : HT.Text := HT.SUS (line); begin if line /= "" then if HT.leads (line, localbase) then declare plist_dir : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last)); begin 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 (line) then TIO.Put_Line (log_handle, errprefix & line); result := True; end if; end if; end; else if directory_list.Contains (line_text) then directory_list.Update_Element (Position => directory_list.Find (line_text), Process => mark_verified'Access); else TIO.Put_Line (log_handle, errprefix & line); 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) 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) 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; namebase : String; rootdir : String) return Boolean is rawlbase : constant String := HT.USS (PM.configuration.dir_localbase); localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last); 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); line_text : HT.Text := HT.SUS (line); begin if line /= "" then if HT.leads (line, localbase) then declare plist_file : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last)); begin 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; else if dossier_list.Contains (line_text) then dossier_list.Update_Element (Position => dossier_list.Find (line_text), Process => mark_verified'Access); else TIO.Put_Line (log_handle, errprefix & line); result := True; end if; end if; end if; end; end loop; return result; end orphaned_files_detected; -------------------------------------------------------------------------------------------- -- modify_file_if_necessary -------------------------------------------------------------------------------------------- function modify_file_if_necessary (original : String) return String is function strip_raw_localbase (wrkstr : String) return String; function strip_raw_localbase (wrkstr : String) return String is rawlbase : constant String := HT.USS (PM.configuration.dir_localbase) & "/"; begin if HT.leads (wrkstr, rawlbase) then return wrkstr (wrkstr'First + rawlbase'Length .. wrkstr'Last); else return wrkstr; end if; end strip_raw_localbase; begin if HT.leads (original, "@info ") then return strip_raw_localbase (original (original'First + 6 .. original 'Last)); else return original; end if; end modify_file_if_necessary; end PortScan.Tests;
Fix plist-check false position
Fix plist-check false position there was a case when a directory only contained directories (which might themselves contain files) where the directories were falsely marked as orphans.
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
3da2e9732521d4c365a07d52e16f6b6e547a273f
awa/src/awa-commands-drivers.ads
awa/src/awa-commands-drivers.ads
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- 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 Util.Commands.Drivers; with Util.Commands.Parsers.GNAT_Parser; with Servlet.Server; with AWA.Applications; generic Driver_Name : String; type Container_Type is limited new Servlet.Server.Container with private; package AWA.Commands.Drivers is package Main_Driver is new Util.Commands.Drivers (Context_Type => Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => Driver_Name); subtype Help_Command_Type is Main_Driver.Help_Command_Type; subtype Driver_Type is Main_Driver.Driver_Type; type Command_Type is abstract new Main_Driver.Command_Type with null record; -- 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); type Application_Command_Type is abstract new Command_Type with record Application_Name : aliased GNAT.Strings.String_Access; end record; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean; procedure Execute (Command : in out Application_Command_Type; Application : in out AWA.Applications.Application'Class; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type); overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Print the command usage. procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := ""); -- Execute the command with its arguments. procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List); Driver : Drivers.Driver_Type; WS : Container_Type; end AWA.Commands.Drivers;
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- Copyright (C) 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with GNAT.Strings; with Util.Commands.Drivers; with Util.Commands.Parsers.GNAT_Parser; with Servlet.Server; with AWA.Applications; generic Driver_Name : String; type Container_Type is limited new Servlet.Server.Container with private; package AWA.Commands.Drivers is package Main_Driver is new Util.Commands.Drivers (Context_Type => Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => Driver_Name); subtype Help_Command_Type is Main_Driver.Help_Command_Type; subtype Driver_Type is Main_Driver.Driver_Type; -- Get the server configuration file path. function Get_Configuration_Path (Context : in out Context_Type) return String; type Command_Type is abstract new Main_Driver.Command_Type with null record; -- 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); type Application_Command_Type is abstract new Command_Type with record Application_Name : aliased GNAT.Strings.String_Access; end record; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean; procedure Execute (Command : in out Application_Command_Type; Application : in out AWA.Applications.Application'Class; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type); overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Print the command usage. procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := ""); -- Execute the command with its arguments. procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List); Driver : Drivers.Driver_Type; WS : Container_Type; end AWA.Commands.Drivers;
Add Get_Configuration_Path function
Add Get_Configuration_Path function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6ad5998ecbbe891eb466294b04a01b27e1ac99db
awt/example/src/package_test.adb
awt/example/src/package_test.adb
with GL.Types; with Orka.Logging; with Orka.Resources.Locations.Directories; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Drawing; with Orka.Windows; with AWT.Drag_And_Drop; package body Package_Test is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Window_System); protected body Dnd_Signal is procedure Set is begin Dropped := True; end Set; entry Wait when Dropped is begin Dropped := False; end Wait; end Dnd_Signal; overriding function On_Close (Object : Test_Window) return Boolean is begin Messages.Log (Debug, "User is trying to close window"); return True; end On_Close; overriding procedure On_Drag (Object : in out Test_Window; X, Y : AWT.Inputs.Fixed) is use all type AWT.Inputs.Action_Kind; use type AWT.Inputs.Fixed; begin Messages.Log (Debug, "User dragged something to " & "(" & Trim (X'Image) & ", " & Trim (Y'Image) & ")"); AWT.Drag_And_Drop.Set_Action (if X < 300.0 and Y < 300.0 then Copy else None); end On_Drag; overriding procedure On_Drop (Object : in out Test_Window) is use all type AWT.Inputs.Action_Kind; Action : constant AWT.Inputs.Action_Kind := AWT.Drag_And_Drop.Valid_Action; begin Messages.Log (Info, "User dropped something. Action is " & Action'Image); if Action /= None then Dnd_Signal.Set; end if; end On_Drop; overriding procedure On_Configure (Object : in out Test_Window; State : Standard.AWT.Windows.Window_State) is begin Messages.Log (Debug, "Configured window surface"); Messages.Log (Debug, " size: " & Trim (State.Width'Image) & " × " & Trim (State.Height'Image)); Messages.Log (Debug, " margin: " & Trim (State.Margin'Image)); Object.Resize := State.Visible and State.Width > 0 and State.Height > 0; end On_Configure; procedure Initialize_Framebuffer (Object : in out Test_Window) is Alpha : constant GL.Types.Single := (if Object.State.Transparent then 0.5 else 1.0); begin Object.FB := Orka.Rendering.Framebuffers.Create_Default_Framebuffer (Object.Width, Object.Height); Object.FB.Set_Default_Values ((Color => (0.0, 0.0, 0.0, Alpha), others => <>)); Object.FB.Use_Framebuffer; Messages.Log (Debug, "Changed size of framebuffer to " & Trim (Object.Width'Image) & " × " & Trim (Object.Height'Image)); end Initialize_Framebuffer; procedure Post_Initialize (Object : in out Test_Window) is Location_Shaders : constant Orka.Resources.Locations.Location_Ptr := Orka.Resources.Locations.Directories.Create_Location ("data"); begin Object.Initialize_Framebuffer; Object.Program := Orka.Rendering.Programs.Create_Program (Orka.Rendering.Programs.Modules.Create_Module (Location_Shaders, VS => "cursor.vert", FS => "cursor.frag")); Object.Program.Use_Program; Object.Cursor := Object.Program.Uniform ("cursor"); end Post_Initialize; procedure Render (Object : in out Test_Window) is use type GL.Types.Single; use Standard.AWT.Inputs; Window_State : constant Standard.AWT.Windows.Window_State := Object.State; Pointer_State : constant Standard.AWT.Inputs.Pointer_State := Object.State; subtype Single is GL.Types.Single; Width : constant Single := Single (Window_State.Width + 2 * Window_State.Margin); Height : constant Single := Single (Window_State.Height + 2 * Window_State.Margin); PX : constant Single := Single (Pointer_State.Position (X)); PY : constant Single := Single (Pointer_State.Position (Y)); Horizontal : constant GL.Types.Single := PX / Width * 2.0 - 1.0; Vertical : constant GL.Types.Single := PY / Height * 2.0 - 1.0; begin if Object.Resize then Object.Resize := False; Object.Initialize_Framebuffer; end if; Object.FB.Clear ((Color => True, others => False)); Object.Cursor.Set_Vector (Orka.Float_32_Array'(Horizontal, -Vertical)); Orka.Rendering.Drawing.Draw (GL.Types.Points, 0, 1); Object.Swap_Buffers; end Render; overriding function Create_Window (Context : aliased Orka.Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return Test_Window is begin return Result : constant Test_Window := (Orka.Contexts.AWT.Create_Window (Context, Width, Height, Title, Samples, Visible => Visible, Resizable => Resizable, Transparent => Transparent) with others => <>); end Create_Window; end Package_Test;
with GL.Types; with Orka.Logging; with Orka.Resources.Locations.Directories; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Drawing; with Orka.Windows; with AWT.Drag_And_Drop; package body Package_Test is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Window_System); protected body Dnd_Signal is procedure Set is begin Dropped := True; end Set; entry Wait when Dropped is begin Dropped := False; end Wait; end Dnd_Signal; overriding function On_Close (Object : Test_Window) return Boolean is begin Messages.Log (Debug, "User is trying to close window"); return True; end On_Close; overriding procedure On_Drag (Object : in out Test_Window; X, Y : AWT.Inputs.Fixed) is use all type AWT.Inputs.Action_Kind; use type AWT.Inputs.Fixed; begin Messages.Log (Debug, "User dragged something to " & "(" & Trim (X'Image) & ", " & Trim (Y'Image) & ")"); AWT.Drag_And_Drop.Set_Action (if X < 300.0 and Y < 300.0 then Copy else None); end On_Drag; overriding procedure On_Drop (Object : in out Test_Window) is use all type AWT.Inputs.Action_Kind; Action : constant AWT.Inputs.Action_Kind := AWT.Drag_And_Drop.Valid_Action; begin Messages.Log (Info, "User dropped something. Action is " & Action'Image); if Action /= None then Dnd_Signal.Set; end if; end On_Drop; overriding procedure On_Configure (Object : in out Test_Window; State : Standard.AWT.Windows.Window_State) is begin Messages.Log (Debug, "Configured window surface"); Messages.Log (Debug, " size: " & Trim (State.Width'Image) & " × " & Trim (State.Height'Image)); Messages.Log (Debug, " margin: " & Trim (State.Margin'Image)); Object.Resize := State.Visible and State.Width > 0 and State.Height > 0; end On_Configure; procedure Initialize_Framebuffer (Object : in out Test_Window) is Alpha : constant Orka.Float_32 := (if Object.State.Transparent then 0.5 else 1.0); begin Object.FB := Orka.Rendering.Framebuffers.Create_Default_Framebuffer (Object.Width, Object.Height); Object.FB.Set_Default_Values ((Color => (0.0, 0.0, 0.0, Alpha), others => <>)); Object.FB.Use_Framebuffer; Messages.Log (Debug, "Changed size of framebuffer to " & Trim (Object.Width'Image) & " × " & Trim (Object.Height'Image)); end Initialize_Framebuffer; procedure Post_Initialize (Object : in out Test_Window) is Location_Shaders : constant Orka.Resources.Locations.Location_Ptr := Orka.Resources.Locations.Directories.Create_Location ("data"); begin Object.Initialize_Framebuffer; Object.Program := Orka.Rendering.Programs.Create_Program (Orka.Rendering.Programs.Modules.Create_Module (Location_Shaders, VS => "cursor.vert", FS => "cursor.frag")); Object.Program.Use_Program; Object.Cursor := Object.Program.Uniform ("cursor"); end Post_Initialize; procedure Render (Object : in out Test_Window) is use type Orka.Float_32; use Standard.AWT.Inputs; Window_State : constant Standard.AWT.Windows.Window_State := Object.State; Pointer_State : constant Standard.AWT.Inputs.Pointer_State := Object.State; subtype Float_32 is Orka.Float_32; Width : constant Float_32 := Float_32 (Window_State.Width + 2 * Window_State.Margin); Height : constant Float_32 := Float_32 (Window_State.Height + 2 * Window_State.Margin); PX : constant Float_32 := Float_32 (Pointer_State.Position (X)); PY : constant Float_32 := Float_32 (Pointer_State.Position (Y)); Horizontal : constant Float_32 := PX / Width * 2.0 - 1.0; Vertical : constant Float_32 := PY / Height * 2.0 - 1.0; begin if Object.Resize then Object.Resize := False; Object.Initialize_Framebuffer; end if; Object.FB.Clear ((Color => True, others => False)); Object.Cursor.Set_Vector (Orka.Float_32_Array'(Horizontal, -Vertical)); Orka.Rendering.Drawing.Draw (GL.Types.Points, 0, 1); Object.Swap_Buffers; end Render; overriding function Create_Window (Context : aliased Orka.Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return Test_Window is begin return Result : constant Test_Window := (Orka.Contexts.AWT.Create_Window (Context, Width, Height, Title, Samples, Visible => Visible, Resizable => Resizable, Transparent => Transparent) with others => <>); end Create_Window; end Package_Test;
Reduce dependency on package GL.Types in example a bit
awt: Reduce dependency on package GL.Types in example a bit Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
6f56e4020c217a59c07ad6fb1f26b5079776d523
src/ado-drivers.ads
src/ado-drivers.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- = Database Drivers == -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. The driver -- is either statically linked to the application and can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by <b>libada_ado_</b>. For example, for a <tt>mysql</tt> driver, the shared -- library name is <tt>libada_ado_mysql.so</tt>. -- -- == Initialization == -- The <b>ADO</b> runtime must be initialized by calling one of the <b>Initialize</b> operation. -- A property file contains the configuration for the database drivers and the database -- connection properties. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- Once initialized, a configuration property can be retrieved by using the <tt>Get_Config</tt> -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised for all errors reported by the database. Database_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- 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; private -- Initialize the drivers which are available. procedure Initialize; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- == Database Drivers == -- Database drivers provide operations to access the database. These operations are -- specific to the database type and the `ADO.Drivers` package among others provide -- an abstraction that allows to make the different databases look like they have almost -- the same interface. -- -- A database driver exists for SQLite, MySQL and PostgreSQL. The driver -- is either statically linked to the application or it can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by `libada_ado_`. For example, for a `mysql` driver, the shared -- library name is `libada_ado_mysql.so`. -- -- | Driver name | Database | -- | ----------- | --------- | -- | mysql | MySQL, MariaDB | -- | sqlite | SQLite | -- | postgresql | PostgreSQL | -- -- The database drivers are initialized automatically but in some cases, you may want -- to control some database driver configuration parameter. In that case, -- the initialization must be done only once before creating a session -- factory and getting a database connection. The initialization can be made using -- a property file which contains the configuration for the database drivers and -- the database connection properties. For such initialization, you will have to -- call one of the `Initialize` operation from the `ADO.Drivers` package. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "sqlite:///mydatabase.db"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Drivers.Initialize (Config); -- -- Once initialized, a configuration property can be retrieved by using the `Get_Config` -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- -- Dynamic loading of database drivers is disabled by default for security reasons and -- it can be enabled by setting the following property in the configuration file: -- -- ado.drivers.load=true -- -- Dynamic loading is triggered when a database connection string refers to a database -- driver which is not known. package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised for all errors reported by the database. Database_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- 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; private -- Initialize the drivers which are available. procedure Initialize; end ADO.Drivers;
Add more information about the configuration
Add more information about the configuration
Ada
apache-2.0
stcarrez/ada-ado
5abcc6d3dee1b6932f5555552dc574eb195bba27
src/natools-web-acl-sx_backends.adb
src/natools-web-acl-sx_backends.adb
------------------------------------------------------------------------------ -- Copyright (c) 2017-2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; package body Natools.Web.ACL.Sx_Backends is type Hashed_Token_List_Array is array (Hash_Id range <>) of Containers.Unsafe_Atom_Lists.List; type Hashed_Token_Map_Array is array (Hash_Id range <>) of Token_Maps.Unsafe_Maps.Map; type User_Builder (Hash_Id_First, Hash_Id_Last : Hash_Id) is record Tokens, Groups : Containers.Unsafe_Atom_Lists.List; Hashed : Hashed_Token_List_Array (Hash_Id_First .. Hash_Id_Last); end record; type Backend_Builder (Hash_Id_First, Hash_Id_Last : Hash_Id) is record Map : Token_Maps.Unsafe_Maps.Map; Hashed : Hashed_Token_Map_Array (Hash_Id_First .. Hash_Id_Last); end record; Cookie_Name : constant String := "User-Token"; Hash_Mark : constant Character := '$'; procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Read_DB is new S_Expressions.Interpreter_Loop (Backend_Builder, Meaningless_Type, Process_User); procedure Read_User is new S_Expressions.Interpreter_Loop (User_Builder, Meaningless_Type, Process_User_Element); -------------------------- -- Constructor Elements -- -------------------------- procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); User : User_Builder (Builder.Hash_Id_First, Builder.Hash_Id_Last); Identity : Containers.Identity; begin Read_User (Arguments, User, Meaningless_Value); Identity := (User => S_Expressions.Atom_Ref_Constructors.Create (Name), Groups => Containers.Create (User.Groups)); for Token of User.Tokens loop Builder.Map.Include (Token, Identity); end loop; for Id in User.Hashed'Range loop for Hashed_Token of User.Hashed (Id) loop Builder.Hashed (Id).Include (Hashed_Token, Identity); end loop; end loop; end Process_User; procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); S_Name : constant String := S_Expressions.To_String (Name); begin if S_Name = "tokens" or else S_Name = "token" then Containers.Append_Atoms (Builder.Tokens, Arguments); elsif S_Name = "groups" or else S_Name = "group" then Containers.Append_Atoms (Builder.Groups, Arguments); elsif (S_Name'Length = 8 or else (S_Name'Length = 9 and then S_Name (S_Name'Last) = 's')) and then S_Name (S_Name'First) = Hash_Mark and then S_Name (S_Name'First + 2 .. S_Name'First + 7) = Hash_Mark & "token" and then not Hash_Function_DB.Is_Empty then declare Id : constant Character := S_Name (S_Name'First + 1); Acc : constant Hash_Function_Array_Refs.Accessor := Hash_Function_DB.Query; begin if Id in Acc.Data.all'Range and then Acc.Data (Id) /= null then Containers.Append_Atoms (Builder.Hashed (Id), Arguments); else Log (Severities.Error, "Unknown hash function id" & Character'Image (Id)); end if; end; else Log (Severities.Error, "Unknown user element """ & S_Name & '"'); end if; end Process_User_Element; ---------------------- -- Public Interface -- ---------------------- overriding procedure Authenticate (Self : in Backend; Exchange : in out Exchanges.Exchange) is Cookie : constant String := Exchange.Cookie (Cookie_Name); Identity : Containers.Identity; begin if Cookie'Length > 3 and then Cookie (Cookie'First) = Hash_Mark and then Cookie (Cookie'First + 2) = Hash_Mark and then not Self.Hashed.Is_Empty and then Cookie (Cookie'First + 1) in Self.Hashed.Query.Data.all'Range then declare Token : constant S_Expressions.Atom := S_Expressions.To_Atom (Cookie (Cookie'First + 3 .. Cookie'Last)); Hash : constant S_Expressions.Atom := Hash_Function_DB.Query.Data (Cookie (Cookie'First + 1)).all (Token); Cursor : constant Token_Maps.Cursor := Self.Hashed.Query.Data (Cookie (Cookie'First + 1)).Find (Hash); begin if Token_Maps.Has_Element (Cursor) then Identity := Token_Maps.Element (Cursor); end if; end; else declare Cursor : constant Token_Maps.Cursor := Self.Map.Find (S_Expressions.To_Atom (Cookie)); begin if Token_Maps.Has_Element (Cursor) then Identity := Token_Maps.Element (Cursor); end if; end; end if; Exchange.Set_Identity (Identity); end Authenticate; function Create (Arguments : in out S_Expressions.Lockable.Descriptor'Class) return ACL.Backend'Class is Hash_Id_First : constant Hash_Id := (if Hash_Function_DB.Is_Empty then Hash_Id'Last else Hash_Function_DB.Query.Data.all'First); Hash_Id_Last : constant Hash_Id := (if Hash_Function_DB.Is_Empty then Hash_Id'First else Hash_Function_DB.Query.Data.all'Last); Builder : Backend_Builder (Hash_Id_First, Hash_Id_Last); begin case Arguments.Current_Event is when S_Expressions.Events.Open_List => Read_DB (Arguments, Builder, Meaningless_Value); when S_Expressions.Events.Add_Atom => declare Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Arguments.Current_Atom)); begin Read_DB (Reader, Builder, Meaningless_Value); end; when others => Log (Severities.Error, "Unable to create ACL from S-expression" & " starting with " & Arguments.Current_Event'Img); end case; return Backend'(Map => Token_Maps.Create (Builder.Map), Hashed => <>); end Create; procedure Register (Id : in Character; Fn : in Hash_Function) is begin if Fn = null then null; elsif Hash_Function_DB.Is_Empty then Hash_Function_DB.Replace (new Hash_Function_Array'(Id => Fn)); elsif Id in Hash_Function_DB.Query.Data.all'Range then Hash_Function_DB.Update.Data.all (Id) := Fn; else declare New_First : constant Hash_Id := Hash_Id'Min (Id, Hash_Function_DB.Query.Data.all'First); New_Last : constant Hash_Id := Hash_Id'Max (Id, Hash_Function_DB.Query.Data.all'Last); New_Data : constant Hash_Function_Array_Refs.Data_Access := new Hash_Function_Array'(New_First .. New_Last => null); begin New_Data (Hash_Function_DB.Query.Data.all'First .. Hash_Function_DB.Query.Data.all'Last) := Hash_Function_DB.Query.Data.all; Hash_Function_DB.Replace (New_Data); end; end if; end Register; end Natools.Web.ACL.Sx_Backends;
------------------------------------------------------------------------------ -- Copyright (c) 2017-2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; package body Natools.Web.ACL.Sx_Backends is type Hashed_Token_List_Array is array (Hash_Id range <>) of Containers.Unsafe_Atom_Lists.List; type Hashed_Token_Map_Array is array (Hash_Id range <>) of Token_Maps.Unsafe_Maps.Map; type User_Builder (Hash_Id_First, Hash_Id_Last : Hash_Id) is record Tokens, Groups : Containers.Unsafe_Atom_Lists.List; Hashed : Hashed_Token_List_Array (Hash_Id_First .. Hash_Id_Last); end record; type Backend_Builder (Hash_Id_First, Hash_Id_Last : Hash_Id) is record Map : Token_Maps.Unsafe_Maps.Map; Hashed : Hashed_Token_Map_Array (Hash_Id_First .. Hash_Id_Last); end record; Cookie_Name : constant String := "User-Token"; Hash_Mark : constant Character := '$'; procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Read_DB is new S_Expressions.Interpreter_Loop (Backend_Builder, Meaningless_Type, Process_User); procedure Read_User is new S_Expressions.Interpreter_Loop (User_Builder, Meaningless_Type, Process_User_Element); -------------------------- -- Constructor Elements -- -------------------------- procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); User : User_Builder (Builder.Hash_Id_First, Builder.Hash_Id_Last); Identity : Containers.Identity; begin Read_User (Arguments, User, Meaningless_Value); Identity := (User => S_Expressions.Atom_Ref_Constructors.Create (Name), Groups => Containers.Create (User.Groups)); for Token of User.Tokens loop Builder.Map.Include (Token, Identity); end loop; for Id in User.Hashed'Range loop for Hashed_Token of User.Hashed (Id) loop Builder.Hashed (Id).Include (Hashed_Token, Identity); end loop; end loop; end Process_User; procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); S_Name : constant String := S_Expressions.To_String (Name); begin if S_Name = "tokens" or else S_Name = "token" then Containers.Append_Atoms (Builder.Tokens, Arguments); elsif S_Name = "groups" or else S_Name = "group" then Containers.Append_Atoms (Builder.Groups, Arguments); elsif (S_Name'Length = 8 or else (S_Name'Length = 9 and then S_Name (S_Name'Last) = 's')) and then S_Name (S_Name'First) = Hash_Mark and then S_Name (S_Name'First + 2 .. S_Name'First + 7) = Hash_Mark & "token" and then not Hash_Function_DB.Is_Empty then declare Id : constant Character := S_Name (S_Name'First + 1); Acc : constant Hash_Function_Array_Refs.Accessor := Hash_Function_DB.Query; begin if Id in Acc.Data.all'Range and then Acc.Data (Id) /= null then Containers.Append_Atoms (Builder.Hashed (Id), Arguments); else Log (Severities.Error, "Unknown hash function id" & Character'Image (Id)); end if; end; else Log (Severities.Error, "Unknown user element """ & S_Name & '"'); end if; end Process_User_Element; ---------------------- -- Public Interface -- ---------------------- overriding procedure Authenticate (Self : in Backend; Exchange : in out Exchanges.Exchange) is Cookie : constant String := Exchange.Cookie (Cookie_Name); Identity : Containers.Identity; begin if Cookie'Length > 3 and then Cookie (Cookie'First) = Hash_Mark and then Cookie (Cookie'First + 2) = Hash_Mark and then not Self.Hashed.Is_Empty and then Cookie (Cookie'First + 1) in Self.Hashed.Query.Data.all'Range then declare Token : constant S_Expressions.Atom := S_Expressions.To_Atom (Cookie (Cookie'First + 3 .. Cookie'Last)); Hash : constant S_Expressions.Atom := Hash_Function_DB.Query.Data (Cookie (Cookie'First + 1)).all (Token); Cursor : constant Token_Maps.Cursor := Self.Hashed.Query.Data (Cookie (Cookie'First + 1)).Find (Hash); begin if Token_Maps.Has_Element (Cursor) then Identity := Token_Maps.Element (Cursor); end if; end; else declare Cursor : constant Token_Maps.Cursor := Self.Map.Find (S_Expressions.To_Atom (Cookie)); begin if Token_Maps.Has_Element (Cursor) then Identity := Token_Maps.Element (Cursor); end if; end; end if; Exchange.Set_Identity (Identity); end Authenticate; function Create (Arguments : in out S_Expressions.Lockable.Descriptor'Class) return ACL.Backend'Class is Hash_Id_First : constant Hash_Id := (if Hash_Function_DB.Is_Empty then Hash_Id'Last else Hash_Function_DB.Query.Data.all'First); Hash_Id_Last : constant Hash_Id := (if Hash_Function_DB.Is_Empty then Hash_Id'First else Hash_Function_DB.Query.Data.all'Last); Builder : Backend_Builder (Hash_Id_First, Hash_Id_Last); begin case Arguments.Current_Event is when S_Expressions.Events.Open_List => Read_DB (Arguments, Builder, Meaningless_Value); when S_Expressions.Events.Add_Atom => declare Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Arguments.Current_Atom)); begin Read_DB (Reader, Builder, Meaningless_Value); end; when others => Log (Severities.Error, "Unable to create ACL from S-expression" & " starting with " & Arguments.Current_Event'Img); end case; return Result : Backend := (Map => Token_Maps.Create (Builder.Map), Hashed => <>) do declare Min : Hash_Id := Hash_Id'Last; Max : Hash_Id := Hash_Id'First; begin for Id in Builder.Hashed'Range loop if not Builder.Hashed (Id).Is_Empty then -- Hash_Id'Min seems broken, using a basic `if` instead if Id < Min then Min := Id; end if; if Id > Max then Max := Id; end if; end if; end loop; if Min <= Max then declare Data : constant Hashed_Token_Array_Refs.Data_Access := new Hashed_Token_Array (Min .. Max); begin Result.Hashed := Hashed_Token_Array_Refs.Create (Data); for Id in Min .. Max loop if not Builder.Hashed (Id).Is_Empty then Data (Id) := Token_Maps.Create (Builder.Hashed (Id)); end if; end loop; end; end if; end; end return; end Create; procedure Register (Id : in Character; Fn : in Hash_Function) is begin if Fn = null then null; elsif Hash_Function_DB.Is_Empty then Hash_Function_DB.Replace (new Hash_Function_Array'(Id => Fn)); elsif Id in Hash_Function_DB.Query.Data.all'Range then Hash_Function_DB.Update.Data.all (Id) := Fn; else declare New_First : constant Hash_Id := Hash_Id'Min (Id, Hash_Function_DB.Query.Data.all'First); New_Last : constant Hash_Id := Hash_Id'Max (Id, Hash_Function_DB.Query.Data.all'Last); New_Data : constant Hash_Function_Array_Refs.Data_Access := new Hash_Function_Array'(New_First .. New_Last => null); begin Log (Severities.Info, "Adding " & Id'Img & " to " & Hash_Function_DB.Query.Data.all'First'Img & " .. " & Hash_Function_DB.Query.Data.all'Last'Img & " -> " & New_First'Img & " .. " & New_Last'Img); New_Data (Hash_Function_DB.Query.Data.all'First .. Hash_Function_DB.Query.Data.all'Last) := Hash_Function_DB.Query.Data.all; Hash_Function_DB.Replace (New_Data); end; end if; end Register; end Natools.Web.ACL.Sx_Backends;
store the hashed tokens in the backend
acl-sx_backends: store the hashed tokens in the backend
Ada
isc
faelys/natools-web,faelys/natools-web
89f1cdb0a0184907eac8ad4d74023bae47368359
src/util-encoders-hmac-sha1.ads
src/util-encoders-hmac-sha1.ads
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code -- 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.Streams; with Ada.Finalization; with Util.Encoders.SHA1; -- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package Util.Encoders.HMAC.SHA1 is pragma Preelaborate; -- Sign the data string with the key and return the HMAC-SHA1 code in binary. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Hash_Array; -- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Digest; -- Sign the data string with the key and return the HMAC-SHA1 code as base64 string. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. function Sign_Base64 (Key : in String; Data : in String; URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest; -- ------------------------------ -- HMAC-SHA1 Context -- ------------------------------ type Context is limited private; -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. procedure Set_Key (E : in out Context; Key : in String); -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. procedure Set_Key (E : in out Context; Key : in Ada.Streams.Stream_Element_Array); -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA1.Hash_Array); -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA1.Digest); -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. procedure Finish_Base64 (E : in out Context; Hash : out Util.Encoders.SHA1.Base64_Digest; URL : in Boolean := False); -- ------------------------------ -- HMAC-SHA1 encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); private type Encoder is new Util.Encoders.Transformer with null record; type Context is new Ada.Finalization.Limited_Controlled with record SHA : Util.Encoders.SHA1.Context; Key : Ada.Streams.Stream_Element_Array (0 .. 63); Key_Len : Ada.Streams.Stream_Element_Offset; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.HMAC.SHA1;
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Util.Encoders.SHA1; -- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package Util.Encoders.HMAC.SHA1 is pragma Preelaborate; -- Sign the data string with the key and return the HMAC-SHA1 code in binary. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Hash_Array; -- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Digest; -- Sign the data string with the key and return the HMAC-SHA1 code as base64 string. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. function Sign_Base64 (Key : in String; Data : in String; URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest; -- ------------------------------ -- HMAC-SHA1 Context -- ------------------------------ type Context is limited private; -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. procedure Set_Key (E : in out Context; Key : in String); -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. procedure Set_Key (E : in out Context; Key : in Ada.Streams.Stream_Element_Array); -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA1.Hash_Array); -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA1.Digest); -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. procedure Finish_Base64 (E : in out Context; Hash : out Util.Encoders.SHA1.Base64_Digest; URL : in Boolean := False); -- ------------------------------ -- HMAC-SHA1 encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); private type Encoder is new Util.Encoders.Transformer with null record; type Context is new Ada.Finalization.Limited_Controlled with record SHA : Util.Encoders.SHA1.Context; Key : Ada.Streams.Stream_Element_Array (0 .. 63); Key_Len : Ada.Streams.Stream_Element_Offset; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.HMAC.SHA1;
Change the Transformer interface to accept in out parameter for the Transformer
Change the Transformer interface to accept in out parameter for the Transformer
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
802123db3871e805c94ad8d2cd10a955bb1d4416
src/asf-responses.ads
src/asf-responses.ads
----------------------------------------------------------------------- -- asf.responses -- ASF Requests -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Finalization; with ASF.Streams; with ASF.Cookies; private with Util.Streams.Texts; -- The <b>ASF.Responses</b> package is an Ada implementation of -- the Java servlet response (JSR 315 5. The Response). package ASF.Responses is SC_CONTINUE : constant Natural := 100; SC_SWITCHING_PROTOCOLS : constant Natural := 101; SC_OK : constant Natural := 200; SC_CREATED : constant Natural := 201; SC_ACCEPTED : constant Natural := 202; SC_NON_AUTHORITATIVE_INFORMATION : constant Natural := 203; SC_NO_CONTENT : constant Natural := 204; SC_RESET_CONTENT : constant Natural := 205; SC_PARTIAL_CONTENT : constant Natural := 206; SC_MULTIPLE_CHOICES : constant Natural := 300; SC_MOVED_PERMANENTLY : constant Natural := 301; SC_MOVED_TEMPORARILY : constant Natural := 302; SC_FOUND : constant Natural := 302; SC_SEE_OTHER : constant Natural := 303; SC_NOT_MODIFIED : constant Natural := 304; SC_USE_PROXY : constant Natural := 305; SC_TEMPORARY_REDIRECT : constant Natural := 307; SC_BAD_REQUEST : constant Natural := 400; SC_UNAUTHORIZED : constant Natural := 401; SC_PAYMENT_REQUIRED : constant Natural := 402; SC_FORBIDDEN : constant Natural := 403; SC_NOT_FOUND : constant Natural := 404; SC_METHOD_NOT_ALLOWED : constant Natural := 405; SC_NOT_ACCEPTABLE : constant Natural := 406; SC_PROXY_AUTHENTICATION_REQUIRED : constant Natural := 407; SC_REQUEST_TIMEOUT : constant Natural := 408; SC_CONFLICT : constant Natural := 409; SC_GONE : constant Natural := 410; SC_LENGTH_REQUIRED : constant Natural := 411; SC_PRECONDITION_FAILED : constant Natural := 412; SC_REQUEST_ENTITY_TOO_LARGE : constant Natural := 413; SC_REQUEST_URI_TOO_LONG : constant Natural := 414; SC_UNSUPPORTED_MEDIA_TYPE : constant Natural := 415; SC_REQUESTED_RANGE_NOT_SATISFIABLE : constant Natural := 416; SC_EXPECTATION_FAILED : constant Natural := 417; SC_INTERNAL_SERVER_ERROR : constant Natural := 500; SC_NOT_IMPLEMENTED : constant Natural := 501; SC_BAD_GATEWAY : constant Natural := 502; SC_SERVICE_UNAVAILABLE : constant Natural := 503; SC_GATEWAY_TIMEOUT : constant Natural := 504; SC_HTTP_VERSION_NOT_SUPPORTED : constant Natural := 505; type Response is abstract tagged limited private; type Response_Access is access all Response'Class; -- Returns the name of the character encoding (MIME charset) used for the body -- sent in this response. The character encoding may have been specified explicitly -- using the setCharacterEncoding(String) or setContentType(String) methods, -- or implicitly using the setLocale(java.util.Locale) method. Explicit -- specifications take precedence over implicit specifications. Calls made -- to these methods after getWriter has been called or after the response has -- been committed have no effect on the character encoding. If no character -- encoding has been specified, ISO-8859-1 is returned. function Get_Character_Encoding (Resp : in Response) return String; -- Returns the content type used for the MIME body sent in this response. -- The content type proper must have been specified using -- setContentType(String) before the response is committed. If no content type -- has been specified, this method returns null. If a content type has been -- specified, and a character encoding has been explicitly or implicitly specified -- as described in getCharacterEncoding() or getWriter() has been called, -- the charset parameter is included in the string returned. If no character -- encoding has been specified, the charset parameter is omitted. function Get_Content_Type (Resp : in Response) return String; -- Sets the character encoding (MIME charset) of the response being sent to the -- client, for example, to UTF-8. If the character encoding has already been -- set by setContentType(java.lang.String) or setLocale(java.util.Locale), -- this method overrides it. Calling setContentType(java.lang.String) with the -- String of text/html and calling this method with the String of UTF-8 is -- equivalent with calling setContentType with the String of text/html; charset=UTF-8. -- -- This method can be called repeatedly to change the character encoding. -- This method has no effect if it is called after getWriter has been called or -- after the response has been committed. -- -- Containers must communicate the character encoding used for the servlet -- response's writer to the client if the protocol provides a way for doing so. -- In the case of HTTP, the character encoding is communicated as part of the -- Content-Type header for text media types. Note that the character encoding -- cannot be communicated via HTTP headers if the servlet does not specify -- a content type; however, it is still used to encode text written via the servlet -- response's writer. procedure Set_Character_Encoding (Resp : in out Response; Encoding : in String); -- Sets the length of the content body in the response In HTTP servlets, -- this method sets the HTTP Content-Length header. procedure Set_Content_Length (Resp : in out Response; Length : in Integer); -- Sets the content type of the response being sent to the client, if the response -- has not been committed yet. The given content type may include a character -- encoding specification, for example, text/html;charset=UTF-8. The response's -- character encoding is only set from the given content type if this method is -- called before getWriter is called. -- -- This method may be called repeatedly to change content type and character -- encoding. This method has no effect if called after the response has been -- committed. It does not set the response's character encoding if it is called -- after getWriter has been called or after the response has been committed. -- -- Containers must communicate the content type and the character encoding used -- for the servlet response's writer to the client if the protocol provides a way -- for doing so. In the case of HTTP, the Content-Type header is used. procedure Set_Content_Type (Resp : in out Response; Content : in String); -- Returns a boolean indicating if the response has been committed. -- A committed response has already had its status code and headers written. function Is_Committed (Resp : in Response) return Boolean; -- Sets the locale of the response, if the response has not been committed yet. -- It also sets the response's character encoding appropriately for the locale, -- if the character encoding has not been explicitly set using -- setContentType(java.lang.String) or setCharacterEncoding(java.lang.String), -- getWriter hasn't been called yet, and the response hasn't been committed yet. -- If the deployment descriptor contains a locale-encoding-mapping-list element, -- and that element provides a mapping for the given locale, that mapping is used. -- Otherwise, the mapping from locale to character encoding is container dependent. -- -- This method may be called repeatedly to change locale and character encoding. -- The method has no effect if called after the response has been committed. -- It does not set the response's character encoding if it is called after -- setContentType(java.lang.String) has been called with a charset specification, -- after setCharacterEncoding(java.lang.String) has been called, -- after getWriter has been called, or after the response has been committed. -- -- Containers must communicate the locale and the character encoding used for -- the servlet response's writer to the client if the protocol provides a way -- for doing so. In the case of HTTP, the locale is communicated via the -- Content-Language header, the character encoding as part of the Content-Type -- header for text media types. Note that the character encoding cannot be -- communicated via HTTP headers if the servlet does not specify a content type; -- however, it is still used to encode text written via the servlet response's writer. procedure Set_Locale (Resp : in out Response; Loc : in Util.Locales.Locale); -- Returns the locale specified for this response using the -- setLocale(java.util.Locale) method. Calls made to setLocale after the -- response is committed have no effect. If no locale has been specified, -- the container's default locale is returned. function Get_Locale (Resp : in Response) return Util.Locales.Locale; -- Adds the specified cookie to the response. This method can be called multiple -- times to set more than one cookie. procedure Add_Cookie (Resp : in out Response; Cookie : in ASF.Cookies.Cookie); -- Returns a boolean indicating whether the named response header has already -- been set. function Contains_Header (Resp : in Response; Name : in String) return Boolean is abstract; -- Iterate over the response headers and executes the <b>Process</b> procedure. procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is abstract; -- Encodes the specified URL by including the session ID in it, or, if encoding -- is not needed, returns the URL unchanged. The implementation of this method -- includes the logic to determine whether the session ID needs to be encoded -- in the URL. For example, if the browser supports cookies, or session tracking -- is turned off, URL encoding is unnecessary. -- -- For robust session tracking, all URLs emitted by a servlet should be run through -- this method. Otherwise, URL rewriting cannot be used with browsers which do not -- support cookies. function Encode_URL (Resp : in Response; URL : in String) return String; -- Encodes the specified URL for use in the sendRedirect method or, if encoding -- is not needed, returns the URL unchanged. The implementation of this method -- includes the logic to determine whether the session ID needs to be encoded -- in the URL. Because the rules for making this determination can differ from -- those used to decide whether to encode a normal link, this method is separated -- from the encodeURL method. -- -- All URLs sent to the HttpServletResponse.sendRedirect method should be run -- through this method. Otherwise, URL rewriting cannot be used with browsers -- which do not support cookies. function Encode_Redirect_URL (Resp : in Response; URL : in String) return String; -- Sends an error response to the client using the specified status. The server -- defaults to creating the response to look like an HTML-formatted server error -- page containing the specified message, setting the content type to "text/html", -- leaving cookies and other headers unmodified. If an error-page declaration -- has been made for the web application corresponding to the status code passed -- in, it will be served back in preference to the suggested msg parameter. -- -- If the response has already been committed, this method throws an -- IllegalStateException. After using this method, the response should be -- considered to be committed and should not be written to. procedure Send_Error (Resp : in out Response; Error : in Integer; Message : in String); -- Sends an error response to the client using the specified status code -- and clearing the buffer. -- -- If the response has already been committed, this method throws an -- IllegalStateException. After using this method, the response should be -- considered to be committed and should not be written to. procedure Send_Error (Resp : in out Response; Error : in Integer); -- Sends a temporary redirect response to the client using the specified redirect -- location URL. This method can accept relative URLs; the servlet container must -- convert the relative URL to an absolute URL before sending the response to the -- client. If the location is relative without a leading '/' the container -- interprets it as relative to the current request URI. If the location is relative -- with a leading '/' the container interprets it as relative to the servlet -- container root. -- -- If the response has already been committed, this method throws an -- IllegalStateException. After using this method, the response should be -- considered to be committed and should not be written to. procedure Send_Redirect (Resp : in out Response; Location : in String); -- Sets a response header with the given name and date-value. -- The date is specified in terms of milliseconds since the epoch. -- If the header had already been set, the new value overwrites the previous one. -- The containsHeader method can be used to test for the presence of a header -- before setting its value. procedure Set_Date_Header (Resp : in out Response; Name : in String; Date : in Ada.Calendar.Time); -- Adds a response header with the given name and date-value. The date is specified -- in terms of milliseconds since the epoch. This method allows response headers -- to have multiple values. procedure Add_Date_Header (Resp : in out Response; Name : in String; Date : in Ada.Calendar.Time); -- Sets a response header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. procedure Set_Header (Resp : in out Response; Name : in String; Value : in String); -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. procedure Add_Header (Resp : in out Response; Name : in String; Value : in String); -- Sets a response header with the given name and integer value. -- If the header had already been set, the new value overwrites the previous one. -- The containsHeader method can be used to test for the presence of a header -- before setting its value. procedure Set_Int_Header (Resp : in out Response; Name : in String; Value : in Integer); -- Adds a response header with the given name and integer value. This method -- allows response headers to have multiple values. procedure Add_Int_Header (Resp : in out Response; Name : in String; Value : in Integer); -- Sets the status code for this response. This method is used to set the -- return status code when there is no error (for example, for the status -- codes SC_OK or SC_MOVED_TEMPORARILY). If there is an error, and the caller -- wishes to invoke an error-page defined in the web application, the sendError -- method should be used instead. -- -- The container clears the buffer and sets the Location header, -- preserving cookies and other headers. procedure Set_Status (Resp : in out Response; Status : in Natural); -- Get the status code that will be returned by this response. function Get_Status (Resp : in Response) return Natural; -- Get the output stream function Get_Output_Stream (Resp : in Response) return ASF.Streams.Print_Stream; private type Response is abstract new Ada.Finalization.Limited_Controlled with record Status : Integer := SC_OK; Stream : Util.Streams.Texts.Print_Stream_Access; Content_Type : Ada.Strings.Unbounded.Unbounded_String; Locale : Util.Locales.Locale; end record; end ASF.Responses;
----------------------------------------------------------------------- -- asf-responses -- ASF Responses -- Copyright (C) 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Servlet.Responses; package ASF.Responses renames Servlet.Responses;
Package ASF.Responses moved to Servlet.Responses
Package ASF.Responses moved to Servlet.Responses
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
d05195fab2b6bb8a4625202bdd3f4040290a2abc
components/sdram/stm32-sdram.adb
components/sdram/stm32-sdram.adb
with Ada.Real_Time; use Ada.Real_Time; with STM32.Board; use STM32.Board; with STM32.Device; use STM32.Device; with STM32.FMC; use STM32.FMC; with STM32.GPIO; use STM32.GPIO; with STM32_SVD.RCC; use STM32_SVD.RCC; package body STM32.SDRAM is Initialized : Boolean := False; G_Base_Addr : Word; procedure SDRAM_GPIOConfig; procedure SDRAM_InitSequence; ---------------------- -- SDRAM_GPIOConfig -- ---------------------- procedure SDRAM_GPIOConfig is begin Enable_Clock (SDRAM_PINS); Configure_IO (SDRAM_PINS, (Speed => Speed_100MHz, Mode => Mode_AF, Output_Type => Push_Pull, Resistors => Pull_Up)); Configure_Alternate_Function (SDRAM_Pins, GPIO_AF_FMC); Lock (SDRAM_PINS); end SDRAM_GPIOConfig; ------------------------ -- SDRAM_InitSequence -- ------------------------ procedure SDRAM_InitSequence is CAS : SDRAM_Mode_CAS_Latency; begin loop exit when not FMC_SDRAM_Busy; end loop; FMC_SDRAM_Cmd ((Mode => FMC_Command_Mode_CLK_Enabled, Target => SDRAM_Bank)); loop exit when not FMC_SDRAM_Busy; end loop; delay until Clock + Milliseconds (1); FMC_SDRAM_Cmd ((Mode => FMC_Command_Mode_PALL, Target => SDRAM_Bank)); loop exit when not FMC_SDRAM_Busy; end loop; FMC_SDRAM_Cmd ((Mode => FMC_Command_Mode_AutoRefresh, Target => SDRAM_Bank, Auto_Refresh_Number => 8)); loop exit when not FMC_SDRAM_Busy; end loop; case SDRAM_CAS_Latency is when FMC_CAS_Latency_1 | FMC_CAS_Latency_2 => CAS := SDRAM_Mode_CAS_Latency_2; when FMC_CAS_Latency_3 => CAS := SDRAM_Mode_CAS_Latency_3; end case; FMC_SDRAM_Cmd ((Mode => FMC_Command_Mode_LoadMode, Target => SDRAM_Bank, Mode_Register => (SDRAM_Mode_Burst_Length_1, SDRAM_Mode_Burst_Sequential, CAS, SDRAM_Mode_Writeburst_Mode_Single))); loop exit when not FMC_SDRAM_Busy; end loop; FMC_Set_Refresh_Count (SDRAM_Refresh_Cnt); loop exit when not FMC_SDRAM_Busy; end loop; end SDRAM_InitSequence; ---------------- -- Initialize -- ---------------- procedure Initialize is Timing_Conf : FMC_SDRAM_TimingInit_Config; SDRAM_Conf : FMC_SDRAM_Init_Config; begin if Initialized then return; end if; Initialized := True; G_Base_Addr := SDRAM_Base; ------------------------ -- GPIO CONFIGURATION -- ------------------------ SDRAM_GPIOConfig; -------------- -- FMC_INIT -- -------------- RCC_Periph.AHB3ENR.FMCEN := True; RCC_Periph.AHB3RSTR.FMCRST := True; RCC_Periph.AHB3RSTR.FMCRST := False; -- 90 MHz of SD clock frequency (180MHz / 2) -- 1 Clock cycle = 1 / 90MHz = 11.1ns Timing_Conf := ( -- 2 Clock cycles for Load to Active delay LoadToActiveDelay => 2, -- min = 70ns: 7 * 11.1 ExitSelfRefreshDelay => 7, -- in range [42ns, 120k ns] => using 4 * 11.1 ns SelfRefreshTime => 4, -- min = 70ns RowCycleDelay => 7, -- min = 20ns WriteRecoveryTime => 2, RPDelay => 2, RCDDelay => 2); SDRAM_Conf := (Bank => SDRAM_Bank, ColumnBitsNumber => FMC_ColumnBits_Number_8b, RowBitsNumber => SDRAM_Row_Bits, SDMemoryDataWidth => SDRAM_Mem_Width, InternalBankNumber => FMC_InternalBank_Number_4, CASLatency => SDRAM_CAS_Latency, WriteProtection => FMC_Write_Protection_Disable, SDClockPeriod => SDRAM_CLOCK_Period, ReadBurst => SDRAM_Read_Burst, ReadPipeDelay => SDRAM_Read_Pipe, Timing_Conf => Timing_Conf); FMC_SDRAM_Init (SDRAM_Conf); if SDRAM_Conf.Bank /= FMC_Bank1_SDRAM then SDRAM_Conf.Bank := FMC_Bank1_SDRAM; FMC_SDRAM_Init (SDRAM_Conf); end if; SDRAM_InitSequence; end Initialize; ------------------ -- Base_Address -- ------------------ function Base_Address return System.Address is begin return System'To_Address (G_Base_Addr); end Base_Address; ------------- -- Reserve -- ------------- function Reserve (Amount : Word; Align : Word := Standard'Maximum_Alignment) return System.Address is Ret : constant System.Address := System'To_Address (G_Base_Addr); Rounded_Size : Word; begin Initialize; Rounded_Size := Amount + Align; Rounded_Size := Rounded_Size - Rounded_Size rem Align; G_Base_Addr := G_Base_Addr + Rounded_Size; return Ret; end Reserve; end STM32.SDRAM;
with Ada.Real_Time; use Ada.Real_Time; with STM32.Board; use STM32.Board; with STM32.Device; use STM32.Device; with STM32.FMC; use STM32.FMC; with STM32.GPIO; use STM32.GPIO; with STM32_SVD.RCC; use STM32_SVD.RCC; package body STM32.SDRAM is Initialized : Boolean := False; G_Base_Addr : Word; procedure SDRAM_GPIOConfig; procedure SDRAM_InitSequence; ---------------------- -- SDRAM_GPIOConfig -- ---------------------- procedure SDRAM_GPIOConfig is begin Enable_Clock (SDRAM_PINS); Configure_IO (SDRAM_PINS, (Speed => Speed_50MHz, Mode => Mode_AF, Output_Type => Push_Pull, Resistors => Pull_Up)); Configure_Alternate_Function (SDRAM_Pins, GPIO_AF_FMC); Lock (SDRAM_PINS); end SDRAM_GPIOConfig; ------------------------ -- SDRAM_InitSequence -- ------------------------ procedure SDRAM_InitSequence is CAS : SDRAM_Mode_CAS_Latency; begin loop exit when not FMC_SDRAM_Busy; end loop; FMC_SDRAM_Cmd ((Mode => FMC_Command_Mode_CLK_Enabled, Target => SDRAM_Bank)); loop exit when not FMC_SDRAM_Busy; end loop; delay until Clock + Milliseconds (1); FMC_SDRAM_Cmd ((Mode => FMC_Command_Mode_PALL, Target => SDRAM_Bank)); loop exit when not FMC_SDRAM_Busy; end loop; FMC_SDRAM_Cmd ((Mode => FMC_Command_Mode_AutoRefresh, Target => SDRAM_Bank, Auto_Refresh_Number => 8)); loop exit when not FMC_SDRAM_Busy; end loop; case SDRAM_CAS_Latency is when FMC_CAS_Latency_1 | FMC_CAS_Latency_2 => CAS := SDRAM_Mode_CAS_Latency_2; when FMC_CAS_Latency_3 => CAS := SDRAM_Mode_CAS_Latency_3; end case; FMC_SDRAM_Cmd ((Mode => FMC_Command_Mode_LoadMode, Target => SDRAM_Bank, Mode_Register => (SDRAM_Mode_Burst_Length_1, SDRAM_Mode_Burst_Sequential, CAS, SDRAM_Mode_Writeburst_Mode_Single))); loop exit when not FMC_SDRAM_Busy; end loop; FMC_Set_Refresh_Count (SDRAM_Refresh_Cnt); loop exit when not FMC_SDRAM_Busy; end loop; end SDRAM_InitSequence; ---------------- -- Initialize -- ---------------- procedure Initialize is Timing_Conf : FMC_SDRAM_TimingInit_Config; SDRAM_Conf : FMC_SDRAM_Init_Config; begin if Initialized then return; end if; Initialized := True; G_Base_Addr := SDRAM_Base; ------------------------ -- GPIO CONFIGURATION -- ------------------------ SDRAM_GPIOConfig; -------------- -- FMC_INIT -- -------------- RCC_Periph.AHB3ENR.FMCEN := True; RCC_Periph.AHB3RSTR.FMCRST := True; RCC_Periph.AHB3RSTR.FMCRST := False; -- 90 MHz of SD clock frequency (180MHz / 2) -- 1 Clock cycle = 1 / 90MHz = 11.1ns Timing_Conf := ( -- 2 Clock cycles for Load to Active delay LoadToActiveDelay => 2, -- min = 70ns: 7 * 11.1 ExitSelfRefreshDelay => 7, -- in range [42ns, 120k ns] => using 4 * 11.1 ns SelfRefreshTime => 4, -- min = 70ns RowCycleDelay => 7, -- min = 20ns WriteRecoveryTime => 2, RPDelay => 2, RCDDelay => 2); SDRAM_Conf := (Bank => SDRAM_Bank, ColumnBitsNumber => FMC_ColumnBits_Number_8b, RowBitsNumber => SDRAM_Row_Bits, SDMemoryDataWidth => SDRAM_Mem_Width, InternalBankNumber => FMC_InternalBank_Number_4, CASLatency => SDRAM_CAS_Latency, WriteProtection => FMC_Write_Protection_Disable, SDClockPeriod => SDRAM_CLOCK_Period, ReadBurst => SDRAM_Read_Burst, ReadPipeDelay => SDRAM_Read_Pipe, Timing_Conf => Timing_Conf); FMC_SDRAM_Init (SDRAM_Conf); if SDRAM_Conf.Bank /= FMC_Bank1_SDRAM then SDRAM_Conf.Bank := FMC_Bank1_SDRAM; FMC_SDRAM_Init (SDRAM_Conf); end if; SDRAM_InitSequence; end Initialize; ------------------ -- Base_Address -- ------------------ function Base_Address return System.Address is begin return System'To_Address (G_Base_Addr); end Base_Address; ------------- -- Reserve -- ------------- function Reserve (Amount : Word; Align : Word := Standard'Maximum_Alignment) return System.Address is Ret : constant System.Address := System'To_Address (G_Base_Addr); Rounded_Size : Word; begin Initialize; Rounded_Size := Amount + Align; Rounded_Size := Rounded_Size - Rounded_Size rem Align; G_Base_Addr := G_Base_Addr + Rounded_Size; return Ret; end Reserve; end STM32.SDRAM;
Fix SDRAM pin configuration
Fix SDRAM pin configuration
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
258bc7b83cb14b236dcfa0697cca6b1f566e3b03
src/gen-generator.ads
src/gen-generator.ads
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; package Gen.Generator is -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; G_URI : constant String := "http://code.google.com/p/ada-ado/generator"; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in Ada.Strings.Unbounded.Unbounded_String; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in String); -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : Unbounded_String; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : Ada.Strings.Unbounded.Unbounded_String; -- Output base directory. Output_Dir : Ada.Strings.Unbounded.Unbounded_String; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : access Util.Beans.Objects.Object; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : access Util.Beans.Objects.Object; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : access Util.Beans.Objects.Object; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with ASF.Servlets.Files; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; package Gen.Generator is -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; G_URI : constant String := "http://code.google.com/p/ada-ado/generator"; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in Ada.Strings.Unbounded.Unbounded_String; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in String); -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : Unbounded_String; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : Ada.Strings.Unbounded.Unbounded_String; -- Output base directory. Output_Dir : Ada.Strings.Unbounded.Unbounded_String; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : access Util.Beans.Objects.Object; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : access Util.Beans.Objects.Object; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : access Util.Beans.Objects.Object; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; -- A fake servlet for template evaluation. Servlet : ASF.Servlets.Servlet_Access; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
Add a file servlet to be able to use the <util:file> component in templates
Add a file servlet to be able to use the <util:file> component in templates
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
6e015360dda93d5744d046f7a27b57f6e869d385
awa/plugins/awa-storages/src/awa-storages-stores.ads
awa/plugins/awa-storages/src/awa-storages-stores.ads
----------------------------------------------------------------------- -- awa-storages-stores -- The storage interface -- 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 ADO.Sessions; with AWA.Storages.Models; -- == Store Service == -- The `AWA.Storages.Stores` package defines the interface that a store must implement to -- be able to save and retrieve a data content. -- -- @include awa-storages-stores-databases.ads -- @include awa-storages-stores-files.ads package AWA.Storages.Stores is -- ------------------------------ -- Store Service -- ------------------------------ type Store is limited interface; type Store_Access is access all Store'Class; -- Create a storage procedure Create (Storage : in Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is abstract; -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. procedure Save (Storage : in Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is abstract; -- Load the storage item represented by `From` in a file that can be accessed locally. procedure Load (Storage : in Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is abstract; -- Delete the content associate with the storage represented by `From`. procedure Delete (Storage : in Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class) is abstract; end AWA.Storages.Stores;
----------------------------------------------------------------------- -- awa-storages-stores -- The storage interface -- 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 ADO.Sessions; with AWA.Storages.Models; -- == Store Service == -- The `AWA.Storages.Stores` package defines the interface that a store must implement to -- be able to save and retrieve a data content. The store can be a file system, a database -- or a remote store service. -- -- @include awa-storages-stores-databases.ads -- @include awa-storages-stores-files.ads package AWA.Storages.Stores is -- ------------------------------ -- Store Service -- ------------------------------ type Store is limited interface; type Store_Access is access all Store'Class; -- Create a storage procedure Create (Storage : in Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is abstract; -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. procedure Save (Storage : in Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is abstract; -- Load the storage item represented by `From` in a file that can be accessed locally. procedure Load (Storage : in Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is abstract; -- Delete the content associate with the storage represented by `From`. procedure Delete (Storage : in Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class) is abstract; end AWA.Storages.Stores;
Update comment
Update comment
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
9a24808d08fe336a7d03b26ad8cf9ea9ce3e880f
awa/src/awa-commands-stop.adb
awa/src/awa-commands-stop.adb
----------------------------------------------------------------------- -- awa-commands-stop -- Command to stop 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.Sockets; with Util.Streams.Sockets; with Util.Streams.Texts; package body AWA.Commands.Stop is -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); GC.Define_Switch (Config => Config, Output => Command.Management_Port'Access, Switch => "-m:", Long_Switch => "--management-port=", Initial => Command.Management_Port, Argument => "NUMBER", Help => -("The server listening management port on localhost")); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Stop the server by sending a 'stop' command on the management socket. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name, Args, Context); Address : GNAT.Sockets.Sock_Addr_Type; Stream : aliased Util.Streams.Sockets.Socket_Stream; Writer : Util.Streams.Texts.Print_Stream; begin Address.Addr := GNAT.Sockets.Loopback_Inet_Addr; Address.Port := GNAT.Sockets.Port_Type (Command.Management_Port); Stream.Connect (Address); Writer.Initialize (Stream'Access, 1024); Writer.Write ("stop" & ASCII.CR & ASCII.LF); Writer.Flush; Writer.Close; end Execute; begin Command_Drivers.Driver.Add_Command ("stop", -("stop the web server"), Command'Access); end AWA.Commands.Stop;
----------------------------------------------------------------------- -- awa-commands-stop -- Command to stop the web server -- Copyright (C) 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with Util.Streams.Sockets; with Util.Streams.Texts; package body AWA.Commands.Stop is -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); GC.Define_Switch (Config => Config, Output => Command.Management_Port'Access, Switch => "-m:", Long_Switch => "--management-port=", Initial => Command.Management_Port, Argument => "NUMBER", Help => -("The server listening management port on localhost")); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Stop the server by sending a 'stop' command on the management socket. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name, Args, Context); Address : GNAT.Sockets.Sock_Addr_Type; Stream : aliased Util.Streams.Sockets.Socket_Stream; Writer : Util.Streams.Texts.Print_Stream; begin Address.Addr := GNAT.Sockets.Loopback_Inet_Addr; Address.Port := GNAT.Sockets.Port_Type (Command.Management_Port); Stream.Connect (Address); Writer.Initialize (Stream'Unchecked_Access, 1024); Writer.Write ("stop" & ASCII.CR & ASCII.LF); Writer.Flush; Writer.Close; end Execute; begin Command_Drivers.Driver.Add_Command ("stop", -("stop the web server"), Command'Access); end AWA.Commands.Stop;
Fix accessibility check raised by GNAT 2021 (but not raised by GNAT 2020 and earlier GNAT versions!)
Fix accessibility check raised by GNAT 2021 (but not raised by GNAT 2020 and earlier GNAT versions!)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
777ffb6fa24b66bd2eaaf29a6cf61b1141e2ec85
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : in Sqlite_Access; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : Strings.chars_ptr := Strings.New_String (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, SQL_Stat, No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); Database.Count := Database.Count - 1; -- if Database.Count <= 1 then -- Result := Sqlite3_H.Sqlite3_Close (Database.Server); -- end if; -- 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 : ADO.Drivers.Connections.Database_Connection_Access := null; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is pragma Unreferenced (D); use Strings; use type System.Address; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased System.Address; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if DB /= null then Result := DB; DB.Count := DB.Count + 1; return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); procedure Configure (Name, Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & To_String (Name) & "=" & To_String (Item); begin Database.Execute (SQL); end Configure; begin Database.Server := Handle; Database.Count := 2; Database.Name := Config.Database; -- 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 := Database.all'Access; DB := Result; end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : in Sqlite_Access; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : Strings.chars_ptr := Strings.New_String (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, SQL_Stat, No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); Database.Count := Database.Count - 1; -- if Database.Count <= 1 then -- Result := Sqlite3_H.Sqlite3_Close (Database.Server); -- end if; -- 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 : ADO.Drivers.Connections.Database_Connection_Access := null; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is pragma Unreferenced (D); use Strings; use type System.Address; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased System.Address; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if DB /= null then Result := DB; DB.Count := DB.Count + 1; return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name, Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & To_String (Name) & "=" & Escape (Item); begin Log.Info ("Configure database with {0}", SQL); Database.Execute (SQL); end Configure; begin Database.Server := Handle; Database.Count := 2; Database.Name := Config.Database; -- 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 := Database.all'Access; DB := Result; 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;
Update the database configuration to escape the configuration value
Update the database configuration to escape the configuration value
Ada
apache-2.0
stcarrez/ada-ado
6239cc07384d5dbd8ce345b6779e869839208dd2
src/asf-sessions-factory.ads
src/asf-sessions-factory.ads
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- 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.Finalization; with Util.Strings; with Ada.Strings.Unbounded; with Util.Concurrent.Locks; with Ada.Containers.Hashed_Maps; with Ada.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package ASF.Sessions.Factory is type Session_Factory is tagged limited private; -- Create a new session procedure Create_Session (Factory : in out Session_Factory; Result : out Session); -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access); -- Deletes the session. procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session); -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session); -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration; -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration); private use Util.Strings; package Session_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Session, Hash => Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys); package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); type Session_Factory is new Ada.Finalization.Limited_Controlled with record Lock : Util.Concurrent.Locks.RW_Lock; -- Id to session map. Sessions : Session_Maps.Map; -- Max inactive time in seconds. Max_Inactive : Duration := DEFAULT_INACTIVE_TIMEOUT; -- Random number generator used for ID generation. Random : Id_Random.Generator; -- Number of 32-bit random numbers used for the ID generation. Id_Size : Ada.Streams.Stream_Element_Offset := 8; end record; -- Initialize the session factory. overriding procedure Initialize (Factory : in out Session_Factory); end ASF.Sessions.Factory;
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- 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.Finalization; with Util.Strings; with Ada.Strings.Unbounded; with Util.Concurrent.Locks; with Ada.Containers.Hashed_Maps; with Ada.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package ASF.Sessions.Factory is type Session_Factory is new Ada.Finalization.Limited_Controlled with private; -- Create a new session procedure Create_Session (Factory : in out Session_Factory; Result : out Session); -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access); -- Deletes the session. procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session); -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session); -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration; -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration); private use Util.Strings; package Session_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Session, Hash => Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys); package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); type Session_Factory is new Ada.Finalization.Limited_Controlled with record Lock : Util.Concurrent.Locks.RW_Lock; -- Id to session map. Sessions : Session_Maps.Map; -- Max inactive time in seconds. Max_Inactive : Duration := DEFAULT_INACTIVE_TIMEOUT; -- Random number generator used for ID generation. Random : Id_Random.Generator; -- Number of 32-bit random numbers used for the ID generation. Id_Size : Ada.Streams.Stream_Element_Offset := 8; end record; -- Initialize the session factory. overriding procedure Initialize (Factory : in out Session_Factory); end ASF.Sessions.Factory;
Fix compilation issue: the Session_Factory must expose the Finalize procedure so that it can be overriden by derived types.
Fix compilation issue: the Session_Factory must expose the Finalize procedure so that it can be overriden by derived types.
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
f805ce7201d1bac0e648e24f45bbfd36b3955e48
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 pragma Unreferenced (Name); 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, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body 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); elsif Name = "type" then return Util.Beans.Objects.To_Object (Operation_Type'Image (From.Kind)); 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); if Into.Kind = UNKNOWN and then Of_Type = "ASF.Parts.Part" then Into.Kind := ASF_UPLOAD; elsif Into.Kind = UNKNOWN then Into.Kind := ASF_ACTION; end if; end Add_Parameter; -- ------------------------------ -- Get the operation type. -- ------------------------------ function Get_Type (From : in Operation_Definition) return Operation_Type is begin return From.Kind; end Get_Type; -- ------------------------------ -- 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;
Implement the Get_Type function Define the operation type according to the first parameter type Return the operation type for the bean evaluation
Implement the Get_Type function Define the operation type according to the first parameter type Return the operation type for the bean evaluation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d7c1914cd3ec33837812bf80bd571faabc222d67
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 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.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Name, Args); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; Lib_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -lib -web -tool -ado -gtk") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; elsif Full_Switch = "-lib" then Lib_Flag := True; elsif Full_Switch = "-gtk" then Gtk_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Cmd.Usage (Name, Generator); return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Cmd.Usage (Name, Generator); return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag)); Generator.Set_Project_Property ("is_lib", Boolean'Image (Lib_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); elsif Gtk_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk"); elsif Tool_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-tool"); elsif Lib_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-lib"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); else Log.Info (""); Ada.Text_IO.Put_Line ("Your project is now created."); Ada.Text_IO.Put_Line ("Run the following commands to build it:"); Ada.Text_IO.Put_Line (" ./configure"); Ada.Text_IO.Put_Line (" make generate build"); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & " [--lib] [--ado] [--gtk] NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); Put_Line (" --gtk Generate a GtkAda project"); Put_Line (" --lib Generate a library project"); end Help; end Gen.Commands.Project;
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Name, Args); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; Lib_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -lib -web -tool -ado -gtk") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; elsif Full_Switch = "-lib" then Lib_Flag := True; elsif Full_Switch = "-gtk" then Gtk_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Cmd.Usage (Name, Generator); return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Cmd.Usage (Name, Generator); return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag)); Generator.Set_Project_Property ("is_lib", Boolean'Image (Lib_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); elsif Gtk_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk"); elsif Tool_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-tool"); elsif Lib_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-lib"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); else Log.Info (""); Ada.Text_IO.Put_Line ("Your project is now created."); Ada.Text_IO.Put_Line ("Run the following commands to build it:"); Ada.Text_IO.Put_Line (" ./configure"); Ada.Text_IO.Put_Line (" make generate build"); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in out Command; Name : in String; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & " [--lib] [--ado] [--gtk] NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); Put_Line (" --gtk Generate a GtkAda project"); Put_Line (" --lib Generate a library project"); end Help; end Gen.Commands.Project;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
672e9b116d387e757bb0b7409a0939d5e7f7d059
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Interfaces; -- == Permission == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. An application should declare each permission -- by instantiating the <tt>Definition</tt> package: -- -- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace"); -- -- This declares a permission that can be represented by "<tt>create-workspace</tt>" in -- configuration files. In Ada, the permission is used as follows: -- -- Perm_Create_Workspace.Permission -- package Security.Permissions is Invalid_Name : exception; -- Max number of permissions supported by the implementation. MAX_PERMISSION : constant Natural := 255; type Permission_Index is new Natural range 0 .. MAX_PERMISSION; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); type Permission_Index_Set is private; -- Check if the permission index set contains the given permission index. function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean; -- Add the permission index to the set. procedure Add_Permission (Set : in out Permission_Index_Set; Index : in Permission_Index); -- The empty set of permission indexes. EMPTY_SET : constant Permission_Index_Set; private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8; type Permission_Index_Set is array (0 .. INDEX_SET_SIZE - 1) of Interfaces.Unsigned_8; EMPTY_SET : constant Permission_Index_Set := (others => 0); end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Interfaces; -- == Permission == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. An application should declare each permission -- by instantiating the <tt>Definition</tt> package: -- -- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace"); -- -- This declares a permission that can be represented by "<tt>create-workspace</tt>" in -- configuration files. In Ada, the permission is used as follows: -- -- Perm_Create_Workspace.Permission -- package Security.Permissions is Invalid_Name : exception; -- Max number of permissions supported by the implementation. MAX_PERMISSION : constant Natural := 255; type Permission_Index is new Natural range 0 .. MAX_PERMISSION; NONE : constant Permission_Index := Permission_Index'First; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); type Permission_Index_Set is private; -- Check if the permission index set contains the given permission index. function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean; -- Add the permission index to the set. procedure Add_Permission (Set : in out Permission_Index_Set; Index : in Permission_Index); -- The empty set of permission indexes. EMPTY_SET : constant Permission_Index_Set; private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8; type Permission_Index_Set is array (0 .. INDEX_SET_SIZE - 1) of Interfaces.Unsigned_8; EMPTY_SET : constant Permission_Index_Set := (others => 0); end Security.Permissions;
Declare the NONE permission constant
Declare the NONE permission constant
Ada
apache-2.0
stcarrez/ada-security
856cbeb18747fffb63a97628d44a7fe29006c257
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with Util.Events; with MAT.Memory.Events; with MAT.Readers; with Ada.Containers.Ordered_Maps; package MAT.Memory.Targets is type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); type Size_Info_Type is record Count : Natural; end record; use type MAT.Types.Target_Size; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out Size_Info_Map); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with Util.Events; with MAT.Memory.Events; with MAT.Readers; with Ada.Containers.Ordered_Maps; package MAT.Memory.Targets is type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); type Size_Info_Type is record Count : Natural; end record; use type MAT.Types.Target_Size; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out Size_Info_Map); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Initialize the root frame instance
Initialize the root frame instance
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
5d0344ac88bd616ffe07602d7d1a434c5e72e0fd
src/lumen-glu.ads
src/lumen-glu.ads
-- Lumen.GLU -- Lumen's own thin OpenGL utilities bindings -- -- 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 System; with Lumen.GL; use Lumen.GL; package Lumen.GLU is --------------------------------------------------------------------------- -- Build mipmaps function Build_1D_Mipmaps (Target : in Enum; Components : in Int; Width : in Int; Format : in Enum; Data_Type : in Enum; Data : in Pointer) return Int with Import => True, Convention => StdCall, External_Name => "gluBuild1DMipmaps"; function Build_2D_Mipmaps (Target : in Enum; Components : in Int; Width : in Int; Height : in Int; Format : in Enum; Data_Type : in Enum; Data : in Pointer) return Int with Import => True, Convention => StdCall, External_Name => "gluBuild2DMipmaps"; -- Projections procedure Ortho_2D (Left : in Double; Right : in Double; Bottom : in Double; Top : in Double) with Import => True, Convention => StdCall, External_Name => "gluOrtho2D"; procedure Perspective (FOV_Y_Angle, Aspect, Z_Near, Z_Far : in Double) with Import => True, Convention => StdCall, External_Name => "gluPerspective"; -- Quadrics type Quadric is new Pointer; function New_Quadric return Quadric with Import => True, Convention => StdCall, External_Name => "gluNewQuadric"; procedure Delete_Quadric (Quad : in Quadric) with Import => True, Convention => StdCall, External_Name => "gluDeleteQuadric"; procedure Quadric_Draw_Style (Quad : in Quadric; Draw : in Enum) with Import => True, Convention => StdCall, External_Name => "gluQuadricDrawStyle"; procedure Quadric_Normals (Quad : in Quadric; Normal : in Enum) with Import => True, Convention => StdCall, External_Name => "gluQuadricNormals"; procedure Quadric_Orientation (Quad : in Quadric; Orientation : in Enum) with Import => True, Convention => StdCall, External_Name => "gluQuadricOrientation"; procedure Quadric_Texture (Quad : in Quadric; Texture : in Bool) with Import => True, Convention => StdCall, External_Name => "gluQuadricTexture"; -- Shapes procedure Cylinder (Quad : in Quadric; Base : in Double; Top : in Double; Height : in Double; Slices : in Int; Stacks : in Int) with Import => True, Convention => StdCall, External_Name => "gluCylinder"; procedure Disk (Quad : in Quadric; Inner : in Double; Outer : in Double; Slices : in Int; Loops : in Int) with Import => True, Convention => StdCall, External_Name => "gluDisk"; procedure Partial_Disk (Quad : in Quadric; Inner : in Double; Outer : in Double; Slices : in Int; Loops : in Int; Start : in Double; Sweep : in Double) with Import => True, Convention => StdCall, External_Name => "gluPartialDisk"; procedure Sphere (Quad : in Quadric; Radius : in Double; Slices : in Int; Stacks : in Int) with Import => True, Convention => StdCall, External_Name => "gluSphere"; --------------------------------------------------------------------------- end Lumen.GLU;
-- Lumen.GLU -- Lumen's own thin OpenGL utilities bindings -- -- 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 Lumen.GL; use Lumen.GL; package Lumen.GLU is --------------------------------------------------------------------------- -- Build mipmaps function Build_1D_Mipmaps (Target : in Enum; Components : in Int; Width : in Int; Format : in Enum; Data_Type : in Enum; Data : in Pointer) return Int with Import => True, Convention => StdCall, External_Name => "gluBuild1DMipmaps"; function Build_2D_Mipmaps (Target : in Enum; Components : in Int; Width : in Int; Height : in Int; Format : in Enum; Data_Type : in Enum; Data : in Pointer) return Int with Import => True, Convention => StdCall, External_Name => "gluBuild2DMipmaps"; -- Projections procedure Ortho_2D (Left : in Double; Right : in Double; Bottom : in Double; Top : in Double) with Import => True, Convention => StdCall, External_Name => "gluOrtho2D"; procedure Perspective (FOV_Y_Angle, Aspect, Z_Near, Z_Far : in Double) with Import => True, Convention => StdCall, External_Name => "gluPerspective"; -- Quadrics type Quadric is new Pointer; function New_Quadric return Quadric with Import => True, Convention => StdCall, External_Name => "gluNewQuadric"; procedure Delete_Quadric (Quad : in Quadric) with Import => True, Convention => StdCall, External_Name => "gluDeleteQuadric"; procedure Quadric_Draw_Style (Quad : in Quadric; Draw : in Enum) with Import => True, Convention => StdCall, External_Name => "gluQuadricDrawStyle"; procedure Quadric_Normals (Quad : in Quadric; Normal : in Enum) with Import => True, Convention => StdCall, External_Name => "gluQuadricNormals"; procedure Quadric_Orientation (Quad : in Quadric; Orientation : in Enum) with Import => True, Convention => StdCall, External_Name => "gluQuadricOrientation"; procedure Quadric_Texture (Quad : in Quadric; Texture : in Bool) with Import => True, Convention => StdCall, External_Name => "gluQuadricTexture"; -- Shapes procedure Cylinder (Quad : in Quadric; Base : in Double; Top : in Double; Height : in Double; Slices : in Int; Stacks : in Int) with Import => True, Convention => StdCall, External_Name => "gluCylinder"; procedure Disk (Quad : in Quadric; Inner : in Double; Outer : in Double; Slices : in Int; Loops : in Int) with Import => True, Convention => StdCall, External_Name => "gluDisk"; procedure Partial_Disk (Quad : in Quadric; Inner : in Double; Outer : in Double; Slices : in Int; Loops : in Int; Start : in Double; Sweep : in Double) with Import => True, Convention => StdCall, External_Name => "gluPartialDisk"; procedure Sphere (Quad : in Quadric; Radius : in Double; Slices : in Int; Stacks : in Int) with Import => True, Convention => StdCall, External_Name => "gluSphere"; --------------------------------------------------------------------------- end Lumen.GLU;
Fix warning.
GLU: Fix warning. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/lumen2
04ce6da3185261bf1f88175fe18688354ec1e954
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 := "18"; copyright_years : constant String := "2015-2019"; 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 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/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 := "19"; copyright_years : constant String := "2015-2019"; 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 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
bump version (dev)
bump version (dev)
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
fa4f140c553e88a516050a19d9c96481d2455dc2
regtests/ado-sequences-tests.adb
regtests/ado-sequences-tests.adb
----------------------------------------------------------------------- -- ado-sequences-tests -- Test sequences factories -- Copyright (C) 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with Regtests.Simple.Model; with ADO.Sequences.Hilo; with ADO.Sessions.Sources; with ADO.Sessions.Factory; package body ADO.Sequences.Tests is type Test_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE) with record Version : Integer; Value : ADO.Identifier; Name : Ada.Strings.Unbounded.Unbounded_String; Select_Name : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Destroy (Object : access Test_Impl); overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); package Caller is new Util.Test_Caller (Test, "ADO.Sequences"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Sequences.Create", Test_Create_Factory'Access); end Add_Tests; -- Test creation of the sequence factory. -- This test revealed a memory leak if we failed to create a database connection. procedure Test_Create_Factory (T : in out Test) is Seq_Factory : ADO.Sequences.Factory; Obj : Test_Impl; Factory : aliased ADO.Sessions.Factory.Session_Factory; Controller : aliased ADO.Sessions.Sources.Data_Source; Prev_Id : Identifier := ADO.NO_IDENTIFIER; begin Seq_Factory.Set_Default_Generator (ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); begin Seq_Factory.Allocate (Obj); T.Assert (False, "No exception raised."); exception when ADO.Drivers.Connection_Error => null; -- Good! An exception is expected because the session factory is empty. end; -- Make a real connection. Controller.Set_Connection (ADO.Drivers.Get_Config ("test.database")); Factory.Create (Controller); for I in 1 .. 1_000 loop Seq_Factory.Allocate (Obj); T.Assert (Obj.Get_Key_Value /= Prev_Id, "Invalid id was allocated"); Prev_Id := Obj.Get_Key_Value; end loop; end Test_Create_Factory; overriding procedure Destroy (Object : access Test_Impl) is begin null; end Destroy; overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is pragma Unreferenced (Object, Session, Query); begin Found := False; end Find; overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class) is begin null; end Load; overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Save; overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Delete; overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Create; end ADO.Sequences.Tests;
----------------------------------------------------------------------- -- ado-sequences-tests -- Test sequences factories -- Copyright (C) 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with Regtests.Simple.Model; with ADO.Sequences.Hilo; with ADO.Sessions.Sources; with ADO.Sessions.Factory; package body ADO.Sequences.Tests is type Test_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE) with record Version : Integer; Value : ADO.Identifier; Name : Ada.Strings.Unbounded.Unbounded_String; Select_Name : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Destroy (Object : access Test_Impl); overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); package Caller is new Util.Test_Caller (Test, "ADO.Sequences"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Sequences.Create", Test_Create_Factory'Access); end Add_Tests; -- Test creation of the sequence factory. -- This test revealed a memory leak if we failed to create a database connection. procedure Test_Create_Factory (T : in out Test) is Seq_Factory : ADO.Sequences.Factory; Obj : Test_Impl; Factory : aliased ADO.Sessions.Factory.Session_Factory; Controller : aliased ADO.Sessions.Sources.Data_Source; Prev_Id : Identifier := ADO.NO_IDENTIFIER; begin Seq_Factory.Set_Default_Generator (ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); begin Seq_Factory.Allocate (Obj); T.Assert (False, "No exception raised."); exception when ADO.Sessions.Connection_Error => null; -- Good! An exception is expected because the session factory is empty. end; -- Make a real connection. Controller.Set_Connection (ADO.Drivers.Get_Config ("test.database")); Factory.Create (Controller); for I in 1 .. 1_000 loop Seq_Factory.Allocate (Obj); T.Assert (Obj.Get_Key_Value /= Prev_Id, "Invalid id was allocated"); Prev_Id := Obj.Get_Key_Value; end loop; end Test_Create_Factory; overriding procedure Destroy (Object : access Test_Impl) is begin null; end Destroy; overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is pragma Unreferenced (Object, Session, Query); begin Found := False; end Find; overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class) is begin null; end Load; overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Save; overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Delete; overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Create; end ADO.Sequences.Tests;
Use the ADO.Sessions.Connection_Error exception
Use the ADO.Sessions.Connection_Error exception
Ada
apache-2.0
stcarrez/ada-ado
a1b2de96f79d9ab962c77b8881691a9ce706fb3d
awa/plugins/awa-tags/src/awa-tags-beans.adb
awa/plugins/awa-tags/src/awa-tags-beans.adb
----------------------------------------------------------------------- -- awa-tags-beans -- Beans for the tags 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.Unchecked_Deallocation; with ADO.Queries; with ADO.Statements; with ADO.Sessions.Entities; package body AWA.Tags.Beans is -- ------------------------------ -- 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 Tag_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); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) onto which the tags are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Tag_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 tag on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Tag_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the tags associated with the given database identifier. -- ------------------------------ procedure Load_Tags (Into : in out Tag_List_Bean; Session : in 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 Query.Set_Query (AWA.Tags.Models.Query_Tag_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Load_Tags; -- ------------------------------ -- Set the list of tags to add. -- ------------------------------ procedure Set_Added (Into : in out Tag_List_Bean; Tags : in Util.Strings.Vectors.Vector) is begin Into.Added := Tags; end Set_Added; -- ------------------------------ -- Set the list of tags to remove. -- ------------------------------ procedure Set_Deleted (Into : in out Tag_List_Bean; Tags : in Util.Strings.Vectors.Vector) is begin Into.Deleted := Tags; end Set_Deleted; -- ------------------------------ -- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>. -- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of -- tags defined by <tt>Set_Added</tt> are associated with the database entity. -- ------------------------------ procedure Update_Tags (From : in Tag_List_Bean; For_Entity_Id : in ADO.Identifier) is use type AWA.Tags.Modules.Tag_Module_Access; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type); Service : AWA.Tags.Modules.Tag_Module_Access := From.Module; begin if Service = null then Service := AWA.Tags.Modules.Get_Tag_Module; end if; Service.Update_Tags (Id => For_Entity_Id, Entity_Type => Entity_Type, Permission => Ada.Strings.Unbounded.To_String (From.Permission), Added => From.Added, Deleted => From.Deleted); end Update_Tags; -- ------------------------------ -- Create the tag list bean instance. -- ------------------------------ function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_List_Bean_Access := new Tag_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Search the tags that match the search string. -- ------------------------------ procedure Search_Tags (Into : in out Tag_Search_Bean; Session : in ADO.Sessions.Session; Search : in String) 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 Query.Set_Query (AWA.Tags.Models.Query_Tag_Search); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("search", Search & "%"); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Search_Tags; -- ------------------------------ -- 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 Tag_Search_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 = "search" then declare Session : constant ADO.Sessions.Session := From.Module.Get_Session; begin From.Search_Tags (Session, Util.Beans.Objects.To_String (Value)); end; end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) onto which the tags are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Tag_Search_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; -- ------------------------------ -- Create the tag search bean instance. -- ------------------------------ function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_Search_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 Tag_Info_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); declare Session : ADO.Sessions.Session := From.Module.Get_Session; begin From.Load_Tags (Session); end; end if; end Set_Value; -- ------------------------------ -- Load the list of tags. -- ------------------------------ procedure Load_Tags (Into : in out Tag_Info_List_Bean; Session : in out ADO.Sessions.Session) 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 Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All); Query.Bind_Param ("entity_type", Kind); AWA.Tags.Models.List (Into, Session, Query); end Load_Tags; -- ------------------------------ -- Create the tag info list bean instance. -- ------------------------------ function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_Info_List_Bean; -- ------------------------------ -- Get the list of tags associated with the given entity. -- Returns null if the entity does not have any tag. -- ------------------------------ function Get_Tags (From : in Entity_Tag_Map; For_Entity : in ADO.Identifier) return Util.Beans.Lists.Strings.List_Bean_Access is Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity); begin if Entity_Tag_Maps.Has_Element (Pos) then return Entity_Tag_Maps.Element (Pos); else return null; end if; end Get_Tags; -- ------------------------------ -- Load the list of tags associated with a list of entities. -- ------------------------------ procedure Load_Tags (Into : in out Entity_Tag_Map; Session : in out ADO.Sessions.Session'Class; Entity_Type : in String; List : in ADO.Utils.Identifier_Vector) is Query : ADO.Queries.Context; Kind : ADO.Entity_Type; begin if List.Is_Empty then return; end if; Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type); Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All); Query.Bind_Param ("entity_id_list", ADO.Utils.To_Parameter_List (List)); Query.Bind_Param ("entity_type", Kind); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); Id : ADO.Identifier; List : Util.Beans.Lists.Strings.List_Bean_Access; Pos : Entity_Tag_Maps.Cursor; begin Stmt.Execute; while Stmt.Has_Elements loop Id := Stmt.Get_Identifier (0); Pos := Into.Tags.Find (Id); if not Entity_Tag_Maps.Has_Element (Pos) then List := new Util.Beans.Lists.Strings.List_Bean; Into.Tags.Insert (Id, List); else List := Entity_Tag_Maps.Element (Pos); end if; List.List.Append (Stmt.Get_String (1)); end loop; end; end Load_Tags; -- ------------------------------ -- Release the list of tags. -- ------------------------------ procedure Clear (List : in out Entity_Tag_Map) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class, Name => Util.Beans.Lists.Strings.List_Bean_Access); Pos : Entity_Tag_Maps.Cursor; Tags : Util.Beans.Lists.Strings.List_Bean_Access; begin loop Pos := List.Tags.First; exit when not Entity_Tag_Maps.Has_Element (Pos); Tags := Entity_Tag_Maps.Element (Pos); List.Tags.Delete (Pos); Free (Tags); end loop; end Clear; -- ------------------------------ -- Release the list of tags. -- ------------------------------ overriding procedure Finalize (List : in out Entity_Tag_Map) is begin List.Clear; end Finalize; end AWA.Tags.Beans;
----------------------------------------------------------------------- -- awa-tags-beans -- Beans for the tags 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.Unchecked_Deallocation; with ADO.Queries; with ADO.Statements; with ADO.Sessions.Entities; package body AWA.Tags.Beans is -- ------------------------------ -- 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 Tag_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); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) onto which the tags are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Tag_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 tag on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Tag_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the tags associated with the given database identifier. -- ------------------------------ procedure Load_Tags (Into : in out Tag_List_Bean; Session : in 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 Query.Set_Query (AWA.Tags.Models.Query_Tag_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Load_Tags; -- ------------------------------ -- Set the list of tags to add. -- ------------------------------ procedure Set_Added (Into : in out Tag_List_Bean; Tags : in Util.Strings.Vectors.Vector) is begin Into.Added := Tags; end Set_Added; -- ------------------------------ -- Set the list of tags to remove. -- ------------------------------ procedure Set_Deleted (Into : in out Tag_List_Bean; Tags : in Util.Strings.Vectors.Vector) is begin Into.Deleted := Tags; end Set_Deleted; -- ------------------------------ -- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>. -- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of -- tags defined by <tt>Set_Added</tt> are associated with the database entity. -- ------------------------------ procedure Update_Tags (From : in Tag_List_Bean; For_Entity_Id : in ADO.Identifier) is use type AWA.Tags.Modules.Tag_Module_Access; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type); Service : AWA.Tags.Modules.Tag_Module_Access := From.Module; begin if Service = null then Service := AWA.Tags.Modules.Get_Tag_Module; end if; Service.Update_Tags (Id => For_Entity_Id, Entity_Type => Entity_Type, Permission => Ada.Strings.Unbounded.To_String (From.Permission), Added => From.Added, Deleted => From.Deleted); end Update_Tags; -- ------------------------------ -- Create the tag list bean instance. -- ------------------------------ function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_List_Bean_Access := new Tag_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Search the tags that match the search string. -- ------------------------------ procedure Search_Tags (Into : in out Tag_Search_Bean; Session : in ADO.Sessions.Session; Search : in String) 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 Query.Set_Query (AWA.Tags.Models.Query_Tag_Search); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("search", Search & "%"); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Search_Tags; -- ------------------------------ -- 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 Tag_Search_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 = "search" then declare Session : constant ADO.Sessions.Session := From.Module.Get_Session; begin From.Search_Tags (Session, Util.Beans.Objects.To_String (Value)); end; end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) onto which the tags are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Tag_Search_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; -- ------------------------------ -- Create the tag search bean instance. -- ------------------------------ function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_Search_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 Tag_Info_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); declare Session : ADO.Sessions.Session := From.Module.Get_Session; begin From.Load_Tags (Session); end; end if; end Set_Value; -- ------------------------------ -- Load the list of tags. -- ------------------------------ procedure Load_Tags (Into : in out Tag_Info_List_Bean; Session : in out ADO.Sessions.Session) 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 Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All); Query.Bind_Param ("entity_type", Kind); AWA.Tags.Models.List (Into, Session, Query); end Load_Tags; -- ------------------------------ -- Create the tag info list bean instance. -- ------------------------------ function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_Info_List_Bean; -- ------------------------------ -- Get the list of tags associated with the given entity. -- Returns null if the entity does not have any tag. -- ------------------------------ function Get_Tags (From : in Entity_Tag_Map; For_Entity : in ADO.Identifier) return Util.Beans.Lists.Strings.List_Bean_Access is Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity); begin if Entity_Tag_Maps.Has_Element (Pos) then return Entity_Tag_Maps.Element (Pos); else return null; end if; end Get_Tags; -- ------------------------------ -- Get the list of tags associated with the given entity. -- Returns a null object if the entity does not have any tag. -- ------------------------------ function Get_Tags (From : in Entity_Tag_Map; For_Entity : in ADO.Identifier) return Util.Beans.Objects.Object is Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity); begin if Entity_Tag_Maps.Has_Element (Pos) then return Util.Beans.Objects.To_Object (Value => Entity_Tag_Maps.Element (Pos).all'Access, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Tags; -- ------------------------------ -- Load the list of tags associated with a list of entities. -- ------------------------------ procedure Load_Tags (Into : in out Entity_Tag_Map; Session : in out ADO.Sessions.Session'Class; Entity_Type : in String; List : in ADO.Utils.Identifier_Vector) is Query : ADO.Queries.Context; Kind : ADO.Entity_Type; begin Into.Clear; if List.Is_Empty then return; end if; Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type); Query.Set_Query (AWA.Tags.Models.Query_Tag_List_For_Entities); Query.Bind_Param ("entity_id_list", List); Query.Bind_Param ("entity_type", Kind); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); Id : ADO.Identifier; List : Util.Beans.Lists.Strings.List_Bean_Access; Pos : Entity_Tag_Maps.Cursor; begin Stmt.Execute; while Stmt.Has_Elements loop Id := Stmt.Get_Identifier (0); Pos := Into.Tags.Find (Id); if not Entity_Tag_Maps.Has_Element (Pos) then List := new Util.Beans.Lists.Strings.List_Bean; Into.Tags.Insert (Id, List); else List := Entity_Tag_Maps.Element (Pos); end if; List.List.Append (Stmt.Get_String (1)); Stmt.Next; end loop; end; end Load_Tags; -- ------------------------------ -- Release the list of tags. -- ------------------------------ procedure Clear (List : in out Entity_Tag_Map) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class, Name => Util.Beans.Lists.Strings.List_Bean_Access); Pos : Entity_Tag_Maps.Cursor; Tags : Util.Beans.Lists.Strings.List_Bean_Access; begin loop Pos := List.Tags.First; exit when not Entity_Tag_Maps.Has_Element (Pos); Tags := Entity_Tag_Maps.Element (Pos); List.Tags.Delete (Pos); Free (Tags); end loop; end Clear; -- ------------------------------ -- Release the list of tags. -- ------------------------------ overriding procedure Finalize (List : in out Entity_Tag_Map) is begin List.Clear; end Finalize; end AWA.Tags.Beans;
Implement the new Get_Tags operation Fix Load_Tags to use the correct query, bind the list of identifiers to search, and collect the result
Implement the new Get_Tags operation Fix Load_Tags to use the correct query, bind the list of identifiers to search, and collect the result
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
d0ef44c49c55770f216445edf790f3914a5e8d10
awa/plugins/awa-comments/src/awa-comments-modules.ads
awa/plugins/awa-comments/src/awa-comments-modules.ads
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Modules.Get; with AWA.Comments.Models; package AWA.Comments.Modules is NAME : constant String := "comments"; type Comment_Module is new AWA.Modules.Module with null record; type Comment_Module_Access is access all Comment_Module'Class; overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Load the comment identified by the given identifier. procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier); -- Create a new comment for the associated database entity. procedure Create_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); function Get_Comment_Module is new AWA.Modules.Get (Comment_Module, Comment_Module_Access, NAME); end AWA.Comments.Modules;
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Modules.Get; with AWA.Comments.Models; package AWA.Comments.Modules is NAME : constant String := "comments"; type Comment_Module is new AWA.Modules.Module with null record; type Comment_Module_Access is access all Comment_Module'Class; overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Load the comment identified by the given identifier. procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier); -- Create a new comment for the associated database entity. procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); function Get_Comment_Module is new AWA.Modules.Get (Comment_Module, Comment_Module_Access, NAME); end AWA.Comments.Modules;
Change the Create_Comment to specify the entity type
Change the Create_Comment to specify the entity type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3b68c71fdbb53861bdde3af0d4fa3cfa992be28d
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 if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; -- ------------------------------ -- 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 Element (Link, 1) = '/' or else Starts_With (Link, "http://") or else 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_Raw (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; 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" or Format = "FORMAT_DOTCLEAR" then return Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.Parsers.SYNTAX_GOOGLE; elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then return Wiki.Parsers.SYNTAX_PHPBB; elsif Format = "creole" or Format = "FORMAT_CREOLE" then return Wiki.Parsers.SYNTAX_CREOLE; elsif Format = "mediawiki" or Format = "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; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; -- ------------------------------ -- 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 Element (Link, 1) = '/' or else Starts_With (Link, "http://") or else 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_Wiki_Style function to take into account more wiki styles
Update the Get_Wiki_Style function to take into account more wiki styles
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
cc467ba63c4c822cc54519ad43e24519f07ac58b
src/wiki-nodes.adb
src/wiki-nodes.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- Finalize the node list to release the allocated memory. overriding procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in out Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START then Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in out Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- Append a node to the node list. procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value.all, Node); end Append; -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- ------------------------------ -- Finalize the node list to release the allocated memory. -- ------------------------------ overriding procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START then Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value.all, Node); end Append; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; -- ------------------------------ -- Returns True if the list reference is empty. -- ------------------------------ function Is_Empty (List : in Node_List_Ref) return Boolean is begin return List.Is_Null; end Is_Empty; end Wiki.Nodes;
Implement the Is_Empty procedure
Implement the Is_Empty procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0f5dff1ad748de48673836ac54f1c8504eb2cfeb
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- 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); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- 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); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- 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 (Into : in out Document; Level : in Positive; Ordered : in Boolean); -- 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); -- 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); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; with Ada.Finalization; package Wiki.Nodes is pragma Preelaborate; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- 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); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- 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); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- 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 (Into : in out Document; Level : in Positive; Ordered : in Boolean); -- 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); -- 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); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited new Ada.Finalization.Limited_Controlled with record Nodes : Node_List; Current : Node_Type_Access; end record; overriding procedure Initialize (Doc : in out Document); end Wiki.Nodes;
Declare the Initialize procedure
Declare the Initialize procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
127cc255ac400b54f006ea01beed54591fb34de8
src/ado-datasets.adb
src/ado-datasets.adb
----------------------------------------------------------------------- -- ado-datasets -- 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.Beans.Objects.Time; with ADO.Schemas; with ADO.Statements; package body ADO.Datasets is -- ------------------------------ -- Execute the SQL query on the database session and populate the dataset. -- The column names are used to setup the dataset row bean definition. -- ------------------------------ procedure List (Into : in out Dataset; Session : in out ADO.Sessions.Session'Class; Query : in ADO.Queries.Context'Class) is procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array); Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array) is use ADO.Schemas; begin for I in Data'Range loop case Stmt.Get_Column_Type (I - 1) is -- Boolean column when T_BOOLEAN => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Boolean (I - 1)); when T_TINYINT | T_SMALLINT | T_INTEGER | T_LONG_INTEGER | T_YEAR => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Integer (I - 1)); when T_FLOAT | T_DOUBLE | T_DECIMAL => Data (I) := Util.Beans.Objects.Null_Object; when T_ENUM => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1)); when T_TIME | T_DATE | T_DATE_TIME | T_TIMESTAMP => Data (I) := Util.Beans.Objects.Time.To_Object (Stmt.Get_Time (I - 1)); when T_CHAR | T_VARCHAR => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1)); when T_BLOB => Data (I) := Util.Beans.Objects.Null_Object; when T_SET | T_UNKNOWN | T_NULL => Data (I) := Util.Beans.Objects.Null_Object; end case; end loop; end Fill; begin Stmt.Execute; Into.Clear; if Stmt.Has_Elements then for I in 1 .. Stmt.Get_Column_Count loop Into.Add_Column (Stmt.Get_Column_Name (I - 1)); end loop; while Stmt.Has_Elements loop Into.Append (Fill'Access); Stmt.Next; end loop; end if; end List; end ADO.Datasets;
----------------------------------------------------------------------- -- ado-datasets -- Datasets -- Copyright (C) 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects.Time; with ADO.Schemas; with ADO.Statements; package body ADO.Datasets is -- ------------------------------ -- Execute the SQL query on the database session and populate the dataset. -- The column names are used to setup the dataset row bean definition. -- ------------------------------ procedure List (Into : in out Dataset; Session : in out ADO.Sessions.Session'Class; Query : in ADO.Queries.Context'Class) is procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array); Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array) is use ADO.Schemas; begin for I in Data'Range loop case Stmt.Get_Column_Type (I - 1) is -- Boolean column when T_BOOLEAN => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Boolean (I - 1)); when T_TINYINT | T_SMALLINT | T_INTEGER | T_LONG_INTEGER | T_YEAR => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Integer (I - 1)); when T_FLOAT | T_DOUBLE | T_DECIMAL => Data (I) := Util.Beans.Objects.Null_Object; when T_ENUM => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1)); when T_TIME | T_DATE | T_DATE_TIME | T_TIMESTAMP => Data (I) := Util.Beans.Objects.Time.To_Object (Stmt.Get_Time (I - 1)); when T_CHAR | T_VARCHAR => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1)); when T_BLOB => Data (I) := Util.Beans.Objects.Null_Object; when T_SET | T_UNKNOWN | T_NULL => Data (I) := Util.Beans.Objects.Null_Object; end case; end loop; end Fill; begin Stmt.Execute; Into.Clear; if Stmt.Has_Elements then for I in 1 .. Stmt.Get_Column_Count loop Into.Add_Column (Stmt.Get_Column_Name (I - 1)); end loop; while Stmt.Has_Elements loop Into.Append (Fill'Access); Stmt.Next; end loop; end if; end List; -- ------------------------------ -- Get the number of items in a list by executing an SQL query. -- ------------------------------ function Get_Count (Session : in ADO.Sessions.Session'Class; Query : in ADO.Queries.Context'Class) return Natural is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; return Stmt.Get_Result_Integer; end Get_Count; end ADO.Datasets;
Implement the Get_Count function
Implement the Get_Count function
Ada
apache-2.0
stcarrez/ada-ado
90aaf51ad13af5267fb5323e602d4fee8a504f34
src/miscellaneous/commontext.adb
src/miscellaneous/commontext.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Strings.Fixed; with Ada.Strings.UTF_Encoding.Strings; package body CommonText is package AS renames Ada.Strings; package UES renames Ada.Strings.UTF_Encoding.Strings; ----------- -- USS -- ----------- function USS (US : Text) return String is begin return SU.To_String (US); end USS; ----------- -- SUS -- ----------- function SUS (S : String) return Text is begin return SU.To_Unbounded_String (S); end SUS; ------------- -- UTF8S -- ------------- function UTF8S (S8 : UTF8) return String is begin return UES.Decode (S8); end UTF8S; ------------- -- SUTF8 -- ------------- function SUTF8 (S : String) return UTF8 is begin return UES.Encode (S); end SUTF8; ----------------- -- IsBlank #1 -- ----------------- function IsBlank (US : Text) return Boolean is begin return SU.Length (US) = 0; end IsBlank; ----------------- -- IsBlank #2 -- ----------------- function IsBlank (S : String) return Boolean is begin return S'Length = 0; end IsBlank; ------------------ -- equivalent -- ------------------ function equivalent (A, B : Text) return Boolean is use type Text; begin return A = B; end equivalent; ------------------ -- equivalent -- ------------------ function equivalent (A : Text; B : String) return Boolean is AS : constant String := USS (A); begin return AS = B; end equivalent; -------------- -- trim #1 -- -------------- function trim (US : Text) return Text is begin return SU.Trim (US, AS.Both); end trim; -------------- -- trim #2 -- -------------- function trim (S : String) return String is begin return AS.Fixed.Trim (S, AS.Both); end trim; --------------- -- int2str -- --------------- function int2str (A : Integer) return String is raw : constant String := A'Img; len : constant Natural := raw'Length; begin return raw (2 .. len); end int2str; ---------------- -- int2text -- ---------------- function int2text (A : Integer) return Text is begin return SUS (int2str (A)); end int2text; ---------------- -- bool2str -- ---------------- function bool2str (A : Boolean) return String is begin if A then return "true"; end if; return "false"; end bool2str; ----------------- -- bool2text -- ----------------- function bool2text (A : Boolean) return Text is begin return SUS (bool2str (A)); end bool2text; -------------------- -- contains #1 -- -------------------- function contains (S : String; fragment : String) return Boolean is begin return (AS.Fixed.Index (Source => S, Pattern => fragment) > 0); end contains; -------------------- -- contains #2 -- -------------------- function contains (US : Text; fragment : String) return Boolean is begin return (SU.Index (Source => US, Pattern => fragment) > 0); end contains; -------------- -- part_1 -- -------------- function part_1 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (S'First .. slash - 1); end part_1; -------------- -- part_2 -- -------------- function part_2 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (slash + separator'Length .. S'Last); end part_2; --------------- -- replace -- --------------- function replace (S : String; reject, shiny : Character) return String is rejectstr : constant String (1 .. 1) := (1 => reject); focus : constant Natural := AS.Fixed.Index (Source => S, Pattern => rejectstr); returnstr : String := S; begin if focus > 0 then returnstr (focus) := shiny; end if; return returnstr; end replace; --------------- -- zeropad -- --------------- function zeropad (N : Natural; places : Positive) return String is template : String (1 .. places) := (others => '0'); myimage : constant String := trim (N'Img); startpos : constant Natural := 1 + places - myimage'Length; begin template (startpos .. places) := myimage; return template; end zeropad; -------------- -- len #1 -- -------------- function len (US : Text) return Natural is begin return SU.Length (US); end len; -------------- -- len #2 -- -------------- function len (S : String) return Natural is begin return S'Length; end len; ------------------ -- count_char -- ------------------ function count_char (S : String; focus : Character) return Natural is result : Natural := 0; begin for x in S'Range loop if S (x) = focus then result := result + 1; end if; end loop; return result; end count_char; end CommonText;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Strings.Fixed; with Ada.Strings.UTF_Encoding.Strings; package body CommonText is package AS renames Ada.Strings; package UES renames Ada.Strings.UTF_Encoding.Strings; ----------- -- USS -- ----------- function USS (US : Text) return String is begin return SU.To_String (US); end USS; ----------- -- SUS -- ----------- function SUS (S : String) return Text is begin return SU.To_Unbounded_String (S); end SUS; ------------- -- UTF8S -- ------------- function UTF8S (S8 : UTF8) return String is begin return UES.Decode (S8); end UTF8S; ------------- -- SUTF8 -- ------------- function SUTF8 (S : String) return UTF8 is begin return UES.Encode (S); end SUTF8; ----------------- -- IsBlank #1 -- ----------------- function IsBlank (US : Text) return Boolean is begin return SU.Length (US) = 0; end IsBlank; ----------------- -- IsBlank #2 -- ----------------- function IsBlank (S : String) return Boolean is begin return S'Length = 0; end IsBlank; ------------------ -- equivalent -- ------------------ function equivalent (A, B : Text) return Boolean is use type Text; begin return A = B; end equivalent; ------------------ -- equivalent -- ------------------ function equivalent (A : Text; B : String) return Boolean is AS : constant String := USS (A); begin return AS = B; end equivalent; -------------- -- trim #1 -- -------------- function trim (US : Text) return Text is begin return SU.Trim (US, AS.Both); end trim; -------------- -- trim #2 -- -------------- function trim (S : String) return String is begin return AS.Fixed.Trim (S, AS.Both); end trim; --------------- -- int2str -- --------------- function int2str (A : Integer) return String is raw : constant String := A'Img; len : constant Natural := raw'Length; begin return raw (2 .. len); end int2str; ---------------- -- int2text -- ---------------- function int2text (A : Integer) return Text is begin return SUS (int2str (A)); end int2text; ---------------- -- bool2str -- ---------------- function bool2str (A : Boolean) return String is begin if A then return "true"; end if; return "false"; end bool2str; ----------------- -- bool2text -- ----------------- function bool2text (A : Boolean) return Text is begin return SUS (bool2str (A)); end bool2text; -------------------- -- contains #1 -- -------------------- function contains (S : String; fragment : String) return Boolean is begin return (AS.Fixed.Index (Source => S, Pattern => fragment) > 0); end contains; -------------------- -- contains #2 -- -------------------- function contains (US : Text; fragment : String) return Boolean is begin return (SU.Index (Source => US, Pattern => fragment) > 0); end contains; -------------- -- part_1 -- -------------- function part_1 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (S'First .. slash - 1); end part_1; -------------- -- part_2 -- -------------- function part_2 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (slash + separator'Length .. S'Last); end part_2; --------------- -- replace -- --------------- function replace (S : String; reject, shiny : Character) return String is rejectstr : constant String (1 .. 1) := (1 => reject); focus : constant Natural := AS.Fixed.Index (Source => S, Pattern => rejectstr); returnstr : String := S; begin if focus > 0 then returnstr (focus) := shiny; end if; return returnstr; end replace; --------------- -- zeropad -- --------------- function zeropad (N : Natural; places : Positive) return String is template : String (1 .. places) := (others => '0'); myimage : constant String := trim (N'Img); startpos : constant Integer := 1 + places - myimage'Length; begin if startpos < 1 then return myimage; else template (startpos .. places) := myimage; return template; end if; end zeropad; -------------- -- len #1 -- -------------- function len (US : Text) return Natural is begin return SU.Length (US); end len; -------------- -- len #2 -- -------------- function len (S : String) return Natural is begin return S'Length; end len; ------------------ -- count_char -- ------------------ function count_char (S : String; focus : Character) return Natural is result : Natural := 0; begin for x in S'Range loop if S (x) = focus then result := result + 1; end if; end loop; return result; end count_char; end CommonText;
Improve zeropad handling
Improve zeropad handling Zeropad crashes if the number has more places than the integer image. Detect this situation and return an unpadded image when that happens.
Ada
isc
jrmarino/AdaBase
cf050d65a87b9d7229d0c5fd8020aa82d56dbdb8
src/wiki-streams-html-stream.adb
src/wiki-streams-html-stream.adb
----------------------------------------------------------------------- -- wiki-streams-html-stream -- Generic Wiki HTML output stream -- Copyright (C) 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Streams.Html.Stream is -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Html_Output_Stream'Class); -- Write the string to the stream. procedure Write_String (Stream : in out Html_Output_Stream'Class; Content : in String); -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out Html_Output_Stream'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; end if; end Close_Current; -- ------------------------------ -- Write the string to the stream. -- ------------------------------ procedure Write_String (Stream : in out Html_Output_Stream'Class; Content : in String) is begin for I in Content'Range loop Stream.Write (Wiki.Strings.To_WChar (Content (I))); end loop; end Write_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 (Stream : in out Html_Output_Stream; Name : in String; Content : in Wiki.Strings.UString) is begin if Stream.Close_Start then Html.Write_Escape_Attribute (Stream, Name, Wiki.Strings.To_WString (Content)); end if; end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wide_Wide_String) is begin if Stream.Close_Start then Stream.Write_Escape_Attribute (Name, Content); end if; end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Stream : in out Html_Output_Stream; Name : in String) is begin Close_Current (Stream); Stream.Write ('<'); Stream.Write_String (Name); Stream.Close_Start := True; end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Stream : in out Html_Output_Stream; Name : in String) is begin if Stream.Close_Start then Stream.Write (" />"); Stream.Close_Start := False; else Close_Current (Stream); Stream.Write ("</"); Stream.Write_String (Name); Stream.Write ('>'); end if; end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Stream : in out Html_Output_Stream; Content : in Wiki.Strings.WString) is begin Close_Current (Stream); Stream.Write_Escape (Content); end Write_Wide_Text; end Wiki.Streams.Html.Stream;
----------------------------------------------------------------------- -- wiki-streams-html-stream -- Generic Wiki HTML output stream -- Copyright (C) 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; package body Wiki.Streams.Html.Stream is -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Html_Output_Stream'Class); -- Write the string to the stream. procedure Write_String (Stream : in out Html_Output_Stream'Class; Content : in String); -- ------------------------------ -- Write an optional newline or space. -- ------------------------------ overriding procedure Newline (Writer : in out Html_Output_Stream) is begin if Writer.Indent_Level > 0 and Writer.Text_Length > 0 then Writer.Write (Wiki.Helpers.LF); Writer.Empty_Line := True; end if; Writer.Text_Length := 0; end Newline; -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out Html_Output_Stream'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; Stream.Empty_Line := False; end if; end Close_Current; -- ------------------------------ -- Write the string to the stream. -- ------------------------------ procedure Write_String (Stream : in out Html_Output_Stream'Class; Content : in String) is begin for I in Content'Range loop Stream.Write (Wiki.Strings.To_WChar (Content (I))); end loop; if Content'Length > 0 then Stream.Text_Length := Stream.Text_Length + Content'Length; Stream.Empty_Line := False; end if; end Write_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 (Stream : in out Html_Output_Stream; Name : in String; Content : in Wiki.Strings.UString) is begin if Stream.Close_Start then Html.Write_Escape_Attribute (Stream, Name, Wiki.Strings.To_WString (Content)); end if; end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wide_Wide_String) is begin if Stream.Close_Start then Stream.Write_Escape_Attribute (Name, Content); end if; end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Stream : in out Html_Output_Stream; Name : in String) is begin Close_Current (Stream); Stream.Indent_Pos := Stream.Indent_Pos + Stream.Indent_Level; if Stream.Indent_Pos > 1 then if not Stream.Empty_Line then Stream.Write (Helpers.LF); end if; for I in 1 .. Stream.Indent_Pos loop Stream.Write (' '); end loop; end if; Stream.Write ('<'); Stream.Write_String (Name); Stream.Close_Start := True; Stream.Text_Length := 0; Stream.Empty_Line := False; end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Stream : in out Html_Output_Stream; Name : in String) is begin if Stream.Indent_Pos > Stream.Indent_Level then Stream.Indent_Pos := Stream.Indent_Pos - Stream.Indent_Level; end if; if Stream.Close_Start then Stream.Write (" />"); Stream.Close_Start := False; else Close_Current (Stream); if Stream.Text_Length = 0 then if not Stream.Empty_Line then Stream.Write (Wiki.Helpers.LF); end if; if Stream.Indent_Pos > 1 then Stream.Write (Helpers.LF); for I in 1 .. Stream.Indent_Pos loop Stream.Write (' '); end loop; end if; end if; Stream.Write ("</"); Stream.Write_String (Name); Stream.Write ('>'); end if; if Stream.Indent_Level > 0 then Stream.Write (Wiki.Helpers.LF); Stream.Empty_Line := True; end if; Stream.Text_Length := 0; end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Stream : in out Html_Output_Stream; Content : in Wiki.Strings.WString) is begin Close_Current (Stream); Stream.Write_Escape (Content); if Content'Length > 0 then Stream.Text_Length := Stream.Text_Length + Content'Length; Stream.Empty_Line := False; end if; end Write_Wide_Text; end Wiki.Streams.Html.Stream;
Add the Newline procedure and update to indent the HTML output stream
Add the Newline procedure and update to indent the HTML output stream
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
bd3df9c282bfa18c25b048f192b8232a3c0ad247
src/wiki-parsers-html.ads
src/wiki-parsers-html.ads
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- 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. ----------------------------------------------------------------------- -- This is a small HTML parser that is called to deal with embedded HTML in wiki text. -- The parser is intended to handle incorrect HTML and clean the result as much as possible. -- We cannot use a real XML/Sax parser (such as XML/Ada) because we must handle errors and -- backtrack from HTML parsing to wiki or raw text parsing. -- -- When parsing HTML content, we call the <tt>Start_Element</tt> or <tt>End_Element</tt> -- operations. The renderer is then able to handle the HTML tag according to its needs. private package Wiki.Parsers.Html is pragma Preelaborate; -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> procedure Parse_Element (P : in out Parser); end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- This is a small HTML parser that is called to deal with embedded HTML in wiki text. -- The parser is intended to handle incorrect HTML and clean the result as much as possible. -- We cannot use a real XML/Sax parser (such as XML/Ada) because we must handle errors and -- backtrack from HTML parsing to wiki or raw text parsing. -- -- When parsing HTML content, we call the <tt>Start_Element</tt> or <tt>End_Element</tt> -- operations. The renderer is then able to handle the HTML tag according to its needs. private package Wiki.Parsers.Html is pragma Preelaborate; -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> procedure Parse_Element (P : in out Parser); -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character); end Wiki.Parsers.Html;
Declare Parse_Entity procedure
Declare Parse_Entity procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
bd69ab4f2a7c7d76fba38237e40df82c8eb1056c
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Get the roles that grant the given permission. function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; type Role_Name_Array is array (Role_Type range <>) of Ada.Strings.Unbounded.String_Access; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Get the roles that grant the given permission. function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_Policy is new Policy with record Names : Role_Name_Array (Role_Type'Range) := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
Make the Role_Name_Array type public
Make the Role_Name_Array type public
Ada
apache-2.0
stcarrez/ada-security
3bedebd21e66cc355fe192f10696249566835dd3
awa/src/awa-users-filters.ads
awa/src/awa-users-filters.ads
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- 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 Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Sessions; with ASF.Principals; with ASF.Filters; with ASF.Servlets; with ASF.Security.Filters; with AWA.Users.Principals; package AWA.Users.Filters is -- Set the user principal on the session associated with the ASF request. procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Authentication verification filter -- ------------------------------ -- The <b>Auth_Filter</b> verifies that the user has the permission to access -- a given page. If the user is not logged, it tries to login automatically -- by using some persistent cookie. When this fails, it redirects the -- user to a login page (configured by AUTH_FILTER_REDIRECT_PARAM property). type Auth_Filter is new ASF.Security.Filters.Auth_Filter with private; -- The configuration parameter which controls the redirection page -- when the user is not logged (this should be the login page). AUTH_FILTER_REDIRECT_PARAM : constant String := "user.auth-filter.redirect"; -- A temporary cookie used to store the URL for redirection after the login is successful. REDIRECT_COOKIE : constant String := "RURL"; -- Initialize the filter and configure the redirection URIs. overriding procedure Initialize (Filter : in out Auth_Filter; Context : in ASF.Servlets.Servlet_Registry'Class); -- Authenticate a user by using the auto-login cookie. This procedure is called if the -- current session does not have any principal. Based on the request and the optional -- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return -- a principal object. The principal object will be freed when the session is closed. -- If the user cannot be authenticated, the returned principal should be null. -- -- The default implementation returns a null principal. overriding procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access); -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- ------------------------------ -- Verify access key filter -- ------------------------------ -- The <b>Verify_Filter</b> filter verifies an access key associated to a user. -- The access key should have been sent to the user by some mechanism (email). -- The access key must be valid, that is an <b>Access_Key</b> database entry -- must exist and it must be associated with an email address and a user. type Verify_Filter is new ASF.Filters.Filter with private; -- The request parameter that <b>Verify_Filter</b> will check. PARAM_ACCESS_KEY : constant String := "key"; -- The configuration parameter which controls the redirection page -- when the access key is invalid. VERIFY_FILTER_REDIRECT_PARAM : constant String := "user.verify-filter.redirect"; -- Initialize the filter and configure the redirection URIs. procedure Initialize (Filter : in out Verify_Filter; Context : in ASF.Servlets.Servlet_Registry'Class); -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); private use Ada.Strings.Unbounded; type Auth_Filter is new ASF.Security.Filters.Auth_Filter with record Login_URI : Unbounded_String; end record; type Verify_Filter is new ASF.Filters.Filter with record Invalid_Key_URI : Unbounded_String; end record; end AWA.Users.Filters;
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- 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 Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Sessions; with ASF.Principals; with ASF.Filters; with ASF.Servlets; with ASF.Security.Filters; with AWA.Users.Principals; package AWA.Users.Filters is -- Set the user principal on the session associated with the ASF request. procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Authentication verification filter -- ------------------------------ -- The <b>Auth_Filter</b> verifies that the user has the permission to access -- a given page. If the user is not logged, it tries to login automatically -- by using some persistent cookie. When this fails, it redirects the -- user to a login page (configured by AUTH_FILTER_REDIRECT_PARAM property). type Auth_Filter is new ASF.Security.Filters.Auth_Filter with private; -- The configuration parameter which controls the redirection page -- when the user is not logged (this should be the login page). AUTH_FILTER_REDIRECT_PARAM : constant String := "user.auth-filter.redirect"; -- A temporary cookie used to store the URL for redirection after the login is successful. REDIRECT_COOKIE : constant String := "RURL"; -- Initialize the filter and configure the redirection URIs. overriding procedure Initialize (Filter : in out Auth_Filter; Config : in ASF.Servlets.Filter_Config); -- Authenticate a user by using the auto-login cookie. This procedure is called if the -- current session does not have any principal. Based on the request and the optional -- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return -- a principal object. The principal object will be freed when the session is closed. -- If the user cannot be authenticated, the returned principal should be null. -- -- The default implementation returns a null principal. overriding procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access); -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- ------------------------------ -- Verify access key filter -- ------------------------------ -- The <b>Verify_Filter</b> filter verifies an access key associated to a user. -- The access key should have been sent to the user by some mechanism (email). -- The access key must be valid, that is an <b>Access_Key</b> database entry -- must exist and it must be associated with an email address and a user. type Verify_Filter is new ASF.Filters.Filter with private; -- The request parameter that <b>Verify_Filter</b> will check. PARAM_ACCESS_KEY : constant String := "key"; -- The configuration parameter which controls the redirection page -- when the access key is invalid. VERIFY_FILTER_REDIRECT_PARAM : constant String := "user.verify-filter.redirect"; -- Initialize the filter and configure the redirection URIs. procedure Initialize (Filter : in out Verify_Filter; Config : in ASF.Servlets.Filter_Config); -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); private use Ada.Strings.Unbounded; type Auth_Filter is new ASF.Security.Filters.Auth_Filter with record Login_URI : Unbounded_String; end record; type Verify_Filter is new ASF.Filters.Filter with record Invalid_Key_URI : Unbounded_String; end record; end AWA.Users.Filters;
Update the filter to use the Filter_Config
Update the filter to use the Filter_Config
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4371ca7c8bd1a5f86fd7bc9694f74274d79d76e4
regtests/util-dates-tests.ads
regtests/util-dates-tests.ads
----------------------------------------------------------------------- -- util-dates-tests - Test for dates -- Copyright (C) 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Dates.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test converting a date in ISO8601. procedure Test_ISO8601_Image (T : in out Test); -- Test converting a string in ISO8601 into a date. procedure Test_ISO8601_Value (T : in out Test); -- Test value convertion errors. procedure Test_ISO8601_Error (T : in out Test); end Util.Dates.Tests;
----------------------------------------------------------------------- -- util-dates-tests - Test for dates -- Copyright (C) 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Dates.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test converting a date in ISO8601. procedure Test_ISO8601_Image (T : in out Test); -- Test converting a string in ISO8601 into a date. procedure Test_ISO8601_Value (T : in out Test); -- Test value convertion errors. procedure Test_ISO8601_Error (T : in out Test); -- Test Is_Same_Day operation. procedure Test_Is_Same_Day (T : in out Test); end Util.Dates.Tests;
Add Test_Is_Same_Day to check the Is_Same_Day operation
Add Test_Is_Same_Day to check the Is_Same_Day operation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e225ab253c56e1e939a1fd6938c802075d254c56
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Contexts; package body Security.Policies is use type Permissions.Permission_Index; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); -- ------------------------------ -- Default Security Controllers -- ------------------------------ -- The <b>Auth_Controller</b> grants the permission if there is a principal. type Auth_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- The <b>Pass_Through_Controller</b> grants access to anybody. type Pass_Through_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). -- ------------------------------ overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Permission); use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then Log.Debug ("Grant permission because a principal exists"); return True; else return False; end if; end Has_Permission; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. -- ------------------------------ overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Context, Permission); begin Log.Debug ("Pass through controller grants the permission"); return True; end Has_Permission; -- ------------------------------ -- 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; -- ------------------------------ -- 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 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; -- If the permission has a controller, release it. if Manager.Permissions (Index) /= null then Log.Warn ("Permission {0} is redefined", Name); -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access; begin Free (P); 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 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; -- ------------------------------ -- Returns True if the security controller is defined for the given permission index. -- ------------------------------ function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean is begin return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null; end Has_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; -- ------------------------------ -- Prepare the XML parser to read the policy configuration. -- ------------------------------ procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- 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; end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- 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 Finish_Config; type Policy_Fields is (FIELD_ALL_PERMISSION, FIELD_AUTH_PERMISSION); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is Name : constant String := Util.Beans.Objects.To_String (Value); begin case Field is when FIELD_ALL_PERMISSION => P.Add_Permission (Name, new Pass_Through_Controller); when FIELD_AUTH_PERMISSION => P.Add_Permission (Name, new Auth_Controller); end case; end Set_Member; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Manager'Class, Element_Type_Access => Policy_Manager_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- 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); Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Manager'Unchecked_Access); Manager.Prepare_Config (Reader); -- Read the configuration file. Reader.Parse (File); Manager.Finish_Config (Reader); end Read_Policy; -- ------------------------------ -- Initialize the policy manager. -- ------------------------------ overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Policy'Class, Policy_Access); begin -- Release the security controllers. if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop if Manager.Permissions (I) /= null then -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end if; end loop; Free (Manager.Permissions); end if; -- Release the policy instances. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Free (Manager.Policies (I)); end loop; end Finalize; begin Policy_Mapping.Add_Mapping ("all-permission/name", FIELD_ALL_PERMISSION); Policy_Mapping.Add_Mapping ("auth-permission/name", FIELD_AUTH_PERMISSION); end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Contexts; package body Security.Policies is use type Permissions.Permission_Index; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); -- ------------------------------ -- Default Security Controllers -- ------------------------------ -- The <b>Auth_Controller</b> grants the permission if there is a principal. type Auth_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- The <b>Pass_Through_Controller</b> grants access to anybody. type Pass_Through_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). -- ------------------------------ overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Permission); use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then Log.Debug ("Grant permission because a principal exists"); return True; else return False; end if; end Has_Permission; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. -- ------------------------------ overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Context, Permission); begin Log.Debug ("Pass through controller grants the permission"); return True; end Has_Permission; -- ------------------------------ -- 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; -- ------------------------------ -- 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 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; -- If the permission has a controller, release it. if Manager.Permissions (Index) /= null then Log.Warn ("Permission {0} is redefined", Name); -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access; begin Free (P); 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 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; -- ------------------------------ -- Returns True if the security controller is defined for the given permission index. -- ------------------------------ function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean is begin return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null; end Has_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; -- ------------------------------ -- Prepare the XML parser to read the policy configuration. -- ------------------------------ procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- 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; end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- 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 Finish_Config; type Policy_Fields is (FIELD_GRANT_PERMISSION, FIELD_AUTH_PERMISSION); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is Name : constant String := Util.Beans.Objects.To_String (Value); begin case Field is when FIELD_GRANT_PERMISSION => P.Add_Permission (Name, new Pass_Through_Controller); when FIELD_AUTH_PERMISSION => P.Add_Permission (Name, new Auth_Controller); end case; end Set_Member; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Manager'Class, Element_Type_Access => Policy_Manager_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- 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); Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Manager'Unchecked_Access); Manager.Prepare_Config (Reader); -- Read the configuration file. Reader.Parse (File); Manager.Finish_Config (Reader); end Read_Policy; -- ------------------------------ -- Initialize the policy manager. -- ------------------------------ overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Policy'Class, Policy_Access); begin -- Release the security controllers. if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop if Manager.Permissions (I) /= null then -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end if; end loop; Free (Manager.Permissions); end if; -- Release the policy instances. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Free (Manager.Policies (I)); end loop; end Finalize; begin Policy_Mapping.Add_Mapping ("grant-permission/name", FIELD_GRANT_PERMISSION); Policy_Mapping.Add_Mapping ("auth-permission/name", FIELD_AUTH_PERMISSION); end Security.Policies;
Rename the <all-permission> into <grant-permission>
Rename the <all-permission> into <grant-permission>
Ada
apache-2.0
Letractively/ada-security
2175214665681fa18484e050de45645df4360fb3
src/asf-components-core-factory.adb
src/asf-components-core-factory.adb
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- Copyright (C) 2009, 2010, 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Base; with ASF.Views.Nodes; with ASF.Views.Nodes.Jsf; with ASF.Components.Html.Selects; with ASF.Components.Core.Views; package body ASF.Components.Core.Factory is function Create_View return Base.UIComponent_Access; function Create_ViewAction return Base.UIComponent_Access; function Create_ViewMetaData return Base.UIComponent_Access; function Create_ViewParameter return Base.UIComponent_Access; function Create_Parameter return Base.UIComponent_Access; function Create_SelectItem return Base.UIComponent_Access; function Create_SelectItems return Base.UIComponent_Access; -- ------------------------------ -- Create an UIView component -- ------------------------------ function Create_View return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIView; end Create_View; -- ------------------------------ -- Create an UIViewAction component -- ------------------------------ function Create_ViewAction return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewAction; end Create_ViewAction; -- ------------------------------ -- Create an UIViewMetaData component -- ------------------------------ function Create_ViewMetaData return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewMetaData; end Create_ViewMetaData; -- ------------------------------ -- Create an UIViewParameter component -- ------------------------------ function Create_ViewParameter return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewParameter; end Create_ViewParameter; -- ------------------------------ -- Create an UIParameter component -- ------------------------------ function Create_Parameter return Base.UIComponent_Access is begin return new ASF.Components.Core.UIParameter; end Create_Parameter; -- ------------------------------ -- Create an UISelectItem component -- ------------------------------ function Create_SelectItem return Base.UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectItem; end Create_SelectItem; -- ------------------------------ -- Create an UISelectItems component -- ------------------------------ function Create_SelectItems return Base.UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectItems; end Create_SelectItems; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/core"; ATTRIBUTE_TAG : aliased constant String := "attribute"; CONVERT_DATE_TIME_TAG : aliased constant String := "convertDateTime"; CONVERTER_TAG : aliased constant String := "converter"; FACET_TAG : aliased constant String := "facet"; METADATA_TAG : aliased constant String := "metadata"; PARAM_TAG : aliased constant String := "param"; SELECT_ITEM_TAG : aliased constant String := "selectItem"; SELECT_ITEMS_TAG : aliased constant String := "selectItems"; VALIDATE_LENGTH_TAG : aliased constant String := "validateLength"; VALIDATE_LONG_RANGE_TAG : aliased constant String := "validateLongRange"; VALIDATOR_TAG : aliased constant String := "validator"; VIEW_TAG : aliased constant String := "view"; VIEW_ACTION_TAG : aliased constant String := "viewAction"; VIEW_PARAM_TAG : aliased constant String := "viewParam"; Core_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => ATTRIBUTE_TAG'Access, Component => null, Tag => ASF.Views.Nodes.Jsf.Create_Attribute_Tag_Node'Access), 2 => (Name => CONVERT_DATE_TIME_TAG'Access, Component => null, Tag => ASF.Views.Nodes.Jsf.Create_Convert_Date_Time_Tag_Node'Access), 3 => (Name => CONVERTER_TAG'Access, Component => null, Tag => ASF.Views.Nodes.Jsf.Create_Converter_Tag_Node'Access), 4 => (Name => FACET_TAG'Access, Component => null, Tag => ASF.Views.Nodes.Jsf.Create_Facet_Tag_Node'Access), 5 => (Name => METADATA_TAG'Access, Component => Create_ViewMetaData'Access, Tag => ASF.Views.Nodes.Jsf.Create_Metadata_Tag_Node'Access), 6 => (Name => PARAM_TAG'Access, Component => Create_Parameter'Access, Tag => Create_Component_Node'Access), 7 => (Name => SELECT_ITEM_TAG'Access, Component => Create_SelectItem'Access, Tag => Create_Component_Node'Access), 8 => (Name => SELECT_ITEMS_TAG'Access, Component => Create_SelectItems'Access, Tag => Create_Component_Node'Access), 9 => (Name => VALIDATE_LENGTH_TAG'Access, Component => null, Tag => ASF.Views.Nodes.Jsf.Create_Length_Validator_Tag_Node'Access), 10 => (Name => VALIDATE_LONG_RANGE_TAG'Access, Component => null, Tag => ASF.Views.Nodes.Jsf.Create_Range_Validator_Tag_Node'Access), 11 => (Name => VALIDATOR_TAG'Access, Component => null, Tag => ASF.Views.Nodes.Jsf.Create_Validator_Tag_Node'Access), 12 => (Name => VIEW_TAG'Access, Component => Create_View'Access, Tag => Create_Component_Node'Access), 13 => (Name => VIEW_ACTION_TAG'Access, Component => Create_ViewAction'Access, Tag => Create_Component_Node'Access), 14 => (Name => VIEW_PARAM_TAG'Access, Component => Create_ViewParameter'Access, Tag => Create_Component_Node'Access) ); Core_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Core_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Core_Factory'Access; end Definition; end ASF.Components.Core.Factory;
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- Copyright (C) 2009, 2010, 2011, 2012, 2014, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Base; with ASF.Views.Nodes; with ASF.Views.Nodes.Jsf; with ASF.Components.Html.Selects; with ASF.Components.Core.Views; package body ASF.Components.Core.Factory is function Create_View return Base.UIComponent_Access; function Create_ViewAction return Base.UIComponent_Access; function Create_ViewMetaData return Base.UIComponent_Access; function Create_ViewParameter return Base.UIComponent_Access; function Create_Parameter return Base.UIComponent_Access; function Create_SelectItem return Base.UIComponent_Access; function Create_SelectItems return Base.UIComponent_Access; -- ------------------------------ -- Create an UIView component -- ------------------------------ function Create_View return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIView; end Create_View; -- ------------------------------ -- Create an UIViewAction component -- ------------------------------ function Create_ViewAction return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewAction; end Create_ViewAction; -- ------------------------------ -- Create an UIViewMetaData component -- ------------------------------ function Create_ViewMetaData return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewMetaData; end Create_ViewMetaData; -- ------------------------------ -- Create an UIViewParameter component -- ------------------------------ function Create_ViewParameter return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewParameter; end Create_ViewParameter; -- ------------------------------ -- Create an UIParameter component -- ------------------------------ function Create_Parameter return Base.UIComponent_Access is begin return new ASF.Components.Core.UIParameter; end Create_Parameter; -- ------------------------------ -- Create an UISelectItem component -- ------------------------------ function Create_SelectItem return Base.UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectItem; end Create_SelectItem; -- ------------------------------ -- Create an UISelectItems component -- ------------------------------ function Create_SelectItems return Base.UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectItems; end Create_SelectItems; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/core"; ATTRIBUTE_TAG : aliased constant String := "attribute"; CONVERT_DATE_TIME_TAG : aliased constant String := "convertDateTime"; CONVERTER_TAG : aliased constant String := "converter"; FACET_TAG : aliased constant String := "facet"; METADATA_TAG : aliased constant String := "metadata"; PARAM_TAG : aliased constant String := "param"; SELECT_ITEM_TAG : aliased constant String := "selectItem"; SELECT_ITEMS_TAG : aliased constant String := "selectItems"; VALIDATE_LENGTH_TAG : aliased constant String := "validateLength"; VALIDATE_LONG_RANGE_TAG : aliased constant String := "validateLongRange"; VALIDATOR_TAG : aliased constant String := "validator"; VIEW_TAG : aliased constant String := "view"; VIEW_ACTION_TAG : aliased constant String := "viewAction"; VIEW_PARAM_TAG : aliased constant String := "viewParam"; -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ procedure Register (Factory : in out ASF.Factory.Component_Factory) is begin ASF.Factory.Register (Factory, URI => URI'Access, Name => ATTRIBUTE_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Attribute_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => CONVERT_DATE_TIME_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Convert_Date_Time_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => CONVERTER_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Converter_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => FACET_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Facet_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => METADATA_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Metadata_Tag_Node'Access, Create => Create_ViewMetaData'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => PARAM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Parameter'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ITEM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectItem'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ITEMS_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectItems'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATE_LENGTH_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Length_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATE_LONG_RANGE_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Range_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATOR_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_View'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_ACTION_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_ViewAction'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_PARAM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_ViewParameter'Access); end Register; end ASF.Components.Core.Factory;
Change the Definition function into a Register procedure
Change the Definition function into a Register procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
ee608c2a6c844b50cdd9be1dfe489ce6a73072fa
src/util-serialize-io-csv.adb
src/util-serialize-io-csv.adb
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- 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.Strings.Unbounded; with Ada.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; Stream.Write ('"'); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ("""null"""); when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("""true"""); else Stream.Write ("""false"""); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (","); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Parser'Class (Handler).Finish_Object (""); end if; Parser'Class (Handler).Start_Object (""); end if; Handler.Row := Row; Parser'Class (Handler).Set_Member (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; Context : Element_Context_Access; begin Context_Stack.Push (Handler.Stack); Context := Context_Stack.Current (Handler.Stack); Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Context_Stack.Pop (Handler.Stack); return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; Stream.Write ('"'); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ("""null"""); when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("""true"""); else Stream.Write ("""false"""); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (","); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Parser'Class (Handler).Finish_Object (""); end if; Parser'Class (Handler).Start_Object (""); end if; Handler.Row := Row; Parser'Class (Handler).Set_Member (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; Context : Element_Context_Access; begin Context_Stack.Push (Handler.Stack); Context := Context_Stack.Current (Handler.Stack); Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Context_Stack.Pop (Handler.Stack); return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
Fix compilation style warning
Fix compilation style warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
90395281d4d4612dd38404295cd40b8742842899
src/util-streams-buffered.adb
src/util-streams-buffered.adb
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams Stream utilities -- Copyright (C) 2010, 2011, 2013, 2014, 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 Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Output : in Output_Stream_Access; Input : in Input_Stream_Access; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Output := null; Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; Stream.No_Flush := False; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Input => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Buffered_Stream) is begin if Stream.Output /= null then Buffered_Stream'Class (Stream).Flush; Stream.Output.Close; end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Buffered_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Buffered_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Stream.Last - Pos + 1; if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data that the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then Stream.Flush; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Buffered_Stream) is begin if Stream.Write_Pos > 1 and not Stream.No_Flush then if Stream.Output = null then raise Ada.IO_Exceptions.Data_Error with "Output buffer is full"; else Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); Stream.Output.Flush; end if; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Buffered_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Buffered_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Buffered_Stream) is begin if Object.Buffer /= null then if Object.Output /= null then Object.Flush; end if; Free_Buffer (Object.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Buffered_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; end Util.Streams.Buffered;
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Output : in Output_Stream_Access; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Input : in Input_Stream_Access; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Buffer_Stream) is begin if Stream.Output /= null then Output_Buffer_Stream'Class (Stream).Flush; Stream.Output.Close; end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Output_Buffer_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Stream.Last - Pos + 1; if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data that the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then Stream.Flush; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Buffer_Stream) is begin if Stream.Write_Pos > 1 and not Stream.No_Flush then if Stream.Output = null then raise Ada.IO_Exceptions.Data_Error with "Output buffer is full"; else Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); Stream.Output.Flush; end if; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Input_Buffer_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Output_Buffer_Stream) is begin if Object.Buffer /= null then if Object.Output /= null then Object.Flush; end if; Free_Buffer (Object.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Input_Buffer_Stream) is begin if Object.Buffer /= null then Free_Buffer (Object.Buffer); end if; end Finalize; end Util.Streams.Buffered;
Refactor Buffered_Stream into Output_Buffer_Stream and Input_Buffer_Stream - separate the Initialize procedure for input vs output buffer - implement Finalize for the Input_Buffer_Stream
Refactor Buffered_Stream into Output_Buffer_Stream and Input_Buffer_Stream - separate the Initialize procedure for input vs output buffer - implement Finalize for the Input_Buffer_Stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c05017288489ecd96183914c4596819d8d4d59a7
src/util-processes.adb
src/util-processes.adb
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- 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 Util.Log.Loggers; with Util.Strings; with Util.Processes.Os; package body Util.Processes is use Util.Log; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes"); procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Processes.System_Process'Class, Name => Util.Processes.System_Process_Access); -- ------------------------------ -- Before launching the process, redirect the input stream of the process -- to the specified file. -- ------------------------------ procedure Set_Input_Stream (Proc : in out Process; File : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set input stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.In_File := To_Unbounded_String (File); end Set_Input_Stream; -- ------------------------------ -- Set the output stream of the process. -- ------------------------------ procedure Set_Output_Stream (Proc : in out Process; File : in String; Append : in Boolean := False) is begin if Proc.Is_Running then Log.Error ("Cannot set output stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.Out_File := To_Unbounded_String (File); Proc.Out_Append := Append; end Set_Output_Stream; -- ------------------------------ -- Set the error stream of the process. -- ------------------------------ procedure Set_Error_Stream (Proc : in out Process; File : in String; Append : in Boolean := False) is begin if Proc.Is_Running then Log.Error ("Cannot set error stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.Err_File := To_Unbounded_String (File); Proc.Err_Append := Append; end Set_Error_Stream; -- ------------------------------ -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. -- ------------------------------ procedure Set_Working_Directory (Proc : in out Process; Path : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set working directory to {0} while process is running", Path); raise Invalid_State with "Process is running"; end if; Proc.Dir := To_Unbounded_String (Path); end Set_Working_Directory; -- ------------------------------ -- Append the argument to the current process argument list. -- Raises <b>Invalid_State</b> if the process is running. -- ------------------------------ procedure Append_Argument (Proc : in out Process; Arg : in String) is begin if Proc.Is_Running then Log.Error ("Cannot add argument '{0}' while process is running", Arg); raise Invalid_State with "Process is running"; end if; Proc.Sys.Append_Argument (Arg); end Append_Argument; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Command : in String; Arguments : in Argument_List) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); Free (Proc.Sys); Proc.Sys := new Util.Processes.Os.System_Process; -- Build the argc/argv table, terminate by NULL for I in Arguments'Range loop Proc.Sys.Append_Argument (Arguments (I).all); end loop; -- Prepare to redirect the input/output/error streams. Proc.Sys.Set_Streams (Input => To_String (Proc.In_File), Output => To_String (Proc.Out_File), Error => To_String (Proc.Err_File), Append_Output => Proc.Out_Append, Append_Error => Proc.Err_Append); -- System specific spawn Proc.Exit_Value := -1; Proc.Sys.Spawn (Proc); end Spawn; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Command : in String; Mode : in Pipe_Mode := NONE) is Pos : Natural := Command'First; N : Natural; begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); Free (Proc.Sys); Proc.Sys := new Util.Processes.Os.System_Process; -- Build the argc/argv table while Pos <= Command'Last loop N := Util.Strings.Index (Command, ' ', Pos); if N = 0 then N := Command'Last + 1; end if; Proc.Sys.Append_Argument (Command (Pos .. N - 1)); Pos := N + 1; end loop; -- Prepare to redirect the input/output/error streams. -- The pipe mode takes precedence and will override these redirections. Proc.Sys.Set_Streams (Input => To_String (Proc.In_File), Output => To_String (Proc.Out_File), Error => To_String (Proc.Err_File), Append_Output => Proc.Out_Append, Append_Error => Proc.Err_Append); -- System specific spawn Proc.Exit_Value := -1; Proc.Sys.Spawn (Proc, Mode); end Spawn; -- ------------------------------ -- Wait for the process to terminate. -- ------------------------------ procedure Wait (Proc : in out Process) is begin if not Is_Running (Proc) then return; end if; Log.Info ("Waiting for process {0}", Process_Identifier'Image (Proc.Pid)); Proc.Sys.Wait (Proc, -1.0); end Wait; -- ------------------------------ -- Get the process exit status. -- ------------------------------ function Get_Exit_Status (Proc : in Process) return Integer is begin return Proc.Exit_Value; end Get_Exit_Status; -- ------------------------------ -- Get the process identifier. -- ------------------------------ function Get_Pid (Proc : in Process) return Process_Identifier is begin return Proc.Pid; end Get_Pid; -- ------------------------------ -- Returns True if the process is running. -- ------------------------------ function Is_Running (Proc : in Process) return Boolean is begin return Proc.Pid > 0 and Proc.Exit_Value < 0; end Is_Running; -- ------------------------------ -- Get the process input stream allowing to write on the process standard input. -- ------------------------------ function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access is begin return Proc.Input; end Get_Input_Stream; -- ------------------------------ -- Get the process output stream allowing to read the process standard output. -- ------------------------------ function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access is begin return Proc.Output; end Get_Output_Stream; -- ------------------------------ -- Get the process error stream allowing to read the process standard output. -- ------------------------------ function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access is begin return Proc.Error; end Get_Error_Stream; -- ------------------------------ -- Initialize the process instance. -- ------------------------------ overriding procedure Initialize (Proc : in out Process) is begin Proc.Sys := new Util.Processes.Os.System_Process; end Initialize; -- ------------------------------ -- Deletes the process instance. -- ------------------------------ overriding procedure Finalize (Proc : in out Process) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Streams.Input_Stream'Class, Name => Util.Streams.Input_Stream_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Streams.Output_Stream'Class, Name => Util.Streams.Output_Stream_Access); begin if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Free (Proc.Input); Free (Proc.Output); Free (Proc.Error); end Finalize; end Util.Processes;
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- 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 Util.Log.Loggers; with Util.Strings; with Util.Processes.Os; package body Util.Processes is use Util.Log; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes"); procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Processes.System_Process'Class, Name => Util.Processes.System_Process_Access); -- ------------------------------ -- Before launching the process, redirect the input stream of the process -- to the specified file. -- ------------------------------ procedure Set_Input_Stream (Proc : in out Process; File : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set input stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.In_File := To_Unbounded_String (File); end Set_Input_Stream; -- ------------------------------ -- Set the output stream of the process. -- ------------------------------ procedure Set_Output_Stream (Proc : in out Process; File : in String; Append : in Boolean := False) is begin if Proc.Is_Running then Log.Error ("Cannot set output stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.Out_File := To_Unbounded_String (File); Proc.Out_Append := Append; end Set_Output_Stream; -- ------------------------------ -- Set the error stream of the process. -- ------------------------------ procedure Set_Error_Stream (Proc : in out Process; File : in String; Append : in Boolean := False) is begin if Proc.Is_Running then Log.Error ("Cannot set error stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.Err_File := To_Unbounded_String (File); Proc.Err_Append := Append; end Set_Error_Stream; -- ------------------------------ -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. -- ------------------------------ procedure Set_Working_Directory (Proc : in out Process; Path : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set working directory to {0} while process is running", Path); raise Invalid_State with "Process is running"; end if; Proc.Dir := To_Unbounded_String (Path); end Set_Working_Directory; -- ------------------------------ -- Append the argument to the current process argument list. -- Raises <b>Invalid_State</b> if the process is running. -- ------------------------------ procedure Append_Argument (Proc : in out Process; Arg : in String) is begin if Proc.Is_Running then Log.Error ("Cannot add argument '{0}' while process is running", Arg); raise Invalid_State with "Process is running"; end if; Proc.Sys.Append_Argument (Arg); end Append_Argument; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Command : in String; Arguments : in Argument_List) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Proc.Sys := new Util.Processes.Os.System_Process; -- Build the argc/argv table, terminate by NULL for I in Arguments'Range loop Proc.Sys.Append_Argument (Arguments (I).all); end loop; -- Prepare to redirect the input/output/error streams. Proc.Sys.Set_Streams (Input => To_String (Proc.In_File), Output => To_String (Proc.Out_File), Error => To_String (Proc.Err_File), Append_Output => Proc.Out_Append, Append_Error => Proc.Err_Append); -- System specific spawn Proc.Exit_Value := -1; Proc.Sys.Spawn (Proc); end Spawn; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Command : in String; Mode : in Pipe_Mode := NONE) is Pos : Natural := Command'First; N : Natural; begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Proc.Sys := new Util.Processes.Os.System_Process; -- Build the argc/argv table while Pos <= Command'Last loop N := Util.Strings.Index (Command, ' ', Pos); if N = 0 then N := Command'Last + 1; end if; Proc.Sys.Append_Argument (Command (Pos .. N - 1)); Pos := N + 1; end loop; -- Prepare to redirect the input/output/error streams. -- The pipe mode takes precedence and will override these redirections. Proc.Sys.Set_Streams (Input => To_String (Proc.In_File), Output => To_String (Proc.Out_File), Error => To_String (Proc.Err_File), Append_Output => Proc.Out_Append, Append_Error => Proc.Err_Append); -- System specific spawn Proc.Exit_Value := -1; Proc.Sys.Spawn (Proc, Mode); end Spawn; -- ------------------------------ -- Wait for the process to terminate. -- ------------------------------ procedure Wait (Proc : in out Process) is begin if not Is_Running (Proc) then return; end if; Log.Info ("Waiting for process {0}", Process_Identifier'Image (Proc.Pid)); Proc.Sys.Wait (Proc, -1.0); end Wait; -- ------------------------------ -- Get the process exit status. -- ------------------------------ function Get_Exit_Status (Proc : in Process) return Integer is begin return Proc.Exit_Value; end Get_Exit_Status; -- ------------------------------ -- Get the process identifier. -- ------------------------------ function Get_Pid (Proc : in Process) return Process_Identifier is begin return Proc.Pid; end Get_Pid; -- ------------------------------ -- Returns True if the process is running. -- ------------------------------ function Is_Running (Proc : in Process) return Boolean is begin return Proc.Pid > 0 and Proc.Exit_Value < 0; end Is_Running; -- ------------------------------ -- Get the process input stream allowing to write on the process standard input. -- ------------------------------ function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access is begin return Proc.Input; end Get_Input_Stream; -- ------------------------------ -- Get the process output stream allowing to read the process standard output. -- ------------------------------ function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access is begin return Proc.Output; end Get_Output_Stream; -- ------------------------------ -- Get the process error stream allowing to read the process standard output. -- ------------------------------ function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access is begin return Proc.Error; end Get_Error_Stream; -- ------------------------------ -- Initialize the process instance. -- ------------------------------ overriding procedure Initialize (Proc : in out Process) is begin Proc.Sys := new Util.Processes.Os.System_Process; end Initialize; -- ------------------------------ -- Deletes the process instance. -- ------------------------------ overriding procedure Finalize (Proc : in out Process) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Streams.Input_Stream'Class, Name => Util.Streams.Input_Stream_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Streams.Output_Stream'Class, Name => Util.Streams.Output_Stream_Access); begin if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Free (Proc.Input); Free (Proc.Output); Free (Proc.Error); end Finalize; end Util.Processes;
Fix finalization of system specific process implementation launch
Fix finalization of system specific process implementation launch
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
dca51fd10cc13a4f4b24ce078e4e9c775bf5805c
src/orka/implementation/orka-jobs-executors.adb
src/orka/implementation/orka-jobs-executors.adb
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Real_Time; -- with Ada.Tags; -- with Ada.Text_IO; with Orka.Containers.Bounded_Vectors; with Orka.Futures; package body Orka.Jobs.Executors is function Get_Root_Dependent (Element : Job_Ptr) return Job_Ptr is Result : Job_Ptr := Element; begin while Result.Dependent /= Null_Job loop Result := Result.Dependent; end loop; return Result; end Get_Root_Dependent; procedure Execute_Jobs (Name : String; Kind : Queues.Executor_Kind; Queue : Queues.Queue_Ptr) is use type Ada.Real_Time.Time; use type Futures.Status; Pair : Queues.Pair; Stop : Boolean := False; Null_Pair : constant Queues.Pair := Queues.Get_Null_Pair; package Vectors is new Orka.Containers.Bounded_Vectors (Job_Ptr, Get_Null_Job); -- T0, T1, T2 : Ada.Real_Time.Time; begin loop -- T0 := Ada.Real_Time.Clock; Queue.Dequeue (Kind) (Pair, Stop); exit when Stop; declare Job : Job_Ptr renames Pair.Job; Future : Futures.Pointers.Reference renames Pair.Future.Get; Promise : Futures.Promise'Class renames Futures.Promise'Class (Future.Value.all); Jobs : Vectors.Vector (Capacity => Maximum_Enqueued_By_Job); procedure Enqueue (Element : Job_Ptr) is begin Jobs.Append (Element); end Enqueue; procedure Set_Root_Dependent (Last_Job : Job_Ptr) is Root_Dependents : Vectors.Vector (Capacity => Jobs.Length); procedure Set_Dependencies (Elements : Vectors.Element_Array) is begin Last_Job.Set_Dependencies (Dependency_Array (Elements)); end Set_Dependencies; begin for Job of Jobs loop declare Root : constant Job_Ptr := Get_Root_Dependent (Job); begin if not (for some Dependent of Root_Dependents => Root = Dependent) then Root_Dependents.Append (Root); end if; end; end loop; Root_Dependents.Query (Set_Dependencies'Access); end Set_Root_Dependent; -- Tag : String renames Ada.Tags.Expanded_Name (Job'Tag); begin -- T1 := Ada.Real_Time.Clock; -- Ada.Text_IO.Put_Line (Name & " executing job " & Tag); if Future.Current_Status = Futures.Waiting then Promise.Set_Status (Futures.Running); end if; begin Job.Execute (Enqueue'Access); exception when Error : others => Promise.Set_Failed (Error); raise; end; -- T2 := Ada.Real_Time.Clock; -- declare -- Waiting_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T1 - T0); -- Running_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T2 - T1); -- begin -- Ada.Text_IO.Put_Line (Name & " (blocked" & Waiting_Time'Image & " ms) executed job " & Tag & " in" & Running_Time'Image & " ms"); -- end; if Job.Dependent /= Null_Job then -- Make the root dependents of the jobs in Jobs -- dependencies of Job.Dependent if not Jobs.Empty then Set_Root_Dependent (Job.Dependent); end if; -- If another job depends on this job, decrement its dependencies counter -- and if it has reached zero then it can be scheduled if Job.Dependent.Decrement_Dependencies then Queue.Enqueue (Job.Dependent, Pair.Future); end if; elsif Jobs.Empty then Promise.Set_Status (Futures.Done); -- Ada.Text_IO.Put_Line (Name & " completed graph with job " & Tag); else -- If the job has enqueued new jobs, we need to create an -- empty job which has the root dependents of these new jobs -- as dependencies. This is so that the empty job will be the -- last job that is given Pair.Future Set_Root_Dependent (Create_Empty_Job); end if; if not Jobs.Empty then for Job of Jobs loop Queue.Enqueue (Job, Pair.Future); end loop; end if; Free (Job); end; -- Finalize the smart pointer (Pair.Future) to reduce the number -- of references to the Future object Pair := Null_Pair; end loop; end Execute_Jobs; end Orka.Jobs.Executors;
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Real_Time; -- with Ada.Tags; -- with Ada.Text_IO; with Orka.Containers.Bounded_Vectors; with Orka.Futures; package body Orka.Jobs.Executors is function Get_Root_Dependent (Element : Job_Ptr) return Job_Ptr is Result : Job_Ptr := Element; begin while Result.Dependent /= Null_Job loop Result := Result.Dependent; end loop; return Result; end Get_Root_Dependent; procedure Execute_Jobs (Name : String; Kind : Queues.Executor_Kind; Queue : Queues.Queue_Ptr) is use type Ada.Real_Time.Time; use type Futures.Status; Pair : Queues.Pair; Stop : Boolean := False; Null_Pair : constant Queues.Pair := Queues.Get_Null_Pair; package Vectors is new Orka.Containers.Bounded_Vectors (Job_Ptr, Get_Null_Job); -- T0, T1, T2 : Ada.Real_Time.Time; begin loop -- T0 := Ada.Real_Time.Clock; Queue.Dequeue (Kind) (Pair, Stop); exit when Stop; declare Job : Job_Ptr renames Pair.Job; Future : Futures.Pointers.Reference renames Pair.Future.Get; Promise : Futures.Promise'Class renames Futures.Promise'Class (Future.Value.all); Jobs : Vectors.Vector (Capacity => Maximum_Enqueued_By_Job); procedure Enqueue (Element : Job_Ptr) is begin Jobs.Append (Element); end Enqueue; procedure Set_Root_Dependent (Last_Job : Job_Ptr) is Root_Dependents : Vectors.Vector (Capacity => Jobs.Length); procedure Set_Dependencies (Elements : Vectors.Element_Array) is begin Last_Job.Set_Dependencies (Dependency_Array (Elements)); end Set_Dependencies; begin for Job of Jobs loop declare Root : constant Job_Ptr := Get_Root_Dependent (Job); begin if not (for some Dependent of Root_Dependents => Root = Dependent) then Root_Dependents.Append (Root); end if; end; end loop; Root_Dependents.Query (Set_Dependencies'Access); end Set_Root_Dependent; -- Tag : String renames Ada.Tags.Expanded_Name (Job'Tag); begin -- T1 := Ada.Real_Time.Clock; -- Ada.Text_IO.Put_Line (Name & " executing job " & Tag); if Future.Current_Status = Futures.Waiting then Promise.Set_Status (Futures.Running); end if; begin Job.Execute (Enqueue'Access); exception when Error : others => Promise.Set_Failed (Error); raise; end; -- T2 := Ada.Real_Time.Clock; -- declare -- Waiting_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T1 - T0); -- Running_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T2 - T1); -- begin -- Ada.Text_IO.Put_Line (Name & " (blocked" & Waiting_Time'Image & " ms) executed job " & Tag & " in" & Running_Time'Image & " ms"); -- end; if Job.Dependent /= Null_Job then -- Make the root dependents of the jobs in Jobs -- dependencies of Job.Dependent if not Jobs.Empty then Set_Root_Dependent (Job.Dependent); end if; -- If another job depends on this job, decrement its dependencies counter -- and if it has reached zero then it can be scheduled if Job.Dependent.Decrement_Dependencies then pragma Assert (Jobs.Empty); Queue.Enqueue (Job.Dependent, Pair.Future); end if; elsif Jobs.Empty then Promise.Set_Status (Futures.Done); -- Ada.Text_IO.Put_Line (Name & " completed graph with job " & Tag); else -- If the job has enqueued new jobs, we need to create an -- empty job which has the root dependents of these new jobs -- as dependencies. This is so that the empty job will be the -- last job that is given Pair.Future Set_Root_Dependent (Create_Empty_Job); end if; if not Jobs.Empty then for Job of Jobs loop Queue.Enqueue (Job, Pair.Future); end loop; end if; Free (Job); end; -- Finalize the smart pointer (Pair.Future) to reduce the number -- of references to the Future object Pair := Null_Pair; end loop; end Execute_Jobs; end Orka.Jobs.Executors;
Add assertion in Orka.Jobs.Executors
orka: Add assertion in Orka.Jobs.Executors Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
6ce4eeb248f4b2fb3770ab93c798cdbdb22fd77c
ARM/STM32/drivers/ltdc/stm32-ltdc.adb
ARM/STM32/drivers/ltdc/stm32-ltdc.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-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 STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f429i_discovery_lcd.c -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief This file includes the LTDC driver to control LCD display. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ with Ada.Interrupts.Names; with Ada.Unchecked_Conversion; with System; use System; with STM32_SVD.LTDC; use STM32_SVD.LTDC; with STM32_SVD.RCC; use STM32_SVD.RCC; package body STM32.LTDC is pragma Warnings (Off, "* is not referenced"); type LCD_Polarity is (Polarity_Active_Low, Polarity_Active_High) with Size => 1; type LCD_PC_Polarity is (Input_Pixel_Clock, Inverted_Input_Pixel_Clock) with Size => 1; pragma Warnings (On, "* is not referenced"); function To_Bool is new Ada.Unchecked_Conversion (LCD_Polarity, Boolean); function To_Bool is new Ada.Unchecked_Conversion (LCD_PC_Polarity, Boolean); -- Extracted from STM32F429x.LTDC type Layer_Type is record LCR : L1CR_Register; -- Layerx Control Register LWHPCR : L1WHPCR_Register; -- Layerx Window Horizontal Position Configuration Register LWVPCR : L1WVPCR_Register; -- Layerx Window Vertical Position Configuration Register LCKCR : L1CKCR_Register; -- Layerx Color Keying Configuration Register LPFCR : L1PFCR_Register; -- Layerx Pixel Format Configuration Register LCACR : L1CACR_Register; -- Layerx Constant Alpha Configuration Register LDCCR : L1DCCR_Register; -- Layerx Default Color Configuration Register LBFCR : L1BFCR_Register; -- Layerx Blending Factors Configuration Register Reserved_0 : Word; Reserved_1 : Word; LCFBAR : Word; -- Layerx Color Frame Buffer Address Register LCFBLR : L1CFBLR_Register; -- Layerx Color Frame Buffer Length Register LCFBLNR : L1CFBLNR_Register; -- Layerx ColorFrame Buffer Line Number Register Reserved_2 : Word; Reserved_3 : Word; Reserved_4 : Word; LCLUTWR : L1CLUTWR_Register; -- Layerx CLUT Write Register end record with Volatile; for Layer_Type use record LCR at 0 range 0 .. 31; LWHPCR at 4 range 0 .. 31; LWVPCR at 8 range 0 .. 31; LCKCR at 12 range 0 .. 31; LPFCR at 16 range 0 .. 31; LCACR at 20 range 0 .. 31; LDCCR at 24 range 0 .. 31; LBFCR at 28 range 0 .. 31; Reserved_0 at 32 range 0 .. 31; Reserved_1 at 36 range 0 .. 31; LCFBAR at 40 range 0 .. 31; LCFBLR at 44 range 0 .. 31; LCFBLNR at 48 range 0 .. 31; Reserved_2 at 52 range 0 .. 31; Reserved_3 at 56 range 0 .. 31; Reserved_4 at 60 range 0 .. 31; LCLUTWR at 64 range 0 .. 31; end record; type Layer_Access is access all Layer_Type; BF1_Constant_Alpha : constant := 2#100#; BF2_Constant_Alpha : constant := 2#101#; BF1_Pixel_Alpha : constant := 2#110#; BF2_Pixel_Alpha : constant := 2#111#; G_Layer1_Reg : aliased Layer_Type with Import, Address => LTDC_Periph.L1CR'Address; G_Layer2_Reg : aliased Layer_Type with Import, Address => LTDC_Periph.L2CR'Address; function Get_Layer (Layer : LCD_Layer) return Layer_Access; -- Retrieve the layer's registers protected Sync is -- Apply pending buffers on Vertical Sync. Caller must call Wait -- afterwards. procedure Apply_On_VSync; -- Wait for an interrupt. entry Wait; procedure Interrupt; pragma Attach_Handler (Interrupt, Ada.Interrupts.Names.LCD_TFT_Interrupt); private Not_Pending : Boolean := True; end Sync; ---------- -- Sync -- ---------- protected body Sync is ---------- -- Wait -- ---------- entry Wait when Not_Pending is begin null; end Wait; -------------------- -- Apply_On_VSync -- -------------------- procedure Apply_On_VSync is begin Not_Pending := False; -- Enable the Register Refresh interrupt LTDC_Periph.IER.RRIE := True; -- And tell the LTDC to apply the layer registers on refresh LTDC_Periph.SRCR.VBR := True; end Apply_On_VSync; --------------- -- Interrupt -- --------------- procedure Interrupt is begin if LTDC_Periph.ISR.RRIF then LTDC_Periph.IER.RRIE := False; LTDC_Periph.ICR.CRRIF := True; Not_Pending := True; end if; end Interrupt; end Sync; --------------- -- Get_Layer -- --------------- function Get_Layer (Layer : LCD_Layer) return Layer_Access is begin if Layer = Layer1 then return G_Layer1_Reg'Access; else return G_Layer2_Reg'Access; end if; end Get_Layer; ------------------- -- Reload_Config -- ------------------- procedure Reload_Config (Immediate : Boolean := False) is begin if Immediate then LTDC_Periph.SRCR.IMR := True; loop exit when not LTDC_Periph.SRCR.IMR; end loop; else Sync.Apply_On_VSync; Sync.Wait; end if; end Reload_Config; --------------------- -- Set_Layer_State -- --------------------- procedure Set_Layer_State (Layer : LCD_Layer; Enabled : Boolean) is L : constant Layer_Access := Get_Layer (Layer); begin if L.LCR.LEN /= Enabled then L.LCR.LEN := Enabled; Reload_Config (Immediate => True); end if; end Set_Layer_State; ---------------- -- Initialize -- ---------------- procedure Initialize (Width : Positive; Height : Positive; H_Sync : Natural; H_Back_Porch : Natural; H_Front_Porch : Natural; V_Sync : Natural; V_Back_Porch : Natural; V_Front_Porch : Natural; PLLSAI_N : UInt9; PLLSAI_R : UInt3; DivR : Natural) is DivR_Val : PLLSAI_DivR; begin if Initialized then return; end if; RCC_Periph.APB2ENR.LTDCEN := True; LTDC_Periph.GCR.VSPOL := To_Bool (Polarity_Active_Low); LTDC_Periph.GCR.HSPOL := To_Bool (Polarity_Active_Low); LTDC_Periph.GCR.DEPOL := To_Bool (Polarity_Active_Low); LTDC_Periph.GCR.PCPOL := To_Bool (Inverted_Input_Pixel_Clock); if DivR = 2 then DivR_Val := PLLSAI_DIV2; elsif DivR = 4 then DivR_Val := PLLSAI_DIV4; elsif DivR = 8 then DivR_Val := PLLSAI_DIV8; elsif DivR = 16 then DivR_Val := PLLSAI_DIV16; else raise Constraint_Error with "Invalid DivR value: 2, 4, 8, 16 allowed"; end if; Disable_PLLSAI; Set_PLLSAI_Factors (LCD => PLLSAI_R, VCO => PLLSAI_N, DivR => DivR_Val); Enable_PLLSAI; -- Synchronization size LTDC_Periph.SSCR := (HSW => SSCR_HSW_Field (H_Sync - 1), VSH => SSCR_VSH_Field (V_Sync - 1), others => <>); -- Accumulated Back Porch LTDC_Periph.BPCR := (AHBP => BPCR_AHBP_Field (H_Sync + H_Back_Porch - 1), AVBP => BPCR_AVBP_Field (V_Sync + V_Back_Porch - 1), others => <>); -- Accumulated Active Width/Height LTDC_Periph.AWCR := (AAW => AWCR_AAW_Field (H_Sync + H_Back_Porch + Width - 1), AAH => AWCR_AAH_Field (V_Sync + V_Back_Porch + Height - 1), others => <>); -- VTotal Width/Height LTDC_Periph.TWCR := (TOTALW => TWCR_TOTALW_Field (H_Sync + H_Back_Porch + Width + H_Front_Porch - 1), TOTALH => TWCR_TOTALH_Field (V_Sync + V_Back_Porch + Height + V_Front_Porch - 1), others => <>); -- Background color to black LTDC_Periph.BCCR.BC := 0; LTDC_Periph.GCR.LTDCEN := True; Set_Layer_State (Layer1, False); Set_Layer_State (Layer2, False); -- enable Dither LTDC_Periph.GCR.DEN := True; end Initialize; ----------- -- Start -- ----------- procedure Start is begin LTDC_Periph.GCR.LTDCEN := True; end Start; ---------- -- Stop -- ---------- procedure Stop is begin LTDC_Periph.GCR.LTDCEN := False; end Stop; ----------------- -- Initialized -- ----------------- function Initialized return Boolean is begin return LTDC_Periph.GCR.LTDCEN; end Initialized; ---------------- -- Layer_Init -- ---------------- procedure Layer_Init (Layer : LCD_Layer; Config : Pixel_Format; Buffer : System.Address; X, Y : Natural; W, H : Positive; Constant_Alpha : Byte := 255; BF : Blending_Factor := BF_Pixel_Alpha_X_Constant_Alpha) is L : constant Layer_Access := Get_Layer (Layer); CFBL : L1CFBLR_Register := L.LCFBLR; begin -- Horizontal start and stop = sync + Back Porch L.LWHPCR := (WHSTPOS => L1WHPCR_WHSTPOS_Field (LTDC_Periph.BPCR.AHBP) + 1 + L1WHPCR_WHSTPOS_Field (X), WHSPPOS => L1WHPCR_WHSPPOS_Field (LTDC_Periph.BPCR.AHBP) + L1WHPCR_WHSPPOS_Field (X + W), others => <>); -- Vertical start and stop L.LWVPCR := (WVSTPOS => LTDC_Periph.BPCR.AVBP + 1 + UInt11 (Y), WVSPPOS => LTDC_Periph.BPCR.AVBP + UInt11 (Y + H), others => <>); L.LPFCR.PF := Pixel_Format'Enum_Rep (Config); L.LCACR.CONSTA := Constant_Alpha; L.LDCCR := (others => 0); case BF is when BF_Constant_Alpha => L.LBFCR.BF1 := BF1_Constant_Alpha; L.LBFCR.BF2 := BF2_Constant_Alpha; when BF_Pixel_Alpha_X_Constant_Alpha => L.LBFCR.BF1 := BF1_Pixel_Alpha; L.LBFCR.BF2 := BF2_Pixel_Alpha; end case; CFBL.CFBLL := UInt13 (W * Bytes_Per_Pixel (Config)) + 3; CFBL.CFBP := UInt13 (W * Bytes_Per_Pixel (Config)); L.LCFBLR := CFBL; L.LCFBLNR.CFBLNBR := UInt11 (H); Set_Frame_Buffer (Layer, Buffer); Set_Layer_State (Layer, True); end Layer_Init; ---------------------- -- Set_Frame_Buffer -- ---------------------- procedure Set_Frame_Buffer (Layer : LCD_Layer; Addr : Frame_Buffer_Access) is function To_Word is new Ada.Unchecked_Conversion (Frame_Buffer_Access, Word); begin if Layer = Layer1 then LTDC_Periph.L1CFBAR := To_Word (Addr); else LTDC_Periph.L2CFBAR := To_Word (Addr); end if; end Set_Frame_Buffer; ---------------------- -- Get_Frame_Buffer -- ---------------------- function Get_Frame_Buffer (Layer : LCD_Layer) return Frame_Buffer_Access is L : constant Layer_Access := Get_Layer (Layer); function To_FBA is new Ada.Unchecked_Conversion (Word, Frame_Buffer_Access); begin return To_FBA (L.LCFBAR); end Get_Frame_Buffer; -------------------- -- Set_Background -- -------------------- procedure Set_Background (R, G, B : Byte) is RShift : constant Word := Shift_Left (Word (R), 16); GShift : constant Word := Shift_Left (Word (G), 8); begin LTDC_Periph.BCCR.BC := UInt24 (RShift) or UInt24 (GShift) or UInt24 (B); end Set_Background; end STM32.LTDC;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-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 STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f429i_discovery_lcd.c -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief This file includes the LTDC driver to control LCD display. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ with Ada.Interrupts.Names; with Ada.Unchecked_Conversion; with System; use System; with STM32_SVD.LTDC; use STM32_SVD.LTDC; with STM32_SVD.RCC; use STM32_SVD.RCC; package body STM32.LTDC is pragma Warnings (Off, "* is not referenced"); type LCD_Polarity is (Polarity_Active_Low, Polarity_Active_High) with Size => 1; type LCD_PC_Polarity is (Input_Pixel_Clock, Inverted_Input_Pixel_Clock) with Size => 1; pragma Warnings (On, "* is not referenced"); function To_Bool is new Ada.Unchecked_Conversion (LCD_Polarity, Boolean); function To_Bool is new Ada.Unchecked_Conversion (LCD_PC_Polarity, Boolean); -- Extracted from STM32F429x.LTDC type Layer_Type is record LCR : L1CR_Register; -- Layerx Control Register LWHPCR : L1WHPCR_Register; -- Layerx Window Horizontal Position Configuration Register LWVPCR : L1WVPCR_Register; -- Layerx Window Vertical Position Configuration Register LCKCR : L1CKCR_Register; -- Layerx Color Keying Configuration Register LPFCR : L1PFCR_Register; -- Layerx Pixel Format Configuration Register LCACR : L1CACR_Register; -- Layerx Constant Alpha Configuration Register LDCCR : L1DCCR_Register; -- Layerx Default Color Configuration Register LBFCR : L1BFCR_Register; -- Layerx Blending Factors Configuration Register Reserved_0 : Word; Reserved_1 : Word; LCFBAR : Word; -- Layerx Color Frame Buffer Address Register LCFBLR : L1CFBLR_Register; -- Layerx Color Frame Buffer Length Register LCFBLNR : L1CFBLNR_Register; -- Layerx ColorFrame Buffer Line Number Register Reserved_2 : Word; Reserved_3 : Word; Reserved_4 : Word; LCLUTWR : L1CLUTWR_Register; -- Layerx CLUT Write Register end record with Volatile; for Layer_Type use record LCR at 0 range 0 .. 31; LWHPCR at 4 range 0 .. 31; LWVPCR at 8 range 0 .. 31; LCKCR at 12 range 0 .. 31; LPFCR at 16 range 0 .. 31; LCACR at 20 range 0 .. 31; LDCCR at 24 range 0 .. 31; LBFCR at 28 range 0 .. 31; Reserved_0 at 32 range 0 .. 31; Reserved_1 at 36 range 0 .. 31; LCFBAR at 40 range 0 .. 31; LCFBLR at 44 range 0 .. 31; LCFBLNR at 48 range 0 .. 31; Reserved_2 at 52 range 0 .. 31; Reserved_3 at 56 range 0 .. 31; Reserved_4 at 60 range 0 .. 31; LCLUTWR at 64 range 0 .. 31; end record; type Layer_Access is access all Layer_Type; BF1_Constant_Alpha : constant := 2#100#; BF2_Constant_Alpha : constant := 2#101#; BF1_Pixel_Alpha : constant := 2#110#; BF2_Pixel_Alpha : constant := 2#111#; G_Layer1_Reg : aliased Layer_Type with Import, Address => LTDC_Periph.L1CR'Address; G_Layer2_Reg : aliased Layer_Type with Import, Address => LTDC_Periph.L2CR'Address; function Get_Layer (Layer : LCD_Layer) return Layer_Access; -- Retrieve the layer's registers protected Sync is -- Apply pending buffers on Vertical Sync. Caller must call Wait -- afterwards. procedure Apply_On_VSync; -- Wait for an interrupt. entry Wait; procedure Interrupt; pragma Attach_Handler (Interrupt, Ada.Interrupts.Names.LCD_TFT_Interrupt); private Not_Pending : Boolean := True; end Sync; ---------- -- Sync -- ---------- protected body Sync is ---------- -- Wait -- ---------- entry Wait when Not_Pending is begin null; end Wait; -------------------- -- Apply_On_VSync -- -------------------- procedure Apply_On_VSync is begin Not_Pending := False; -- Enable the Register Refresh interrupt LTDC_Periph.IER.RRIE := True; -- And tell the LTDC to apply the layer registers on refresh LTDC_Periph.SRCR.VBR := True; end Apply_On_VSync; --------------- -- Interrupt -- --------------- procedure Interrupt is begin if LTDC_Periph.ISR.RRIF then LTDC_Periph.IER.RRIE := False; LTDC_Periph.ICR.CRRIF := True; Not_Pending := True; end if; end Interrupt; end Sync; --------------- -- Get_Layer -- --------------- function Get_Layer (Layer : LCD_Layer) return Layer_Access is begin if Layer = Layer1 then return G_Layer1_Reg'Access; else return G_Layer2_Reg'Access; end if; end Get_Layer; ------------------- -- Reload_Config -- ------------------- procedure Reload_Config (Immediate : Boolean := False) is begin if Immediate then LTDC_Periph.SRCR.IMR := True; loop exit when not LTDC_Periph.SRCR.IMR; end loop; else Sync.Apply_On_VSync; Sync.Wait; end if; end Reload_Config; --------------------- -- Set_Layer_State -- --------------------- procedure Set_Layer_State (Layer : LCD_Layer; Enabled : Boolean) is L : constant Layer_Access := Get_Layer (Layer); begin if L.LCR.LEN /= Enabled then L.LCR.LEN := Enabled; Reload_Config (Immediate => True); end if; end Set_Layer_State; ---------------- -- Initialize -- ---------------- procedure Initialize (Width : Positive; Height : Positive; H_Sync : Natural; H_Back_Porch : Natural; H_Front_Porch : Natural; V_Sync : Natural; V_Back_Porch : Natural; V_Front_Porch : Natural; PLLSAI_N : UInt9; PLLSAI_R : UInt3; DivR : Natural) is DivR_Val : PLLSAI_DivR; begin if Initialized then return; end if; if DivR = 2 then DivR_Val := PLLSAI_DIV2; elsif DivR = 4 then DivR_Val := PLLSAI_DIV4; elsif DivR = 8 then DivR_Val := PLLSAI_DIV8; elsif DivR = 16 then DivR_Val := PLLSAI_DIV16; else raise Constraint_Error with "Invalid DivR value: 2, 4, 8, 16 allowed"; end if; Disable_PLLSAI; RCC_Periph.APB2ENR.LTDCEN := True; LTDC_Periph.GCR.VSPOL := To_Bool (Polarity_Active_Low); LTDC_Periph.GCR.HSPOL := To_Bool (Polarity_Active_Low); LTDC_Periph.GCR.DEPOL := To_Bool (Polarity_Active_Low); LTDC_Periph.GCR.PCPOL := To_Bool (Inverted_Input_Pixel_Clock); Set_PLLSAI_Factors (LCD => PLLSAI_R, VCO => PLLSAI_N, DivR => DivR_Val); Enable_PLLSAI; -- Synchronization size LTDC_Periph.SSCR := (HSW => SSCR_HSW_Field (H_Sync - 1), VSH => SSCR_VSH_Field (V_Sync - 1), others => <>); -- Accumulated Back Porch LTDC_Periph.BPCR := (AHBP => BPCR_AHBP_Field (H_Sync + H_Back_Porch - 1), AVBP => BPCR_AVBP_Field (V_Sync + V_Back_Porch - 1), others => <>); -- Accumulated Active Width/Height LTDC_Periph.AWCR := (AAW => AWCR_AAW_Field (H_Sync + H_Back_Porch + Width - 1), AAH => AWCR_AAH_Field (V_Sync + V_Back_Porch + Height - 1), others => <>); -- VTotal Width/Height LTDC_Periph.TWCR := (TOTALW => TWCR_TOTALW_Field (H_Sync + H_Back_Porch + Width + H_Front_Porch - 1), TOTALH => TWCR_TOTALH_Field (V_Sync + V_Back_Porch + Height + V_Front_Porch - 1), others => <>); -- Background color to black LTDC_Periph.BCCR.BC := 0; LTDC_Periph.GCR.LTDCEN := True; end Initialize; ----------- -- Start -- ----------- procedure Start is begin LTDC_Periph.GCR.LTDCEN := True; end Start; ---------- -- Stop -- ---------- procedure Stop is begin LTDC_Periph.GCR.LTDCEN := False; end Stop; ----------------- -- Initialized -- ----------------- function Initialized return Boolean is begin return LTDC_Periph.GCR.LTDCEN; end Initialized; ---------------- -- Layer_Init -- ---------------- procedure Layer_Init (Layer : LCD_Layer; Config : Pixel_Format; Buffer : System.Address; X, Y : Natural; W, H : Positive; Constant_Alpha : Byte := 255; BF : Blending_Factor := BF_Pixel_Alpha_X_Constant_Alpha) is L : constant Layer_Access := Get_Layer (Layer); CFBL : L1CFBLR_Register := L.LCFBLR; begin -- Horizontal start and stop = sync + Back Porch L.LWHPCR := (WHSTPOS => L1WHPCR_WHSTPOS_Field (LTDC_Periph.BPCR.AHBP) + 1 + L1WHPCR_WHSTPOS_Field (X), WHSPPOS => L1WHPCR_WHSPPOS_Field (LTDC_Periph.BPCR.AHBP) + L1WHPCR_WHSPPOS_Field (X + W), others => <>); -- Vertical start and stop L.LWVPCR := (WVSTPOS => LTDC_Periph.BPCR.AVBP + 1 + UInt11 (Y), WVSPPOS => LTDC_Periph.BPCR.AVBP + UInt11 (Y + H), others => <>); L.LPFCR.PF := Pixel_Format'Enum_Rep (Config); L.LCACR.CONSTA := Constant_Alpha; L.LDCCR := (others => 0); case BF is when BF_Constant_Alpha => L.LBFCR.BF1 := BF1_Constant_Alpha; L.LBFCR.BF2 := BF2_Constant_Alpha; when BF_Pixel_Alpha_X_Constant_Alpha => L.LBFCR.BF1 := BF1_Pixel_Alpha; L.LBFCR.BF2 := BF2_Pixel_Alpha; end case; CFBL.CFBLL := UInt13 (W * Bytes_Per_Pixel (Config)) + 3; CFBL.CFBP := UInt13 (W * Bytes_Per_Pixel (Config)); L.LCFBLR := CFBL; L.LCFBLNR.CFBLNBR := UInt11 (H); Set_Frame_Buffer (Layer, Buffer); L.LCR.LEN := True; Reload_Config (True); end Layer_Init; ---------------------- -- Set_Frame_Buffer -- ---------------------- procedure Set_Frame_Buffer (Layer : LCD_Layer; Addr : Frame_Buffer_Access) is function To_Word is new Ada.Unchecked_Conversion (Frame_Buffer_Access, Word); begin if Layer = Layer1 then LTDC_Periph.L1CFBAR := To_Word (Addr); else LTDC_Periph.L2CFBAR := To_Word (Addr); end if; end Set_Frame_Buffer; ---------------------- -- Get_Frame_Buffer -- ---------------------- function Get_Frame_Buffer (Layer : LCD_Layer) return Frame_Buffer_Access is L : constant Layer_Access := Get_Layer (Layer); function To_FBA is new Ada.Unchecked_Conversion (Word, Frame_Buffer_Access); begin return To_FBA (L.LCFBAR); end Get_Frame_Buffer; -------------------- -- Set_Background -- -------------------- procedure Set_Background (R, G, B : Byte) is RShift : constant Word := Shift_Left (Word (R), 16); GShift : constant Word := Shift_Left (Word (G), 8); begin LTDC_Periph.BCCR.BC := UInt24 (RShift) or UInt24 (GShift) or UInt24 (B); end Set_Background; end STM32.LTDC;
Fix the initialization of the LTDC, not working properly on the F7.
Fix the initialization of the LTDC, not working properly on the F7.
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library
7327d49bff4ebfc8f02bfb14a8e0ba0d38e68b3c
regtests/util-streams-texts-tests.adb
regtests/util-streams-texts-tests.adb
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; package body Util.Streams.Texts.Tests is use Util.Tests; 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'Unchecked_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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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'Unchecked_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;
Remove unused use Util.Tests clause
Remove unused use Util.Tests clause
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8bbed78fb8cdc59042f02502729ce008cd73aa2a
awa/regtests/awa-users-tests.adb
awa/regtests/awa-users-tests.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- 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 Util.Test_Caller; with ASF.Tests; with AWA.Users.Models; with AWA.Tests.Helpers.Users; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Users.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register", "1"); Request.Set_Parameter ("register-button", "1"); Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); end; -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]"); Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "[email protected]"; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirect after lost password"); -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/reset-password.html", "reset-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Post the reset password Request.Set_Parameter ("password", "asd"); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Test_Reset_Password_User; end AWA.Users.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Tests; with AWA.Users.Models; with AWA.Tests.Helpers.Users; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Users.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register", "1"); Request.Set_Parameter ("register-button", "1"); Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); end; -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]"); Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "[email protected]"; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirect after lost password"); -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", "asd"); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Test_Reset_Password_User; end AWA.Users.Tests;
Update the unit test according to the lost password recovery process
Update the unit test according to the lost password recovery process
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
c2a9375e073ced390b6aa026d2db35ef281903bd
regtests/babel-streams-tests.adb
regtests/babel-streams-tests.adb
----------------------------------------------------------------------- -- babel-streams-tests - Unit tests for babel streams -- 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 Util.Test_Caller; with Babel.Files.Buffers; with Babel.Streams.Cached; with Babel.Streams.Files; with Babel.Streams.XZ; package body Babel.Streams.Tests is package Caller is new Util.Test_Caller (Test, "Streams"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Babel.Streams.Read", Test_Stream_Composition'Access); end Add_Tests; -- ------------------------------ -- Stream copy, compression and decompression test. -- Create a compressed version of the source file and then decompress the result. -- The source file is then compared to the decompressed result and must match. -- ------------------------------ procedure Do_Copy (T : in out Test; Pool : in out Babel.Files.Buffers.Buffer_Pool; Src : in String) is use type Babel.Files.Buffers.Buffer_Access; Src_Path : constant String := Util.Tests.Get_Path (Src); Dst_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/" & Src & ".xz"); Tst_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/" & Src); Buffer : Babel.Files.Buffers.Buffer_Access; begin -- Compress the 'configure' file into 'configure.xz' through the file+cache+xz+file streams. declare In_File : aliased Babel.Streams.Files.Stream_Type; Out_File : aliased Babel.Streams.Files.Stream_Type; Cache : aliased Babel.Streams.Cached.Stream_Type; Lz : aliased Babel.Streams.XZ.Stream_Type; begin Pool.Get_Buffer (Buffer); In_File.Open (Src_Path, Buffer); Cache.Load (In_File, Pool); Pool.Get_Buffer (Buffer); Out_File.Create (Dst_Path, 8#644#); Lz.Set_Buffer (Buffer); Lz.Set_Output (Out_File'Unchecked_Access); loop Cache.Read (Buffer); exit when Buffer = null; Lz.Write (Buffer); end loop; Lz.Flush; Lz.Close; end; -- Decompress through file+cache+xz+file declare In_File : aliased Babel.Streams.Files.Stream_Type; Out_File : aliased Babel.Streams.Files.Stream_Type; Cache : aliased Babel.Streams.Cached.Stream_Type; Lz : aliased Babel.Streams.XZ.Stream_Type; begin Pool.Get_Buffer (Buffer); In_File.Open (Dst_Path, Buffer); Cache.Load (In_File, Pool); -- Setup decompression. Pool.Get_Buffer (Buffer); Lz.Set_Input (Cache'Unchecked_Access); Lz.Set_Buffer (Buffer); Out_File.Create (Tst_Path, 8#644#); loop Lz.Read (Buffer); exit when Buffer = null; Out_File.Write (Buffer); end loop; Out_File.Close; end; Util.Tests.Assert_Equal_Files (T, Src_Path, Tst_Path, "Composition stream failed for: " & Src); end Do_Copy; -- ------------------------------ -- Test the Find function resolving some existing user. -- ------------------------------ procedure Test_Stream_Composition (T : in out Test) is Pool : aliased Babel.Files.Buffers.Buffer_Pool; begin Babel.Files.Buffers.Create_Pool (Into => Pool, Size => 1_000, Count => 1000); Do_Copy (T, Pool, "configure"); Do_Copy (T, Pool, "babel.gpr"); Do_Copy (T, Pool, "configure.in"); Do_Copy (T, Pool, "config.guess"); Do_Copy (T, Pool, "Makefile.in"); end Test_Stream_Composition; end Babel.Streams.Tests;
----------------------------------------------------------------------- -- babel-streams-tests - Unit tests for babel streams -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Babel.Files.Buffers; with Babel.Streams.Cached; with Babel.Streams.Files; with Babel.Streams.XZ; package body Babel.Streams.Tests is package Caller is new Util.Test_Caller (Test, "Streams"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Babel.Streams.Read", Test_Stream_Composition'Access); end Add_Tests; -- ------------------------------ -- Stream copy, compression and decompression test. -- Create a compressed version of the source file and then decompress the result. -- The source file is then compared to the decompressed result and must match. -- ------------------------------ procedure Do_Copy (T : in out Test; Pool : in out Babel.Files.Buffers.Buffer_Pool; Src : in String) is use type Babel.Files.Buffers.Buffer_Access; Src_Path : constant String := Util.Tests.Get_Path (Src); Dst_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/" & Src & ".xz"); Tst_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/" & Src); Buffer : Babel.Files.Buffers.Buffer_Access; begin -- Compress the 'configure' file into 'configure.xz' through the file+cache+xz+file streams. declare In_File : aliased Babel.Streams.Files.Stream_Type; Out_File : aliased Babel.Streams.Files.Stream_Type; Cache : aliased Babel.Streams.Cached.Stream_Type; Lz : aliased Babel.Streams.XZ.Stream_Type; begin Pool.Get_Buffer (Buffer); In_File.Open (Src_Path, Buffer); Cache.Load (In_File, Pool); Pool.Get_Buffer (Buffer); Out_File.Create (Dst_Path, 8#644#); Lz.Set_Buffer (Buffer); Lz.Set_Output (Out_File'Unchecked_Access); loop Cache.Read (Buffer); exit when Buffer = null; Lz.Write (Buffer); end loop; Lz.Flush; Lz.Close; lz.Finalize; Cache.Finalize; In_File.Finalize; Out_File.Finalize; end; -- Decompress through file+cache+xz+file declare In_File : aliased Babel.Streams.Files.Stream_Type; Out_File : aliased Babel.Streams.Files.Stream_Type; Cache : aliased Babel.Streams.Cached.Stream_Type; Lz : aliased Babel.Streams.XZ.Stream_Type; begin Pool.Get_Buffer (Buffer); In_File.Open (Dst_Path, Buffer); Cache.Load (In_File, Pool); -- Setup decompression. Pool.Get_Buffer (Buffer); Lz.Set_Input (Cache'Unchecked_Access); Lz.Set_Buffer (Buffer); Out_File.Create (Tst_Path, 8#644#); loop Lz.Read (Buffer); exit when Buffer = null; Out_File.Write (Buffer); end loop; Out_File.Close; lz.Finalize; Cache.Finalize; In_File.Finalize; Out_File.Finalize; end; Util.Tests.Assert_Equal_Files (T, Src_Path, Tst_Path, "Composition stream failed for: " & Src); end Do_Copy; -- ------------------------------ -- Test the Find function resolving some existing user. -- ------------------------------ procedure Test_Stream_Composition (T : in out Test) is Pool : aliased Babel.Files.Buffers.Buffer_Pool; begin Pool.Create_Pool (Size => 1_000, Count => 1000); Do_Copy (T, Pool, "configure"); Do_Copy (T, Pool, "babel.gpr"); Do_Copy (T, Pool, "configure.in"); Do_Copy (T, Pool, "config.guess"); Do_Copy (T, Pool, "Makefile.in"); end Test_Stream_Composition; end Babel.Streams.Tests;
Update the stream unit tests
Update the stream unit tests
Ada
apache-2.0
stcarrez/babel
4a5a44aff83a4abd237d9fc194b327a5d4e5f8c5
src/ado-configs.ads
src/ado-configs.ads
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Properties; package ADO.Configs is -- Configuration property to control the search paths to load XML queries. QUERY_PATHS_CONFIG : constant String := "ado.queries.paths"; -- Configuration property to control whether all the program XML queries must be -- loaded when the database configuration is setup. QUERY_LOAD_CONFIG : constant String := "ado.queries.load"; -- Raised when the connection URI is invalid. Connection_Error : exception; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Config : in out Configuration; URI : in String); -- Get the connection URI that describes the database connection string. -- The returned string may contain connection authentication information. function Get_URI (Config : in Configuration) return String; -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. function Get_Log_URI (Config : in Configuration) return String; -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Config : in Configuration; Name : in String) return String; -- Set the server hostname. procedure Set_Server (Config : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Config : in Configuration) return String; -- Set the server port. procedure Set_Port (Config : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Config : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Config : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Config : in Configuration) return String; -- Get the database driver name. function Get_Driver (Config : in Configuration) return String; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)); private use Ada.Strings.Unbounded; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Driver : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; end record; end ADO.Configs;
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Properties; package ADO.Configs is -- Configuration property to control the search paths to load XML queries. QUERY_PATHS_CONFIG : constant String := "ado.queries.paths"; -- Configuration property to control whether all the program XML queries must be -- loaded when the database configuration is setup. QUERY_LOAD_CONFIG : constant String := "ado.queries.load"; -- Configuration property to enable or disable the dynamic load of database driver. DYNAMIC_DRIVER_LOAD : constant String := "ado.drivers.load"; -- Raised when the connection URI is invalid. Connection_Error : exception; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Config : in out Configuration; URI : in String); -- Get the connection URI that describes the database connection string. -- The returned string may contain connection authentication information. function Get_URI (Config : in Configuration) return String; -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. function Get_Log_URI (Config : in Configuration) return String; -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Config : in Configuration; Name : in String) return String; -- Set the server hostname. procedure Set_Server (Config : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Config : in Configuration) return String; -- Set the server port. procedure Set_Port (Config : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Config : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Config : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Config : in Configuration) return String; -- Get the database driver name. function Get_Driver (Config : in Configuration) return String; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)); private use Ada.Strings.Unbounded; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Driver : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; end record; end ADO.Configs;
Declare DYNAMIC_DRIVER_LOAD configuration parameter
Declare DYNAMIC_DRIVER_LOAD configuration parameter
Ada
apache-2.0
stcarrez/ada-ado
fadcb7cd8b07273d3a5081e0593682b072588e66
tests/simple_site.adb
tests/simple_site.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Command_Line; with Ada.Text_IO; with AWS.Config; with AWS.Server; with Common; with Natools.Web.Sites; with Syslog.Guess.App_Name; with Syslog.Guess.Hostname; with Syslog.Transport.Send_Task; with Syslog.Transport.UDP; procedure Simple_Site is WS : AWS.Server.HTTP; Debug : constant Boolean := Ada.Command_Line.Argument_Count >= 2; begin if Debug then Natools.Web.Log := Common.Text_IO_Log'Access; else Syslog.Guess.App_Name; Syslog.Guess.Hostname; Syslog.Transport.UDP.Connect ("127.0.0.1"); Syslog.Transport.Send_Task.Set_Backend (Syslog.Transport.UDP.Transport); Syslog.Set_Transport (Syslog.Transport.Send_Task.Transport); Syslog.Set_Default_Facility (Syslog.Facilities.Daemon); Natools.Web.Log := Common.Syslog_Log'Access; end if; if Ada.Command_Line.Argument_Count >= 1 then Natools.Web.Sites.Reset (Common.Site'Access, Ada.Command_Line.Argument (1)); else Natools.Web.Sites.Reset (Common.Site'Access, "site.sx"); end if; AWS.Server.Start (WS, Common.Respond'Access, AWS.Config.Get_Current); if Debug then Ada.Text_IO.Put_Line ("Websever started"); AWS.Server.Wait (AWS.Server.Q_Key_Pressed); else AWS.Server.Wait; end if; AWS.Server.Shutdown (WS); end Simple_Site;
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Command_Line; with Ada.Directories; with Ada.Text_IO; with AWS.Config; with AWS.Server; with Common; with Natools.Web.Sites; with Syslog.Guess.App_Name; with Syslog.Guess.Hostname; with Syslog.Transport.Send_Task; with Syslog.Transport.UDP; procedure Simple_Site is WS : AWS.Server.HTTP; Debug : constant Boolean := Ada.Command_Line.Argument_Count >= 2; begin if Debug then Natools.Web.Log := Common.Text_IO_Log'Access; else Syslog.Guess.App_Name; Syslog.Guess.Hostname; Syslog.Transport.UDP.Connect ("127.0.0.1"); Syslog.Transport.Send_Task.Set_Backend (Syslog.Transport.UDP.Transport); Syslog.Set_Transport (Syslog.Transport.Send_Task.Transport); Syslog.Set_Default_Facility (Syslog.Facilities.Daemon); Natools.Web.Log := Common.Syslog_Log'Access; end if; if Ada.Command_Line.Argument_Count >= 1 then Natools.Web.Sites.Reset (Common.Site'Access, Ada.Command_Line.Argument (1)); else Natools.Web.Sites.Reset (Common.Site'Access, "site.sx"); end if; AWS.Server.Start (WS, Common.Respond'Access, AWS.Config.Get_Current); if not Debug then AWS.Server.Wait; elsif Ada.Directories.Exists (Ada.Command_Line.Argument (2)) then Ada.Text_IO.Put_Line ("Websever started, waiting for removal of " & Ada.Command_Line.Argument (2)); loop delay 1.0; exit when not Ada.Directories.Exists (Ada.Command_Line.Argument (2)); end loop; else Ada.Text_IO.Put_Line ("Websever started, waiting for Q press"); AWS.Server.Wait (AWS.Server.Q_Key_Pressed); end if; AWS.Server.Shutdown (WS); end Simple_Site;
add an option to drive program termination through file deletion
simple_site: add an option to drive program termination through file deletion
Ada
isc
faelys/natools-web,faelys/natools-web
cb71ea4712e5d29939f4e8ccd4d381d485c9ba94
mat/src/mat-readers.ads
mat/src/mat-readers.ads
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with System; with Util.Streams.Buffered; with MAT.Types; with MAT.Events; with MAT.Events.Targets; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access all Buffer_Type; type Message_Type is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; subtype Message is Message_Type; ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with private; type Manager is access all Manager_Base'Class; -- Initialize the manager instance. overriding procedure Initialize (Manager : in out Manager_Base); -- Register the reader to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); -- Read a message from the stream. procedure Read_Message (Client : in out Manager_Base; Msg : in out Message) is abstract; -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Manager_Base; Msg : in out Message); -- Get the target events. function Get_Target_Events (Client : in Manager_Base) return MAT.Events.Targets.Target_Events_Access; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (List : in out Reader_List_Type; Reader : in out Manager_Base'Class) is abstract; private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Buffer : Util.Streams.Buffered.Buffer_Access; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; end record; -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message); -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with System; with Util.Streams.Buffered; with MAT.Types; with MAT.Events; with MAT.Events.Targets; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access all Buffer_Type; type Message_Type is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; subtype Message is Message_Type; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (List : in out Reader_List_Type; Reader : in out Manager_Base'Class) is abstract; private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Buffer : Util.Streams.Buffered.Buffer_Access; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; end record; -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message); -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
Remove the Manager_Base type (now replaced by MAT.Events.Probes)
Remove the Manager_Base type (now replaced by MAT.Events.Probes)
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8b7ea3dc010ef5a7f56d76310fce532131535b23
awa/regtests/awa-users-tests.adb
awa/regtests/awa-users-tests.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- 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 Util.Test_Caller; with ASF.Tests; with AWA.Users.Models; with AWA.Tests.Helpers.Users; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Users.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register", "1"); Request.Set_Parameter ("register-button", "1"); Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); end; -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]"); Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "[email protected]"; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/reset-password.html", "reset-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Post the reset password Request.Set_Parameter ("password", "asd"); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Test_Reset_Password_User; end AWA.Users.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Tests; with AWA.Users.Models; with AWA.Tests.Helpers.Users; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Users.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register", "1"); Request.Set_Parameter ("register-button", "1"); Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); end; -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]"); Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "[email protected]"; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirect after lost password"); -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/reset-password.html", "reset-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Post the reset password Request.Set_Parameter ("password", "asd"); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Test_Reset_Password_User; end AWA.Users.Tests;
Fix unit test: after the lost password form submission, we are redirected to the login page
Fix unit test: after the lost password form submission, we are redirected to the login page
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1a218ee68dc6f24cb4a4c4e3214e08b9199f269d
awa/src/awa-permissions.ads
awa/src/awa-permissions.ads
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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 not argument and some others need a context -- such as some entity identifier to perform the check. -- -- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, -- Entity => Blog_Id); -- -- === Configuring a permission === -- The *AWA.Permissions* framework supports a simple permission model -- The application configuration file must provide some information to help in checking the -- permission. The permission name is referenced by the `name` XML entity. The `entity-type` -- refers to the database entity (ie, the table) that the permission concerns. -- The `sql` XML entity represents the SQL statement that must be used to verify the permission. -- -- <entity-permission> -- <name>blog-create-post</name> -- <entity-type>blog</entity-type> -- <description>Permission to create a new post.</description> -- <sql> -- SELECT acl.id FROM acl -- WHERE acl.entity_type = :entity_type -- AND acl.user_id = :user_id -- AND acl.entity_id = :entity_id -- </sql> -- </entity-permission> -- -- === Adding a permission === -- Adding a permission means to create an `ACL` database record that links a given database -- entity to the user. This is done easily with the `Add_Permission` procedure: -- -- AWA.Permissions.Services.Add_Permission (Session => DB, -- User => User, -- Entity => Blog); -- -- == Data Model == -- @include Permission.hbm.xml -- -- == Queries == -- @include permissions.xml -- package AWA.Permissions is NAME : constant String := "Entity-Policy"; -- Exception raised by the <b>Check</b> procedure if the user does not have -- the permission. NO_PERMISSION : exception; -- 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: -- -- 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;
Fix typo in documentation
Fix typo in documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa