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
|
---|---|---|---|---|---|---|---|---|---|
fbacb3a1d41dc887f6a3f5fcb77c6c3a95451af5
|
src/os-linux/util-processes-os.adb
|
src/os-linux/util-processes-os.adb
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Processes.Os is
use Util.Systems.Os;
use type Interfaces.C.size_t;
type Pipe_Type is array (0 .. 1) of File_Type;
procedure Close (Pipes : in out Pipe_Type);
-- ------------------------------
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
-- ------------------------------
function Create_Stream (File : in File_Type)
return Util.Streams.Raw.Raw_Stream_Access is
Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream;
Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC);
pragma Unreferenced (Status);
begin
Stream.Initialize (File);
return Stream;
end Create_Stream;
-- ------------------------------
-- Wait for the process to exit.
-- ------------------------------
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is
pragma Unreferenced (Sys, Timeout);
use type Util.Streams.Output_Stream_Access;
Result : Integer;
Wpid : Integer;
begin
-- Close the input stream pipe if there is one.
if Proc.Input /= null then
Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close;
end if;
Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0);
if Wpid = Integer (Proc.Pid) then
Proc.Exit_Value := Result / 256;
if Result mod 256 /= 0 then
Proc.Exit_Value := (Result mod 256) * 1000;
end if;
end if;
end Wait;
-- ------------------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- ------------------------------
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is
pragma Unreferenced (Sys);
Result : Integer;
begin
Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal));
end Stop;
-- ------------------------------
-- Close both ends of the pipe (used to cleanup in case or error).
-- ------------------------------
procedure Close (Pipes : in out Pipe_Type) is
Result : Integer;
pragma Unreferenced (Result);
begin
if Pipes (0) /= NO_FILE then
Result := Sys_Close (Pipes (0));
Pipes (0) := NO_FILE;
end if;
if Pipes (1) /= NO_FILE then
Result := Sys_Close (Pipes (1));
Pipes (1) := NO_FILE;
end if;
end Close;
-- ------------------------------
-- Spawn a new process.
-- ------------------------------
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
use Util.Streams.Raw;
use Interfaces.C.Strings;
use type Interfaces.C.int;
procedure Cleanup;
-- Suppress all checks to make sure the child process will not raise any exception.
pragma Suppress (All_Checks);
Result : Integer;
pragma Unreferenced (Result);
Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE);
Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE);
Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE);
procedure Cleanup is
begin
Close (Stdin_Pipes);
Close (Stdout_Pipes);
Close (Stderr_Pipes);
end Cleanup;
begin
-- Since checks are disabled, verify by hand that the argv table is correct.
if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then
raise Program_Error with "Invalid process argument list";
end if;
-- Setup the pipes.
if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then
if Sys_Pipe (Stdout_Pipes'Address) /= 0 then
raise Process_Error with "Cannot create stdout pipe";
end if;
end if;
if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then
if Sys_Pipe (Stdin_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stdin pipe";
end if;
end if;
if Mode = READ_ERROR then
if Sys_Pipe (Stderr_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stderr pipe";
end if;
end if;
-- Create the new process by using vfork instead of fork. The parent process is blocked
-- until the child executes the exec or exits. The child process uses the same stack
-- as the parent.
Proc.Pid := Sys_VFork;
if Proc.Pid = 0 then
-- Do not use any Ada type while in the child process.
if Mode = READ_ALL or Mode = READ_WRITE_ALL then
Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO);
end if;
if Stderr_Pipes (1) /= NO_FILE then
if Stderr_Pipes (1) /= STDERR_FILENO then
Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO);
Result := Sys_Close (Stderr_Pipes (1));
end if;
Result := Sys_Close (Stderr_Pipes (0));
elsif Sys.Err_File /= Null_Ptr then
-- Redirect the process error to a file.
declare
Fd : File_Type;
begin
if Sys.Err_Append then
Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#);
else
Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#);
end if;
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end;
end if;
if Stdout_Pipes (1) /= NO_FILE then
if Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO);
Result := Sys_Close (Stdout_Pipes (1));
end if;
Result := Sys_Close (Stdout_Pipes (0));
elsif Sys.Out_File /= Null_Ptr then
-- Redirect the process output to a file.
declare
Fd : File_Type;
begin
if Sys.Out_Append then
Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#);
else
Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#);
end if;
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end;
end if;
if Stdin_Pipes (0) /= NO_FILE then
if Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO);
Result := Sys_Close (Stdin_Pipes (0));
end if;
Result := Sys_Close (Stdin_Pipes (1));
elsif Sys.In_File /= Null_Ptr then
-- Redirect the process input to a file.
declare
Fd : File_Type;
begin
Fd := Sys_Open (Sys.Out_File, O_RDONLY, 8#644#);
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDIN_FILENO);
Result := Sys_Close (Fd);
end;
end if;
Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all);
Sys_Exit (255);
end if;
-- Process creation failed, cleanup and raise an exception.
if Proc.Pid < 0 then
Cleanup;
raise Process_Error with "Cannot create process";
end if;
if Stdin_Pipes (1) /= NO_FILE then
Result := Sys_Close (Stdin_Pipes (0));
Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access;
end if;
if Stdout_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stdout_Pipes (1));
Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access;
end if;
if Stderr_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stderr_Pipes (1));
Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access;
end if;
end Spawn;
procedure Free is
new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array);
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
begin
if Sys.Argv = null then
Sys.Argv := new Ptr_Array (0 .. 10);
elsif Sys.Argc = Sys.Argv'Last - 1 then
declare
N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32);
begin
N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc);
Free (Sys.Argv);
Sys.Argv := N;
end;
end if;
Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg);
Sys.Argc := Sys.Argc + 1;
Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr;
end Append_Argument;
-- ------------------------------
-- Set the process input, output and error streams to redirect and use specified files.
-- ------------------------------
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean) is
begin
if Input'Length > 0 then
Sys.In_File := Interfaces.C.Strings.New_String (Input);
end if;
if Output'Length > 0 then
Sys.Out_File := Interfaces.C.Strings.New_String (Output);
Sys.Out_Append := Append_Output;
end if;
if Error'Length > 0 then
Sys.Err_File := Interfaces.C.Strings.New_String (Error);
Sys.Err_Append := Append_Error;
end if;
end Set_Streams;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
begin
if Sys.Argv /= null then
for I in Sys.Argv'Range loop
Interfaces.C.Strings.Free (Sys.Argv (I));
end loop;
Free (Sys.Argv);
end if;
Interfaces.C.Strings.Free (Sys.In_File);
Interfaces.C.Strings.Free (Sys.Out_File);
Interfaces.C.Strings.Free (Sys.Err_File);
end Finalize;
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Processes.Os is
use Util.Systems.Os;
use type Interfaces.C.size_t;
type Pipe_Type is array (0 .. 1) of File_Type;
procedure Close (Pipes : in out Pipe_Type);
-- ------------------------------
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
-- ------------------------------
function Create_Stream (File : in File_Type)
return Util.Streams.Raw.Raw_Stream_Access is
Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream;
Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC);
pragma Unreferenced (Status);
begin
Stream.Initialize (File);
return Stream;
end Create_Stream;
-- ------------------------------
-- Wait for the process to exit.
-- ------------------------------
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is
pragma Unreferenced (Sys, Timeout);
use type Util.Streams.Output_Stream_Access;
Result : Integer;
Wpid : Integer;
begin
-- Close the input stream pipe if there is one.
if Proc.Input /= null then
Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close;
end if;
Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0);
if Wpid = Integer (Proc.Pid) then
Proc.Exit_Value := Result / 256;
if Result mod 256 /= 0 then
Proc.Exit_Value := (Result mod 256) * 1000;
end if;
end if;
end Wait;
-- ------------------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- ------------------------------
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is
pragma Unreferenced (Sys);
Result : Integer;
pragma Unreferenced (Result);
begin
Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal));
end Stop;
-- ------------------------------
-- Close both ends of the pipe (used to cleanup in case or error).
-- ------------------------------
procedure Close (Pipes : in out Pipe_Type) is
Result : Integer;
pragma Unreferenced (Result);
begin
if Pipes (0) /= NO_FILE then
Result := Sys_Close (Pipes (0));
Pipes (0) := NO_FILE;
end if;
if Pipes (1) /= NO_FILE then
Result := Sys_Close (Pipes (1));
Pipes (1) := NO_FILE;
end if;
end Close;
-- ------------------------------
-- Spawn a new process.
-- ------------------------------
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
use Util.Streams.Raw;
use Interfaces.C.Strings;
use type Interfaces.C.int;
procedure Cleanup;
-- Suppress all checks to make sure the child process will not raise any exception.
pragma Suppress (All_Checks);
Result : Integer;
pragma Unreferenced (Result);
Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE);
Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE);
Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE);
procedure Cleanup is
begin
Close (Stdin_Pipes);
Close (Stdout_Pipes);
Close (Stderr_Pipes);
end Cleanup;
begin
-- Since checks are disabled, verify by hand that the argv table is correct.
if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then
raise Program_Error with "Invalid process argument list";
end if;
-- Setup the pipes.
if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then
if Sys_Pipe (Stdout_Pipes'Address) /= 0 then
raise Process_Error with "Cannot create stdout pipe";
end if;
end if;
if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then
if Sys_Pipe (Stdin_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stdin pipe";
end if;
end if;
if Mode = READ_ERROR then
if Sys_Pipe (Stderr_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stderr pipe";
end if;
end if;
-- Create the new process by using vfork instead of fork. The parent process is blocked
-- until the child executes the exec or exits. The child process uses the same stack
-- as the parent.
Proc.Pid := Sys_VFork;
if Proc.Pid = 0 then
-- Do not use any Ada type while in the child process.
if Mode = READ_ALL or Mode = READ_WRITE_ALL then
Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO);
end if;
if Stderr_Pipes (1) /= NO_FILE then
if Stderr_Pipes (1) /= STDERR_FILENO then
Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO);
Result := Sys_Close (Stderr_Pipes (1));
end if;
Result := Sys_Close (Stderr_Pipes (0));
elsif Sys.Err_File /= Null_Ptr then
-- Redirect the process error to a file.
declare
Fd : File_Type;
begin
if Sys.Err_Append then
Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#);
else
Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#);
end if;
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end;
end if;
if Stdout_Pipes (1) /= NO_FILE then
if Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO);
Result := Sys_Close (Stdout_Pipes (1));
end if;
Result := Sys_Close (Stdout_Pipes (0));
elsif Sys.Out_File /= Null_Ptr then
-- Redirect the process output to a file.
declare
Fd : File_Type;
begin
if Sys.Out_Append then
Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#);
else
Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#);
end if;
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end;
end if;
if Stdin_Pipes (0) /= NO_FILE then
if Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO);
Result := Sys_Close (Stdin_Pipes (0));
end if;
Result := Sys_Close (Stdin_Pipes (1));
elsif Sys.In_File /= Null_Ptr then
-- Redirect the process input to a file.
declare
Fd : File_Type;
begin
Fd := Sys_Open (Sys.Out_File, O_RDONLY, 8#644#);
if Fd < 0 then
Sys_Exit (254);
end if;
Result := Sys_Dup2 (Fd, STDIN_FILENO);
Result := Sys_Close (Fd);
end;
end if;
Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all);
Sys_Exit (255);
end if;
-- Process creation failed, cleanup and raise an exception.
if Proc.Pid < 0 then
Cleanup;
raise Process_Error with "Cannot create process";
end if;
if Stdin_Pipes (1) /= NO_FILE then
Result := Sys_Close (Stdin_Pipes (0));
Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access;
end if;
if Stdout_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stdout_Pipes (1));
Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access;
end if;
if Stderr_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stderr_Pipes (1));
Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access;
end if;
end Spawn;
procedure Free is
new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array);
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
begin
if Sys.Argv = null then
Sys.Argv := new Ptr_Array (0 .. 10);
elsif Sys.Argc = Sys.Argv'Last - 1 then
declare
N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32);
begin
N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc);
Free (Sys.Argv);
Sys.Argv := N;
end;
end if;
Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg);
Sys.Argc := Sys.Argc + 1;
Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr;
end Append_Argument;
-- ------------------------------
-- Set the process input, output and error streams to redirect and use specified files.
-- ------------------------------
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean) is
begin
if Input'Length > 0 then
Sys.In_File := Interfaces.C.Strings.New_String (Input);
end if;
if Output'Length > 0 then
Sys.Out_File := Interfaces.C.Strings.New_String (Output);
Sys.Out_Append := Append_Output;
end if;
if Error'Length > 0 then
Sys.Err_File := Interfaces.C.Strings.New_String (Error);
Sys.Err_Append := Append_Error;
end if;
end Set_Streams;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
begin
if Sys.Argv /= null then
for I in Sys.Argv'Range loop
Interfaces.C.Strings.Free (Sys.Argv (I));
end loop;
Free (Sys.Argv);
end if;
Interfaces.C.Strings.Free (Sys.In_File);
Interfaces.C.Strings.Free (Sys.Out_File);
Interfaces.C.Strings.Free (Sys.Err_File);
end Finalize;
end Util.Processes.Os;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
e414e6a54fbc810ad653b6981464fe48c951089f
|
src/os-linux/util-systems-dlls.adb
|
src/os-linux/util-systems-dlls.adb
|
-----------------------------------------------------------------------
-- util-systems-dlls -- Unix shared library support
-- 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 System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Systems.Constants;
package body Util.Systems.DLLs is
function Sys_Dlopen (Path : in Interfaces.C.Strings.chars_ptr;
Mode : in Flags) return Handle;
pragma Import (C, Sys_Dlopen, "dlopen");
function Sys_Dlclose (Lib : in Handle) return Interfaces.C.int;
pragma Import (C, Sys_Dlclose, "dlclose");
function Sys_Dlsym (Lib : in Handle;
Symbol : in Interfaces.C.Strings.chars_ptr) return System.Address;
pragma Import (C, Sys_Dlsym, "dlsym");
function Sys_Dlerror return Interfaces.C.Strings.chars_ptr;
pragma Import (C, Sys_Dlerror, "dlerror");
function Error_Message return String is
begin
return Interfaces.C.Strings.Value (Sys_Dlerror);
end Error_Message;
-- -----------------------
-- Load the shared library with the given name or path and return a library handle.
-- Raises the <tt>Load_Error</tt> exception if the library cannot be loaded.
-- -----------------------
function Load (Path : in String;
Mode : in Flags := Util.Systems.Constants.RTLD_LAZY) return Handle is
Lib : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Result : Handle := Sys_Dlopen (Lib, Mode);
begin
Interfaces.C.Strings.Free (Lib);
if Result = Null_Handle then
raise Load_Error with Error_Message;
else
return Result;
end if;
end Load;
-- -----------------------
-- Unload the shared library.
-- -----------------------
procedure Unload (Lib : in Handle) is
Result : Interfaces.C.int;
begin
if Lib /= Null_Handle then
Result := Sys_Dlclose (Lib);
end if;
end Unload;
-- -----------------------
-- Get a global symbol with the given name in the library.
-- Raises the <tt>Not_Found</tt> exception if the symbol does not exist.
-- -----------------------
function Get_Symbol (Lib : in Handle;
Name : in String) return System.Address is
use type System.Address;
Symbol : Interfaces.C.Strings.Chars_Ptr := Interfaces.C.Strings.New_String (Name);
Result : System.Address := Sys_Dlsym (Lib, Symbol);
begin
Interfaces.C.Strings.Free (Symbol);
if Result = System.Null_Address then
raise Not_Found with Error_Message;
else
return Result;
end if;
end Get_Symbol;
end Util.Systems.DLLs;
|
-----------------------------------------------------------------------
-- util-systems-dlls -- Unix shared library support
-- 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 Interfaces.C.Strings;
package body Util.Systems.DLLs is
pragma Linker_Options (Util.Systems.Constants.DLL_OPTIONS);
function Sys_Dlopen (Path : in Interfaces.C.Strings.chars_ptr;
Mode : in Flags) return Handle;
pragma Import (C, Sys_Dlopen, "dlopen");
function Sys_Dlclose (Lib : in Handle) return Interfaces.C.int;
pragma Import (C, Sys_Dlclose, "dlclose");
function Sys_Dlsym (Lib : in Handle;
Symbol : in Interfaces.C.Strings.chars_ptr) return System.Address;
pragma Import (C, Sys_Dlsym, "dlsym");
function Sys_Dlerror return Interfaces.C.Strings.chars_ptr;
pragma Import (C, Sys_Dlerror, "dlerror");
function Error_Message return String;
function Error_Message return String is
begin
return Interfaces.C.Strings.Value (Sys_Dlerror);
end Error_Message;
-- -----------------------
-- Load the shared library with the given name or path and return a library handle.
-- Raises the <tt>Load_Error</tt> exception if the library cannot be loaded.
-- -----------------------
function Load (Path : in String;
Mode : in Flags := Util.Systems.Constants.RTLD_LAZY) return Handle is
Lib : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Result : constant Handle := Sys_Dlopen (Lib, Mode);
begin
Interfaces.C.Strings.Free (Lib);
if Result = Null_Handle then
raise Load_Error with Error_Message;
else
return Result;
end if;
end Load;
-- -----------------------
-- Unload the shared library.
-- -----------------------
procedure Unload (Lib : in Handle) is
Result : Interfaces.C.int;
pragma Unreferenced (Result);
begin
if Lib /= Null_Handle then
Result := Sys_Dlclose (Lib);
end if;
end Unload;
-- -----------------------
-- Get a global symbol with the given name in the library.
-- Raises the <tt>Not_Found</tt> exception if the symbol does not exist.
-- -----------------------
function Get_Symbol (Lib : in Handle;
Name : in String) return System.Address is
use type System.Address;
Symbol : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Name);
Result : constant System.Address := Sys_Dlsym (Lib, Symbol);
begin
Interfaces.C.Strings.Free (Symbol);
if Result = System.Null_Address then
raise Not_Found with Error_Message;
else
return Result;
end if;
end Get_Symbol;
end Util.Systems.DLLs;
|
Add a pragma Linker_Options configured by utilgen in Util.Systems.Constants Fix compilation warnings
|
Add a pragma Linker_Options configured by utilgen in Util.Systems.Constants
Fix compilation warnings
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
409cbc59e9a1d90bb6686726c03f0baa15cef799
|
regtests/asf-views-facelets-tests.adb
|
regtests/asf-views-facelets-tests.adb
|
-----------------------------------------------------------------------
-- Facelet Tests - Unit tests for ASF.Views.Facelet
-- 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 AUnit.Test_Caller;
with AUnit.Assertions;
with Ada.Text_IO;
with ASF.Testsuite;
with AUnit.Assertions;
with ASF.Contexts.Facelets;
with ASF.Components.Util.Factory;
package body ASF.Views.Facelets.Tests is
use AUnit.Assertions;
use ASF.Testsuite;
use ASF.Contexts.Facelets;
-- Set up performed before each test case
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Tear down performed after each test case
overriding
procedure Tear_Down (T : in out Test) is
begin
null;
end Tear_Down;
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
Factory : ASF.Views.Facelets.Facelet_Factory;
Components : aliased ASF.Factory.Component_Factory;
View : ASF.Views.Facelets.Facelet;
Ctx : Facelet_Context;
begin
Initialize (Factory, Components'Unchecked_Access, "regtests/files/views;.", True, True, True);
Find_Facelet (Factory, "text.xhtml", Ctx, View);
T.Assert (Condition => not Is_Null (View),
Message => "Loading an existing facelet should return a view");
end Test_Load_Facelet;
-- Test loading of an unknown file
procedure Test_Load_Unknown_Facelet (T : in out Test) is
Factory : ASF.Views.Facelets.Facelet_Factory;
Components : aliased ASF.Factory.Component_Factory;
View : ASF.Views.Facelets.Facelet;
Ctx : Facelet_Context;
begin
Initialize (Factory, Components'Unchecked_Access, "regtests/files;.", True, True, True);
Find_Facelet (Factory, "not-found-file.xhtml", Ctx, View);
T.Assert (Condition => Is_Null (View),
Message => "Loading a missing facelet should not raise any exception");
end Test_Load_Unknown_Facelet;
package Caller is new AUnit.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Suite.Add_Test (Caller.Create ("Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Facelet'Access));
Suite.Add_Test (Caller.Create ("Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Unknown_Facelet'Access));
end Add_Tests;
end ASF.Views.Facelets.Tests;
|
-----------------------------------------------------------------------
-- Facelet Tests - Unit tests for ASF.Views.Facelet
-- 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 AUnit.Test_Caller;
with AUnit.Assertions;
with Ada.Text_IO;
with ASF.Testsuite;
with AUnit.Assertions;
with ASF.Contexts.Facelets;
with ASF.Components.Utils.Factory;
with ASF.Applications.Main;
package body ASF.Views.Facelets.Tests is
use AUnit.Assertions;
use ASF.Testsuite;
use ASF.Contexts.Facelets;
type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with null record;
-- Get the application associated with this facelet context.
overriding
function Get_Application (Context : in Facelet_Context)
return access ASF.Applications.Main.Application'Class;
-- Get the application associated with this facelet context.
overriding
function Get_Application (Context : in Facelet_Context)
return access ASF.Applications.Main.Application'Class is
begin
return null;
end Get_Application;
-- Set up performed before each test case
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Tear down performed after each test case
overriding
procedure Tear_Down (T : in out Test) is
begin
null;
end Tear_Down;
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
Factory : ASF.Views.Facelets.Facelet_Factory;
Components : aliased ASF.Factory.Component_Factory;
View : ASF.Views.Facelets.Facelet;
Ctx : Facelet_Context;
begin
Initialize (Factory, Components'Unchecked_Access, "regtests/files/views;.", True, True, True);
Find_Facelet (Factory, "text.xhtml", Ctx, View);
T.Assert (Condition => not Is_Null (View),
Message => "Loading an existing facelet should return a view");
end Test_Load_Facelet;
-- Test loading of an unknown file
procedure Test_Load_Unknown_Facelet (T : in out Test) is
Factory : ASF.Views.Facelets.Facelet_Factory;
Components : aliased ASF.Factory.Component_Factory;
View : ASF.Views.Facelets.Facelet;
Ctx : Facelet_Context;
begin
Initialize (Factory, Components'Unchecked_Access, "regtests/files;.", True, True, True);
Find_Facelet (Factory, "not-found-file.xhtml", Ctx, View);
T.Assert (Condition => Is_Null (View),
Message => "Loading a missing facelet should not raise any exception");
end Test_Load_Unknown_Facelet;
package Caller is new AUnit.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Suite.Add_Test (Caller.Create ("Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Facelet'Access));
Suite.Add_Test (Caller.Create ("Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Unknown_Facelet'Access));
end Add_Tests;
end ASF.Views.Facelets.Tests;
|
Fix compilation of unit tests
|
Fix compilation of unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
5fdf64c1c44fed5d4e0cdfdd6a193f45a1e23933
|
regtests/el-contexts-tests.adb
|
regtests/el-contexts-tests.adb
|
-----------------------------------------------------------------------
-- 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.Test_Caller;
with Util.Properties;
with Util.Beans.Objects;
with EL.Expressions;
with EL.Contexts.Properties;
with EL.Contexts.Default;
package body EL.Contexts.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test EL.Contexts.Properties.Get_Value",
Test_Context_Properties'Access);
end Add_Tests;
-- ------------------------------
-- Test Add_Parameter
-- ------------------------------
procedure Test_Context_Properties (T : in out Test) is
function Eval (Item : in String) return String;
Context : EL.Contexts.Default.Default_Context;
Prop_Resolver : aliased EL.Contexts.Properties.Property_Resolver;
Props : Util.Properties.Manager;
function Eval (Item : in String) return String is
Expr : constant Expressions.Expression
:= EL.Expressions.Create_Expression (Item, Context);
Result : constant Util.Beans.Objects.Object := Expr.Get_Value (Context);
begin
return Util.Beans.Objects.To_String (Result);
end Eval;
begin
Props.Set ("user", "joe");
Props.Set ("home", "/home/joe");
Prop_Resolver.Set_Properties (Props);
Context.Set_Resolver (Prop_Resolver'Unchecked_Access);
Assert_Equals (T, "joe", Eval ("#{user}"), "Invalid evaluation of #{user}");
Assert_Equals (T, "/home/joe", Eval ("#{home}"), "Invalid evaluation of #{home}");
end Test_Context_Properties;
end EL.Contexts.Tests;
|
-----------------------------------------------------------------------
-- 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.Test_Caller;
with Util.Properties;
with Util.Beans.Objects;
with EL.Expressions;
with EL.Contexts.Properties;
with EL.Contexts.Default;
package body EL.Contexts.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "EL.Contexts");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test EL.Contexts.Properties.Get_Value",
Test_Context_Properties'Access);
end Add_Tests;
-- ------------------------------
-- Test Add_Parameter
-- ------------------------------
procedure Test_Context_Properties (T : in out Test) is
function Eval (Item : in String) return String;
Context : EL.Contexts.Default.Default_Context;
Prop_Resolver : aliased EL.Contexts.Properties.Property_Resolver;
Props : Util.Properties.Manager;
function Eval (Item : in String) return String is
Expr : constant Expressions.Expression
:= EL.Expressions.Create_Expression (Item, Context);
Result : constant Util.Beans.Objects.Object := Expr.Get_Value (Context);
begin
return Util.Beans.Objects.To_String (Result);
end Eval;
begin
Props.Set ("user", "joe");
Props.Set ("home", "/home/joe");
Prop_Resolver.Set_Properties (Props);
Context.Set_Resolver (Prop_Resolver'Unchecked_Access);
Assert_Equals (T, "joe", Eval ("#{user}"), "Invalid evaluation of #{user}");
Assert_Equals (T, "/home/joe", Eval ("#{home}"), "Invalid evaluation of #{home}");
end Test_Context_Properties;
end EL.Contexts.Tests;
|
Use the test name EL.Contexts
|
Use the test name EL.Contexts
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
ab24d440dacc20c7a98d56f143ceb942c5ebd727
|
matp/src/events/mat-events-targets.ads
|
matp/src/events/mat-events-targets.ads
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Ada.Finalization;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is (MSG_BEGIN,
MSG_END,
MSG_LIBRARY,
MSG_MALLOC,
MSG_FREE,
MSG_REALLOC
);
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Next_Id : Event_Id_Type := 0;
Prev_Id : Event_Id_Type := 0;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
Old_Size : MAT.Types.Target_Size;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type;
type Event_Info_Type is record
First_Event : Target_Event;
Last_Event : Target_Event;
Frame_Addr : MAT.Types.Target_Addr;
Count : Natural;
end record;
package Size_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size,
Element_Type => Event_Info_Type);
subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map;
subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor;
package Frame_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Event_Info_Type);
subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map;
subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor;
package Event_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Event_Info_Type);
subtype Event_Info_Vector is Event_Info_Vectors.Vector;
subtype Event_Info_Cursor is Event_Info_Vectors.Cursor;
-- Extract from the frame info map, the list of event info sorted on the count.
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector);
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the first and last event that have been received.
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Clear the events.
procedure Clear;
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is new Ada.Finalization.Limited_Controlled with record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
-- Release the storage allocated for the events.
overriding
procedure Finalize (Target : in out Target_Events);
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Ada.Finalization;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is (MSG_BEGIN,
MSG_END,
MSG_LIBRARY,
MSG_MALLOC,
MSG_FREE,
MSG_REALLOC
);
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Next_Id : Event_Id_Type := 0;
Prev_Id : Event_Id_Type := 0;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
Old_Size : MAT.Types.Target_Size;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Probe_Event_Type;
type Event_Info_Type is record
First_Event : Target_Event;
Last_Event : Target_Event;
Frame_Addr : MAT.Types.Target_Addr;
Count : Natural;
end record;
package Size_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size,
Element_Type => Event_Info_Type);
subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map;
subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor;
package Frame_Event_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Event_Info_Type);
subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map;
subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor;
package Event_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Event_Info_Type);
subtype Event_Info_Vector is Event_Info_Vectors.Vector;
subtype Event_Info_Cursor is Event_Info_Vectors.Cursor;
-- Extract from the frame info map, the list of event info sorted on the count.
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector);
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the first and last event that have been received.
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
procedure Update_Event (Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type);
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
-- Clear the events.
procedure Clear;
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is new Ada.Finalization.Limited_Controlled with record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
-- Release the storage allocated for the events.
overriding
procedure Finalize (Target : in out Target_Events);
end MAT.Events.Targets;
|
Declare the Update_Event protected procedure
|
Declare the Update_Event protected procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
7014dfe426f17c1608ee7c64db4dcced01ae5668
|
src/util-beans.ads
|
src/util-beans.ads
|
-----------------------------------------------------------------------
-- util-beans -- Interface Definition with Getter and Setters
-- Copyright (C) 2009, 2010, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- = Ada Beans =
-- A [Java Bean](http://en.wikipedia.org/wiki/JavaBean) is an object that
-- allows to access its properties through getters and setters. Java Beans
-- rely on the use of Java introspection to discover the Java Bean object properties.
--
-- An Ada Bean has some similarities with the Java Bean as it tries to expose
-- an object through a set of common interfaces. Since Ada does not have introspection,
-- some developer work is necessary. The Ada Bean framework consists of:
--
-- * An `Object` concrete type that allows to hold any data type such
-- as boolean, integer, floats, strings, dates and Ada bean objects.
-- * A `Bean` interface that exposes a `Get_Value` and `Set_Value`
-- operation through which the object properties can be obtained and modified.
-- * A `Method_Bean` interface that exposes a set of method bindings
-- that gives access to the methods provided by the Ada Bean object.
--
-- The benefit of Ada beans comes when you need to get a value or invoke
-- a method on an object but you don't know at compile time the object or method.
-- That step being done later through some external configuration or presentation file.
--
-- The Ada Bean framework is the basis for the implementation of
-- [Ada Server Faces](http://code.google.com/p/ada-asf/) and
-- [Ada EL](http://code.google.com/p/ada-el/). It allows the presentation layer to
-- access information provided by Ada beans.
--
-- @include util-beans-objects.ads
-- @include util-beans-objects-datasets.ads
-- @include util-beans-basic.ads
package Util.Beans is
pragma Preelaborate;
end Util.Beans;
|
-----------------------------------------------------------------------
-- util-beans -- Interface Definition with Getter and Setters
-- Copyright (C) 2009, 2010, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- = Ada Beans =
-- A [Java Bean](http://en.wikipedia.org/wiki/JavaBean) is an object that
-- allows to access its properties through getters and setters. Java Beans
-- rely on the use of Java introspection to discover the Java Bean object properties.
--
-- An Ada Bean has some similarities with the Java Bean as it tries to expose
-- an object through a set of common interfaces. Since Ada does not have introspection,
-- some developer work is necessary. The Ada Bean framework consists of:
--
-- * An `Object` concrete type that allows to hold any data type such
-- as boolean, integer, floats, strings, dates and Ada bean objects.
-- * A `Bean` interface that exposes a `Get_Value` and `Set_Value`
-- operation through which the object properties can be obtained and modified.
-- * A `Method_Bean` interface that exposes a set of method bindings
-- that gives access to the methods provided by the Ada Bean object.
--
-- The benefit of Ada beans comes when you need to get a value or invoke
-- a method on an object but you don't know at compile time the object or method.
-- That step being done later through some external configuration or presentation file.
--
-- The Ada Bean framework is the basis for the implementation of
-- Ada Server Faces and Ada EL. It allows the presentation layer to
-- access information provided by Ada beans.
--
-- @include util-beans-objects.ads
-- @include util-beans-objects-datasets.ads
-- @include util-beans-basic.ads
package Util.Beans is
pragma Preelaborate;
end Util.Beans;
|
Remove links since they are now automatically generated
|
Remove links since they are now automatically generated
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
03e5941a343701187e39d633658abab928bbb15b
|
regtests/ado-tests.adb
|
regtests/ado-tests.adb
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- 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 Ada.Exceptions;
with Ada.Calendar;
with ADO.Statements;
with ADO.Objects;
with ADO.Databases;
with ADO.Sessions;
with ADO.Utils;
with Regtests;
with Regtests.Simple.Model;
with Regtests.Images.Model;
with Util.Assertions;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Test_Caller;
package body ADO.Tests is
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests");
package Caller is new Util.Test_Caller (Test, "ADO");
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
T.Fail ("Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
T.Fail ("Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use ADO.Objects;
use type ADO.Sessions.Connection_Status;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
T.Assert (DB.Get_Status = ADO.Sessions.OPEN,
"The database connection is open");
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
-- ------------------------------
-- Test string insert.
-- ------------------------------
procedure Test_String (T : in out Test) is
use ADO.Objects;
use Ada.Strings.Unbounded;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
User : Regtests.Simple.Model.User_Ref;
Usr2 : Regtests.Simple.Model.User_Ref;
Name : Unbounded_String;
begin
for I in 1 .. 127 loop
Append (Name, Character'Val (I));
end loop;
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
DB.Begin_Transaction;
User.Set_Name (Name);
User.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Usr2.Load (DB, User.Get_Id);
Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name),
"Invalid name inserted for user");
end Test_String;
-- ------------------------------
-- Test blob insert.
-- ------------------------------
procedure Test_Blob (T : in out Test) is
use ADO.Objects;
use Ada.Streams;
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element);
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Img : Regtests.Images.Model.Image_Ref;
Size : constant Natural := 100;
Data : ADO.Blob_Ref := ADO.Create_Blob (Size);
Img2 : Regtests.Images.Model.Image_Ref;
begin
for I in 1 .. Size loop
Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255);
end loop;
DB.Begin_Transaction;
Img.Set_Image (Data);
Img.Set_Create_Date (Ada.Calendar.Clock);
Img.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
-- And verify that the blob data matches what we inserted.
Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len),
"Invalid blob length");
for I in 1 .. Data.Value.Len loop
Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I),
"Invalid blob content at " & Stream_Element_Offset'Image (I));
end loop;
-- Create a blob initialized with a file content.
Data := ADO.Create_Blob ("Makefile");
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob");
T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small");
declare
Content : Ada.Streams.Stream_Element_Array (1 .. 10);
Img3 : Regtests.Images.Model.Image_Ref;
begin
for I in Content'Range loop
Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30);
end loop;
Data := ADO.Create_Blob (Content);
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)");
T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small");
DB.Begin_Transaction;
Img3.Set_Image (Data);
Img3.Set_Create_Date (Ada.Calendar.Clock);
Img3.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img3.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
Img2.Set_Image (ADO.Null_Blob);
Img2.Save (DB);
DB.Commit;
end;
end Test_Blob;
-- ------------------------------
-- Test the To_Object and To_Identifier operations.
-- ------------------------------
procedure Test_Identifier_To_Object (T : in out Test) is
Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER);
begin
T.Assert (Util.Beans.Objects.Is_Null (Val),
"To_Object must return null for ADO.NO_IDENTIFIER");
T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER,
"To_Identifier must return ADO.NO_IDENTIFIER for null");
Val := ADO.Utils.To_Object (1);
T.Assert (not Util.Beans.Objects.Is_Null (Val),
"To_Object must not return null for a valid Identifier");
T.Assert (ADO.Utils.To_Identifier (Val) = 1,
"To_Identifier must return the correct identifier");
end Test_Identifier_To_Object;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access);
Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access);
Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access);
Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access);
Caller.Add_Test (Suite, "Test insert string",
Test_String'Access);
Caller.Add_Test (Suite, "Test insert blob",
Test_Blob'Access);
Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier",
Test_Identifier_To_Object'Access);
end Add_Tests;
end ADO.Tests;
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- 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 Ada.Exceptions;
with Ada.Calendar;
with ADO.Statements;
with ADO.Objects;
with ADO.Sessions;
with ADO.Utils;
with Regtests;
with Regtests.Simple.Model;
with Regtests.Images.Model;
with Util.Assertions;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Test_Caller;
package body ADO.Tests is
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests");
package Caller is new Util.Test_Caller (Test, "ADO");
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
T.Fail ("Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
T.Fail ("Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use ADO.Objects;
use type ADO.Sessions.Connection_Status;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
T.Assert (DB.Get_Status = ADO.Sessions.OPEN,
"The database connection is open");
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
-- ------------------------------
-- Test string insert.
-- ------------------------------
procedure Test_String (T : in out Test) is
use ADO.Objects;
use Ada.Strings.Unbounded;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
User : Regtests.Simple.Model.User_Ref;
Usr2 : Regtests.Simple.Model.User_Ref;
Name : Unbounded_String;
begin
for I in 1 .. 127 loop
Append (Name, Character'Val (I));
end loop;
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
DB.Begin_Transaction;
User.Set_Name (Name);
User.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Usr2.Load (DB, User.Get_Id);
Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name),
"Invalid name inserted for user");
end Test_String;
-- ------------------------------
-- Test blob insert.
-- ------------------------------
procedure Test_Blob (T : in out Test) is
use ADO.Objects;
use Ada.Streams;
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element);
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Img : Regtests.Images.Model.Image_Ref;
Size : constant Natural := 100;
Data : ADO.Blob_Ref := ADO.Create_Blob (Size);
Img2 : Regtests.Images.Model.Image_Ref;
begin
for I in 1 .. Size loop
Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255);
end loop;
DB.Begin_Transaction;
Img.Set_Image (Data);
Img.Set_Create_Date (Ada.Calendar.Clock);
Img.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
-- And verify that the blob data matches what we inserted.
Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len),
"Invalid blob length");
for I in 1 .. Data.Value.Len loop
Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I),
"Invalid blob content at " & Stream_Element_Offset'Image (I));
end loop;
-- Create a blob initialized with a file content.
Data := ADO.Create_Blob ("Makefile");
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob");
T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small");
declare
Content : Ada.Streams.Stream_Element_Array (1 .. 10);
Img3 : Regtests.Images.Model.Image_Ref;
begin
for I in Content'Range loop
Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30);
end loop;
Data := ADO.Create_Blob (Content);
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)");
T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small");
DB.Begin_Transaction;
Img3.Set_Image (Data);
Img3.Set_Create_Date (Ada.Calendar.Clock);
Img3.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img3.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
Img2.Set_Image (ADO.Null_Blob);
Img2.Save (DB);
DB.Commit;
end;
end Test_Blob;
-- ------------------------------
-- Test the To_Object and To_Identifier operations.
-- ------------------------------
procedure Test_Identifier_To_Object (T : in out Test) is
Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER);
begin
T.Assert (Util.Beans.Objects.Is_Null (Val),
"To_Object must return null for ADO.NO_IDENTIFIER");
T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER,
"To_Identifier must return ADO.NO_IDENTIFIER for null");
Val := ADO.Utils.To_Object (1);
T.Assert (not Util.Beans.Objects.Is_Null (Val),
"To_Object must not return null for a valid Identifier");
T.Assert (ADO.Utils.To_Identifier (Val) = 1,
"To_Identifier must return the correct identifier");
end Test_Identifier_To_Object;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access);
Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access);
Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access);
Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access);
Caller.Add_Test (Suite, "Test insert string",
Test_String'Access);
Caller.Add_Test (Suite, "Test insert blob",
Test_Blob'Access);
Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier",
Test_Identifier_To_Object'Access);
end Add_Tests;
end ADO.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
291f6d2c157f59ac2e9f83321a9d93626ca4c587
|
src/wiki-nodes.ads
|
src/wiki-nodes.ads
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Strings;
package Wiki.Nodes is
pragma Preelaborate;
type Node_Kind is (N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_TOC_DISPLAY,
N_PARAGRAPH,
N_NEWLINE,
N_HEADER,
N_TOC,
N_TOC_ENTRY,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_PREFORMAT,
N_TABLE,
N_ROW,
N_COLUMN,
N_LIST,
N_NUM_LIST,
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_NEWLINE;
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
Parent : Node_Type_Access;
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY =>
Level : Natural := 0;
Header : Wiki.Strings.WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : Wiki.Strings.WString (1 .. Len);
when N_LINK | N_IMAGE | N_QUOTE =>
Link_Attr : Wiki.Attributes.Attribute_List;
Title : Wiki.Strings.WString (1 .. Len);
when N_TAG_START | N_TABLE | N_ROW | N_COLUMN =>
Tag_Start : Html_Tag;
Attributes : Wiki.Attributes.Attribute_List;
Children : Node_List_Access;
when N_PREFORMAT =>
Language : Wiki.Strings.UString;
Preformatted : Wiki.Strings.WString (1 .. Len);
when N_TOC =>
Entries : Node_List_Access;
when others =>
null;
end case;
end record;
-- Append a node to the tag node.
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access);
-- Append a node to the document.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
-- Finalize the node list to release the allocated memory.
procedure Finalize (List : in out Node_List);
private
NODE_LIST_BLOCK_SIZE : constant Positive := 16;
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;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Strings;
package Wiki.Nodes is
pragma Preelaborate;
type Node_Kind is (N_NONE,
N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_TOC_DISPLAY,
N_PARAGRAPH,
N_LIST_ITEM_END,
N_LIST_END,
N_NUM_LIST_END,
N_LIST_ITEM,
N_NEWLINE,
N_HEADER,
N_TOC,
N_TOC_ENTRY,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_PREFORMAT,
N_TABLE,
N_ROW,
N_COLUMN,
N_LIST_START,
N_NUM_LIST_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_NONE .. N_NEWLINE;
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
Parent : Node_Type_Access;
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_TOC_ENTRY
| N_NUM_LIST_START | N_LIST_START =>
Level : Natural := 0;
Header : Wiki.Strings.WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : Wiki.Strings.WString (1 .. Len);
when N_LINK | N_IMAGE | N_QUOTE =>
Link_Attr : Wiki.Attributes.Attribute_List;
Title : Wiki.Strings.WString (1 .. Len);
when N_TAG_START | N_TABLE | N_ROW | N_COLUMN =>
Tag_Start : Html_Tag;
Attributes : Wiki.Attributes.Attribute_List;
Children : Node_List_Access;
when N_PREFORMAT =>
Language : Wiki.Strings.UString;
Preformatted : Wiki.Strings.WString (1 .. Len);
when N_TOC =>
Entries : Node_List_Access;
when others =>
null;
end case;
end record;
-- Append a node to the tag node.
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access);
-- Append a node to the document.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
-- Finalize the node list to release the allocated memory.
procedure Finalize (List : in out Node_List);
private
NODE_LIST_BLOCK_SIZE : constant Positive := 16;
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;
end Wiki.Nodes;
|
Change the list representation to better identify the start and end of list and list items
|
Change the list representation to better identify the start and end of list and list items
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
b1a58ebfee8ef5110a2cf2d86612eebadb7a6a61
|
demo/text2.adb
|
demo/text2.adb
|
with ada.text_io; use ada.text_io;
-- Simple Lumen demo/test program to illustrate how to display text, using the
-- texture-mapped font facility.
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.Strings.Fixed;
with Ada.Float_Text_IO;
with Lumen.Events.Animate;
with Lumen.Window;
with Lumen.Font.Txf;
with Lumen.GL;
with Lumen.GLU;
use Lumen;
procedure Text2 is
---------------------------------------------------------------------------
-- Rotation wraps around at this point, in degrees
Max_Rotation : constant := 359;
-- Nice peppy game-style framerate, in frames per second
Framerate : constant := 60;
-- A font to fall back on
Default_Font_Path : constant String := "fsb.txf";
---------------------------------------------------------------------------
Win : Window.Handle;
Direct : Boolean := True; -- want direct rendering by default
Event : Events.Event_Data;
Wide : Natural := 400;
High : Natural := 400;
Img_Wide : Float;
Img_High : Float;
Rotation : Natural := 0;
Tx_Font : Font.Txf.Handle;
Object : GL.UInt;
Frame : Natural := 0;
Attrs : Window.Context_Attributes :=
(
(Window.Attr_Red_Size, 8),
(Window.Attr_Green_Size, 8),
(Window.Attr_Blue_Size, 8),
(Window.Attr_Alpha_Size, 8),
(Window.Attr_Depth_Size, 24)
);
---------------------------------------------------------------------------
Program_Error : exception;
Program_Exit : exception;
---------------------------------------------------------------------------
-- Return number blank-padded on the left out to Width; returns full
-- number if it's wider than Width.
function Img (Number : in Integer;
Width : in Positive := 1) return String is
use Ada.Strings.Fixed;
Image : String := Trim (Integer'Image (Number), Side => Ada.Strings.Left);
begin -- Img
if Image'Length >= Width then
return Image;
else
return ((Width - Image'Length) * ' ') & Image;
end if;
end Img;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
Aspect : GL.Double;
begin -- Set_View
-- Viewport dimensions
GL.Viewport (0, 0, GL.SizeI (W), GL.SizeI (H));
-- Size of rectangle upon which text is displayed
if Wide > High then
Img_Wide := 1.0;
Img_High := Float (High) / Float (Wide);
else
Img_Wide := Float (Wide) / Float (High);
Img_High := 1.0;
end if;
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
GL.MatrixMode (GL.GL_PROJECTION);
GL.LoadIdentity;
-- Set up a 3D viewing frustum, which is basically a truncated pyramid
-- in which the scene takes place. Roughly, the narrow end is your
-- screen, and the wide end is 10 units away from the camera.
if W <= H then
Aspect := GL.Double (H) / GL.Double (W);
GL.Frustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0);
else
Aspect := GL.Double (W) / GL.Double (H);
GL.Frustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0);
end if;
end Set_View;
---------------------------------------------------------------------------
-- Draw our scene
procedure Draw is
use type GL.Bitfield;
MW : Natural;
MA : Natural;
MD : Natural;
Scale : Float;
Pad : Float := Img_Wide / 10.0;
FNum : String := Img (Frame, 6);
FRate : String (1 .. 6);
begin -- Draw
-- Set an off-white background
GL.ClearColor (0.85, 0.85, 0.85, 0.0);
GL.Clear (GL.GL_COLOR_BUFFER_BIT or GL.GL_DEPTH_BUFFER_BIT);
-- Draw a black square
GL.Disable (GL.GL_TEXTURE_2D);
GL.Disable (GL.GL_BLEND);
GL.Disable (GL.GL_ALPHA_TEST);
GL.Color (Float (0.0), 0.0, 0.0);
GL.glBegin (GL.GL_POLYGON);
begin
GL.Vertex (-Img_Wide, -Img_High, 0.0);
GL.Vertex (-Img_Wide, Img_High, 0.0);
GL.Vertex ( Img_Wide, Img_High, 0.0);
GL.Vertex ( Img_Wide, -Img_High, 0.0);
end;
GL.glEnd;
-- Set up to draw the text messages
GL.PushMatrix;
GL.Enable (GL.GL_TEXTURE_2D);
GL.Enable (GL.GL_ALPHA_TEST);
GL.AlphaFunc (GL.GL_GEQUAL, 0.0625);
GL.Enable (GL.GL_BLEND);
GL.BlendFunc (GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
GL.Enable (GL.GL_POLYGON_OFFSET_FILL);
GL.PolygonOffset (0.0, -3.0);
GL.Color (Float (0.1), 0.8, 0.1);
-- Draw the frame number, right-justified in upper half of rectangle
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, FNum, MW, MA, MD);
Scale := Img_High / (Float (MA) * 3.0);
GL.Translate (Img_Wide - (Pad + Float (MW) * Scale), Float (MA) * Scale, 0.0);
GL.Scale (Scale, Scale, Scale);
Font.Txf.Render (Tx_Font, FNum);
GL.PopMatrix;
-- Draw the frame rate, right-justified in lowe half of rectangle
GL.PushMatrix;
begin
Ada.Float_Text_IO.Put (FRate, Events.Animate.FPS (Win), Aft => 3, Exp => 0);
exception
when others =>
FRate := (others => '?');
end;
Font.Txf.Get_String_Metrics (Tx_Font, FRate, MW, MA, MD);
GL.Translate (Img_Wide - (Pad + Float (MW) * Scale), -Float (MA) * Scale, 0.0);
GL.Scale (Scale, Scale, Scale);
Font.Txf.Render (Tx_Font, FRate);
GL.PopMatrix;
GL.PopMatrix;
-- Rotate the object around the Y and Z axes by the current amount, to
-- give a "tumbling" effect.
GL.MatrixMode (GL.GL_MODELVIEW);
GL.LoadIdentity;
GL.Translate (GL.Double (0.0), 0.0, -4.0);
GL.Rotate (GL.Double (Rotation), 0.0, 1.0, 0.0);
GL.Rotate (GL.Double (Rotation), 0.0, 0.0, 1.0);
-- Now show it
Window.Swap (Win);
end Draw;
---------------------------------------------------------------------------
-- Simple event handler routine for close-window events
procedure Quit_Handler (Event : in Events.Event_Data) is
begin -- Quit_Handler
raise Program_Exit;
end Quit_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses
procedure Key_Handler (Event : in Events.Event_Data) is
use type Events.Key_Symbol;
begin -- Key_Handler
if Event.Key_Data.Key = Events.To_Symbol (Ada.Characters.Latin_1.ESC) or
Event.Key_Data.Key = Events.To_Symbol ('q') then
raise Program_Exit;
end if;
end Key_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Exposed events
procedure Expose_Handler (Event : in Events.Event_Data) is
begin -- Expose_Handler
Draw;
end Expose_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Resized events
procedure Resize_Handler (Event : in Events.Event_Data) is
begin -- Resize_Handler
Wide := Event.Resize_Data.Width;
High := Event.Resize_Data.Height;
Set_View (Wide, High);
Draw;
end Resize_Handler;
---------------------------------------------------------------------------
-- Our draw-a-frame routine, should get called FPS times a second
procedure New_Frame (Frame_Delta : in Duration) is
begin -- New_Frame
if Rotation >= Max_Rotation then
Rotation := 0;
else
Rotation := Rotation + 1;
end if;
Frame := Frame + 1;
Draw;
end New_Frame;
---------------------------------------------------------------------------
begin -- Text2
-- Load the font we'll be using
if Ada.Command_Line.Argument_Count > 0 then
declare
Font_Path : String := Ada.Command_Line.Argument (1);
begin
Font.Txf.Load (Tx_Font, Font_Path);
exception
when others =>
raise Program_Error with "cannot find font file """ & Font_Path & """";
end;
else
begin
Font.Txf.Load (Tx_Font, Default_Font_Path);
exception
when others =>
begin
Font.Txf.Load (Tx_Font, "demo/" & Default_Font_Path);
exception
when others =>
raise Program_Error with "cannot find default font file """ & Default_Font_Path & """";
end;
end;
end if;
-- If other command-line arguments were given then process them
for Index in 2 .. Ada.Command_Line.Argument_Count loop
declare
use Window;
Arg : String := Ada.Command_Line.Argument (Index);
begin
case Arg (Arg'First) is
when 'a' =>
Attrs (4) := (Attr_Alpha_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'c' =>
Attrs (1) := (Attr_Red_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (2) := (Attr_Blue_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (3) := (Attr_Green_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'd' =>
Attrs (5) := (Attr_Depth_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'n' =>
Direct := False;
when others =>
null;
end case;
end;
end loop;
-- Create Lumen window, accepting most defaults; turn double buffering off
-- for simplicity
Window.Create (Win,
Name => "Text Demo #2, Revenge of the Text",
Width => Wide,
Height => High,
Direct => Direct,
Attributes => Attrs,
Events => (Window.Want_Key_Press => True,
Window.Want_Exposure => True,
others => False));
-- Set up the viewport and scene parameters
Set_View (Wide, High);
Object := Font.Txf.Establish_Texture (Tx_Font, 0, True);
-- Enter the event loop
declare
use Events;
begin
Animate.Select_Events (Win => Win,
Calls => (Key_Press => Key_Handler'Unrestricted_Access,
Exposed => Expose_Handler'Unrestricted_Access,
Resized => Resize_Handler'Unrestricted_Access,
Close_Window => Quit_Handler'Unrestricted_Access,
others => No_Callback),
FPS => Framerate,
Frame => New_Frame'Unrestricted_Access);
end;
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Text2;
|
with ada.text_io; use ada.text_io;
-- Simple Lumen demo/test program to illustrate how to display text, using the
-- texture-mapped font facility.
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.Strings.Fixed;
with Ada.Float_Text_IO;
with Lumen.Events.Animate;
with Lumen.Window;
with Lumen.Font.Txf;
with Lumen.GL;
with Lumen.GLU;
use Lumen;
procedure Text2 is
---------------------------------------------------------------------------
-- Rotation wraps around at this point, in degrees
Max_Rotation : constant := 359;
-- Nice peppy game-style framerate, in frames per second
Framerate : constant := 60;
-- A font to fall back on
Default_Font_Path : constant String := "fsb.txf";
---------------------------------------------------------------------------
Win : Window.Handle;
Direct : Boolean := True; -- want direct rendering by default
Event : Events.Event_Data;
Wide : Natural := 400;
High : Natural := 400;
Img_Wide : Float;
Img_High : Float;
Rotation : Natural := 0;
Rotating : Boolean := True;
Tx_Font : Font.Txf.Handle;
Object : GL.UInt;
Frame : Natural := 0;
Attrs : Window.Context_Attributes :=
(
(Window.Attr_Red_Size, 8),
(Window.Attr_Green_Size, 8),
(Window.Attr_Blue_Size, 8),
(Window.Attr_Alpha_Size, 8),
(Window.Attr_Depth_Size, 24)
);
---------------------------------------------------------------------------
Program_Error : exception;
Program_Exit : exception;
---------------------------------------------------------------------------
-- Return number blank-padded on the left out to Width; returns full
-- number if it's wider than Width.
function Img (Number : in Integer;
Width : in Positive := 1) return String is
use Ada.Strings.Fixed;
Image : String := Trim (Integer'Image (Number), Side => Ada.Strings.Left);
begin -- Img
if Image'Length >= Width then
return Image;
else
return ((Width - Image'Length) * ' ') & Image;
end if;
end Img;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
Aspect : GL.Double;
begin -- Set_View
-- Viewport dimensions
GL.Viewport (0, 0, GL.SizeI (W), GL.SizeI (H));
-- Size of rectangle upon which text is displayed
if Wide > High then
Img_Wide := 1.0;
Img_High := Float (High) / Float (Wide);
else
Img_Wide := Float (Wide) / Float (High);
Img_High := 1.0;
end if;
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
GL.MatrixMode (GL.GL_PROJECTION);
GL.LoadIdentity;
-- Set up a 3D viewing frustum, which is basically a truncated pyramid
-- in which the scene takes place. Roughly, the narrow end is your
-- screen, and the wide end is 10 units away from the camera.
if W <= H then
Aspect := GL.Double (H) / GL.Double (W);
GL.Frustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0);
else
Aspect := GL.Double (W) / GL.Double (H);
GL.Frustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0);
end if;
end Set_View;
---------------------------------------------------------------------------
-- Draw our scene
procedure Draw is
use type GL.Bitfield;
MW : Natural;
MA : Natural;
MD : Natural;
Scale : Float;
Pad : Float := Img_Wide / 10.0; -- margin width
FNum : String := Img (Frame, 6);
FRate : String (1 .. 6);
begin -- Draw
-- Set a light grey background
GL.ClearColor (0.85, 0.85, 0.85, 0.0);
GL.Clear (GL.GL_COLOR_BUFFER_BIT or GL.GL_DEPTH_BUFFER_BIT);
-- Draw a black rectangle, disabling texturing so we can do plain colors
GL.Disable (GL.GL_TEXTURE_2D);
GL.Disable (GL.GL_BLEND);
GL.Disable (GL.GL_ALPHA_TEST);
GL.Color (Float (0.0), 0.0, 0.0);
GL.glBegin (GL.GL_POLYGON);
begin
GL.Vertex (-Img_Wide, -Img_High, 0.0);
GL.Vertex (-Img_Wide, Img_High, 0.0);
GL.Vertex ( Img_Wide, Img_High, 0.0);
GL.Vertex ( Img_Wide, -Img_High, 0.0);
end;
GL.glEnd;
-- Turn texturing back on and set up to draw the text messages
GL.PushMatrix;
GL.Enable (GL.GL_TEXTURE_2D);
GL.Enable (GL.GL_ALPHA_TEST);
GL.AlphaFunc (GL.GL_GEQUAL, 0.0625);
GL.Enable (GL.GL_BLEND);
GL.BlendFunc (GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
GL.Enable (GL.GL_POLYGON_OFFSET_FILL);
GL.PolygonOffset (0.0, -3.0);
GL.Color (Float (0.1), 0.8, 0.1);
-- Draw the frame number, right-justified in upper half of rectangle
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, FNum, MW, MA, MD);
Scale := Img_High / (Float (MA) * 3.0);
GL.Translate (Img_Wide - (Pad + Float (MW) * Scale), Float (MA) * Scale, 0.0);
GL.Scale (Scale, Scale, Scale);
Font.Txf.Render (Tx_Font, FNum);
GL.PopMatrix;
-- Draw the frame number label, left-justified in upper half of
-- rectangle, and one-third the size of the number itself
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, "Frame", MW, MA, MD);
GL.Translate (-(Img_Wide - Pad), Float (MA) * Scale, 0.0);
GL.Scale (Scale / 3.0, Scale / 3.0, Scale / 3.0);
Font.Txf.Render (Tx_Font, "Frame");
GL.PopMatrix;
-- Draw the frame rate, right-justified in lower half of rectangle
GL.PushMatrix;
-- Guard against out-of-range values, and display all question marks if so
begin
Ada.Float_Text_IO.Put (FRate, Events.Animate.FPS (Win), Aft => 3, Exp => 0);
exception
when others =>
FRate := (others => '?');
end;
Font.Txf.Get_String_Metrics (Tx_Font, FRate, MW, MA, MD);
GL.Translate (Img_Wide - (Pad + Float (MW) * Scale), -Float (MA) * Scale, 0.0);
GL.Scale (Scale, Scale, Scale);
Font.Txf.Render (Tx_Font, FRate);
GL.PopMatrix;
-- Draw the frame rate label, left-justified in lower half of
-- rectangle, and one-third the size of the number itself
GL.PushMatrix;
Font.Txf.Get_String_Metrics (Tx_Font, "FPS", MW, MA, MD);
GL.Translate (-(Img_Wide - Pad), -Float (MA) * Scale, 0.0);
GL.Scale (Scale / 3.0, Scale / 3.0, Scale / 3.0);
Font.Txf.Render (Tx_Font, "FPS");
GL.PopMatrix;
GL.PopMatrix;
-- Rotate the object around the Y and Z axes by the current amount, to
-- give a "tumbling" effect.
GL.MatrixMode (GL.GL_MODELVIEW);
GL.LoadIdentity;
GL.Translate (GL.Double (0.0), 0.0, -4.0);
GL.Rotate (GL.Double (Rotation), 0.0, 1.0, 0.0);
GL.Rotate (GL.Double (Rotation), 0.0, 0.0, 1.0);
-- Now show it
Window.Swap (Win);
end Draw;
---------------------------------------------------------------------------
-- Simple event handler routine for close-window events
procedure Quit_Handler (Event : in Events.Event_Data) is
begin -- Quit_Handler
raise Program_Exit;
end Quit_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses
procedure Key_Handler (Event : in Events.Event_Data) is
use type Events.Key_Symbol;
begin -- Key_Handler
if Event.Key_Data.Key = Events.To_Symbol (Ada.Characters.Latin_1.ESC) or
Event.Key_Data.Key = Events.To_Symbol ('q') then
raise Program_Exit;
elsif Event.Key_Data.Key = Events.To_Symbol (Ada.Characters.Latin_1.Space) then
Rotating := not Rotating;
end if;
end Key_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Exposed events
procedure Expose_Handler (Event : in Events.Event_Data) is
begin -- Expose_Handler
Draw;
end Expose_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Resized events
procedure Resize_Handler (Event : in Events.Event_Data) is
begin -- Resize_Handler
Wide := Event.Resize_Data.Width;
High := Event.Resize_Data.Height;
Set_View (Wide, High);
Draw;
end Resize_Handler;
---------------------------------------------------------------------------
-- Our draw-a-frame routine, should get called FPS times a second
procedure New_Frame (Frame_Delta : in Duration) is
begin -- New_Frame
if Rotating then
if Rotation >= Max_Rotation then
Rotation := 0;
else
Rotation := Rotation + 1;
end if;
end if;
Frame := Frame + 1;
Draw;
end New_Frame;
---------------------------------------------------------------------------
begin -- Text2
-- Load the font we'll be using
if Ada.Command_Line.Argument_Count > 0 then
declare
Font_Path : String := Ada.Command_Line.Argument (1);
begin
Font.Txf.Load (Tx_Font, Font_Path);
exception
when others =>
raise Program_Error with "cannot find font file """ & Font_Path & """";
end;
else
begin
Font.Txf.Load (Tx_Font, Default_Font_Path);
exception
when others =>
begin
Font.Txf.Load (Tx_Font, "demo/" & Default_Font_Path);
exception
when others =>
raise Program_Error with "cannot find default font file """ & Default_Font_Path & """";
end;
end;
end if;
-- If other command-line arguments were given then process them
for Index in 2 .. Ada.Command_Line.Argument_Count loop
declare
use Window;
Arg : String := Ada.Command_Line.Argument (Index);
begin
case Arg (Arg'First) is
when 'a' =>
Attrs (4) := (Attr_Alpha_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'c' =>
Attrs (1) := (Attr_Red_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (2) := (Attr_Blue_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (3) := (Attr_Green_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'd' =>
Attrs (5) := (Attr_Depth_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'n' =>
Direct := False;
when others =>
null;
end case;
end;
end loop;
-- Create Lumen window, accepting most defaults; turn double buffering off
-- for simplicity
Window.Create (Win,
Name => "Text Demo #2, Revenge of the Text",
Width => Wide,
Height => High,
Direct => Direct,
Attributes => Attrs,
Events => (Window.Want_Key_Press => True,
Window.Want_Exposure => True,
others => False));
-- Set up the viewport and scene parameters
Set_View (Wide, High);
Object := Font.Txf.Establish_Texture (Tx_Font, 0, True);
-- Enter the event loop
declare
use Events;
begin
Animate.Select_Events (Win => Win,
Calls => (Key_Press => Key_Handler'Unrestricted_Access,
Exposed => Expose_Handler'Unrestricted_Access,
Resized => Resize_Handler'Unrestricted_Access,
Close_Window => Quit_Handler'Unrestricted_Access,
others => No_Callback),
FPS => Framerate,
Frame => New_Frame'Unrestricted_Access);
end;
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Text2;
|
Add labels, pause key, and other minor touch-ups
|
Add labels, pause key, and other minor touch-ups
|
Ada
|
isc
|
darkestkhan/lumen,darkestkhan/lumen2
|
9d2028532abe35ecb0b8266a8713f1307fa9a9a1
|
src/util-strings.ads
|
src/util-strings.ads
|
-----------------------------------------------------------------------
-- Util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Indefinite_Hashed_Maps;
package Util.Strings is
type String_Access is access all String;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
package String_Map is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
end Util.Strings;
|
-----------------------------------------------------------------------
-- Util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Sets;
package Util.Strings is
type String_Access is access all String;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
package String_Map is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
package String_Set is new Ada.Containers.Indefinite_Hashed_Sets
(Element_Type => Name_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Keys);
end Util.Strings;
|
Define a package to represent and use a set of string pointers
|
Define a package to represent and use a set of string pointers
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
bb7095b556dcd87bbfdb22bcaac32718155ed577
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Nodes;
with Wiki.Streams;
with Wiki.Render;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
type Parser is tagged limited private;
-- Add the plugin to the wiki engine.
procedure Add_Plugin (Engine : in out Parser;
Name : in String;
Plugin : in Wiki.Plugins.Wiki_Plugin_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wide_Wide_String);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access);
private
HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#);
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#);
type Parser is tagged limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Syntax : Wiki_Syntax_Type;
Document : Wiki.Nodes.Document;
Filters : Wiki.Filters.Filter_Chain;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Token : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List_Type;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wide_Wide_Character);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wide_Wide_String) return Boolean;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type);
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Nodes;
with Wiki.Streams;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
type Parser is tagged limited private;
-- Add the plugin to the wiki engine.
procedure Add_Plugin (Engine : in out Parser;
Name : in String;
Plugin : in Wiki.Plugins.Wiki_Plugin_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wide_Wide_String;
Doc : in out Wiki.Nodes.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Nodes.Document);
private
HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#);
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#);
type Parser is tagged limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Syntax : Wiki_Syntax_Type;
Document : Wiki.Nodes.Document;
Filters : Wiki.Filters.Filter_Chain;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Token : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List_Type;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wide_Wide_Character);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wide_Wide_String) return Boolean;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type);
end Wiki.Parsers;
|
Update the Parse procedure to add the Document as output
|
Update the Parse procedure to add the Document as output
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
bb426c09f13a43e084f7fdde73b136ef8009456e
|
src/asf-lifecycles.adb
|
src/asf-lifecycles.adb
|
-----------------------------------------------------------------------
-- asf-lifecycles -- Lifecycle
-- 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 ASF.Contexts.Exceptions;
package body ASF.Lifecycles is
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Controller : in out Lifecycle;
App : access ASF.Applications.Main.Application'Class) is
begin
-- Create the phase controllers.
Lifecycle'Class (Controller).Create_Phase_Controllers;
-- Initialize the phase controllers.
for Phase in Controller.Controllers'Range loop
Controller.Controllers (Phase).Initialize (App);
end loop;
end Initialize;
-- ------------------------------
-- Finalize the lifecycle handler, freeing the allocated storage.
-- ------------------------------
overriding
procedure Finalize (Controller : in out Lifecycle) is
procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class,
Phase_Controller_Access);
begin
-- Free the phase controllers.
for Phase in Controller.Controllers'Range loop
Free (Controller.Controllers (Phase));
end loop;
end Finalize;
-- ------------------------------
-- Set the controller to be used for the given phase.
-- ------------------------------
procedure Set_Controller (Controller : in out Lifecycle;
Phase : in Phase_Type;
Instance : in Phase_Controller_Access) is
begin
Controller.Controllers (Phase) := Instance;
end Set_Controller;
-- ------------------------------
-- Register a bundle and bind it to a facelet variable.
-- ------------------------------
procedure Execute (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Contexts.Exceptions.Exception_Handler_Access;
use ASF.Events.Phases;
Listeners : constant Listener_Vectors.Ref := Controller.Listeners.Get;
begin
for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop
if Context.Get_Render_Response or Context.Get_Response_Completed then
return;
end if;
declare
procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access);
procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access);
Event : ASF.Events.Phases.Phase_Event (Phase);
procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is
P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase;
begin
if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then
Listener.Before_Phase (Event);
end if;
exception
when E : others =>
Context.Queue_Exception (E);
end Before_Phase;
procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is
P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase;
begin
if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then
Listener.Before_Phase (Event);
end if;
exception
when E : others =>
Context.Queue_Exception (E);
end After_Phase;
begin
Context.Set_Current_Phase (Phase);
-- Call the before phase listeners if there are some.
if not Listeners.Is_Empty then
Listeners.Iterate (Before_Phase'Access);
end if;
begin
Controller.Controllers (Phase).Execute (Context);
exception
when E : others =>
Context.Queue_Exception (E);
end;
if not Listeners.Is_Empty then
Listeners.Iterate (After_Phase'Access);
end if;
-- If exceptions have been raised and queued during the current phase, process them.
-- An exception handler could use them to redirect the current request to another
-- page or navigate to a specific view.
declare
Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access
:= Context.Get_Exception_Handler;
begin
if Ex /= null then
Ex.Handle;
end if;
end;
end;
end loop;
end Execute;
-- ------------------------------
-- Render the response by executing the response phase.
-- ------------------------------
procedure Render (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
Context.Set_Current_Phase (ASF.Events.Phases.RENDER_RESPONSE);
Controller.Controllers (ASF.Events.Phases.RENDER_RESPONSE).Execute (Context);
end Render;
-- ------------------------------
-- Add a phase listener in the lifecycle controller.
-- ------------------------------
procedure Add_Phase_Listener (Controller : in out Lifecycle;
Listener : in ASF.Events.Phases.Phase_Listener_Access) is
begin
Controller.Listeners.Append (Listener);
end Add_Phase_Listener;
end ASF.Lifecycles;
|
-----------------------------------------------------------------------
-- asf-lifecycles -- Lifecycle
-- 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 ASF.Contexts.Exceptions;
package body ASF.Lifecycles is
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Controller : in out Lifecycle;
App : access ASF.Applications.Main.Application'Class) is
begin
-- Create the phase controllers.
Lifecycle'Class (Controller).Create_Phase_Controllers;
-- Initialize the phase controllers.
for Phase in Controller.Controllers'Range loop
Controller.Controllers (Phase).Initialize (App);
end loop;
end Initialize;
-- ------------------------------
-- Finalize the lifecycle handler, freeing the allocated storage.
-- ------------------------------
overriding
procedure Finalize (Controller : in out Lifecycle) is
procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class,
Phase_Controller_Access);
begin
-- Free the phase controllers.
for Phase in Controller.Controllers'Range loop
Free (Controller.Controllers (Phase));
end loop;
end Finalize;
-- ------------------------------
-- Set the controller to be used for the given phase.
-- ------------------------------
procedure Set_Controller (Controller : in out Lifecycle;
Phase : in Phase_Type;
Instance : in Phase_Controller_Access) is
begin
Controller.Controllers (Phase) := Instance;
end Set_Controller;
-- ------------------------------
-- Register a bundle and bind it to a facelet variable.
-- ------------------------------
procedure Execute (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Contexts.Exceptions.Exception_Handler_Access;
use ASF.Events.Phases;
Listeners : constant Listener_Vectors.Ref := Controller.Listeners.Get;
begin
for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop
if Context.Get_Render_Response or Context.Get_Response_Completed then
return;
end if;
declare
procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access);
procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access);
Event : ASF.Events.Phases.Phase_Event (Phase);
procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is
P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase;
begin
if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then
Listener.Before_Phase (Event);
end if;
exception
when E : others =>
Context.Queue_Exception (E);
end Before_Phase;
procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is
P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase;
begin
if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then
Listener.After_Phase (Event);
end if;
exception
when E : others =>
Context.Queue_Exception (E);
end After_Phase;
begin
Context.Set_Current_Phase (Phase);
-- Call the before phase listeners if there are some.
Listeners.Iterate (Before_Phase'Access);
begin
Controller.Controllers (Phase).Execute (Context);
exception
when E : others =>
Context.Queue_Exception (E);
end;
Listeners.Iterate (After_Phase'Access);
-- If exceptions have been raised and queued during the current phase, process them.
-- An exception handler could use them to redirect the current request to another
-- page or navigate to a specific view.
declare
Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access
:= Context.Get_Exception_Handler;
begin
if Ex /= null then
Ex.Handle;
end if;
end;
end;
end loop;
end Execute;
-- ------------------------------
-- Render the response by executing the response phase.
-- ------------------------------
procedure Render (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
Context.Set_Current_Phase (ASF.Events.Phases.RENDER_RESPONSE);
Controller.Controllers (ASF.Events.Phases.RENDER_RESPONSE).Execute (Context);
end Render;
-- ------------------------------
-- Add a phase listener in the lifecycle controller.
-- ------------------------------
procedure Add_Phase_Listener (Controller : in out Lifecycle;
Listener : in ASF.Events.Phases.Phase_Listener_Access) is
begin
Controller.Listeners.Append (Listener);
end Add_Phase_Listener;
end ASF.Lifecycles;
|
Fix call to After_Phase listener
|
Fix call to After_Phase listener
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
2f1cd4819a772b9320a82e09b867ded93c7cfa40
|
src/asf-lifecycles.adb
|
src/asf-lifecycles.adb
|
-----------------------------------------------------------------------
-- asf-lifecycles -- Lifecycle
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ASF.Contexts.Exceptions;
package body ASF.Lifecycles is
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Controller : in out Lifecycle;
App : access ASF.Applications.Main.Application'Class) is
begin
-- Create the phase controllers.
Lifecycle'Class (Controller).Create_Phase_Controllers;
-- Initialize the phase controllers.
for Phase in Controller.Controllers'Range loop
Controller.Controllers (Phase).Initialize (App);
end loop;
end Initialize;
-- ------------------------------
-- Finalize the lifecycle handler, freeing the allocated storage.
-- ------------------------------
overriding
procedure Finalize (Controller : in out Lifecycle) is
procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class,
Phase_Controller_Access);
begin
-- Free the phase controllers.
for Phase in Controller.Controllers'Range loop
Free (Controller.Controllers (Phase));
end loop;
end Finalize;
-- ------------------------------
-- Set the controller to be used for the given phase.
-- ------------------------------
procedure Set_Controller (Controller : in out Lifecycle;
Phase : in Phase_Type;
Instance : in Phase_Controller_Access) is
begin
Controller.Controllers (Phase) := Instance;
end Set_Controller;
-- ------------------------------
-- Register a bundle and bind it to a facelet variable.
-- ------------------------------
procedure Execute (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Contexts.Exceptions.Exception_Handler_Access;
use ASF.Events.Phases;
begin
for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop
if Context.Get_Render_Response or Context.Get_Response_Completed then
return;
end if;
begin
Controller.Controllers (Phase).Execute (Context);
exception
when E : others =>
Context.Queue_Exception (E);
end;
-- If exceptions have been raised and queued during the current phase, process them.
-- An exception handler could use them to redirect the current request to another
-- page or navigate to a specific view.
declare
Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access
:= Context.Get_Exception_Handler;
begin
if Ex /= null then
Ex.Handle;
end if;
end;
end loop;
end Execute;
-- ------------------------------
-- Render the response by executing the response phase.
-- ------------------------------
procedure Render (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
Controller.Controllers (ASF.Events.Phases.RENDER_RESPONSE).Execute (Context);
end Render;
end ASF.Lifecycles;
|
-----------------------------------------------------------------------
-- asf-lifecycles -- Lifecycle
-- 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 ASF.Contexts.Exceptions;
package body ASF.Lifecycles is
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Controller : in out Lifecycle;
App : access ASF.Applications.Main.Application'Class) is
begin
-- Create the phase controllers.
Lifecycle'Class (Controller).Create_Phase_Controllers;
-- Initialize the phase controllers.
for Phase in Controller.Controllers'Range loop
Controller.Controllers (Phase).Initialize (App);
end loop;
end Initialize;
-- ------------------------------
-- Finalize the lifecycle handler, freeing the allocated storage.
-- ------------------------------
overriding
procedure Finalize (Controller : in out Lifecycle) is
procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class,
Phase_Controller_Access);
begin
-- Free the phase controllers.
for Phase in Controller.Controllers'Range loop
Free (Controller.Controllers (Phase));
end loop;
end Finalize;
-- ------------------------------
-- Set the controller to be used for the given phase.
-- ------------------------------
procedure Set_Controller (Controller : in out Lifecycle;
Phase : in Phase_Type;
Instance : in Phase_Controller_Access) is
begin
Controller.Controllers (Phase) := Instance;
end Set_Controller;
-- ------------------------------
-- Register a bundle and bind it to a facelet variable.
-- ------------------------------
procedure Execute (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Contexts.Exceptions.Exception_Handler_Access;
use ASF.Events.Phases;
begin
for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop
if Context.Get_Render_Response or Context.Get_Response_Completed then
return;
end if;
begin
Context.Set_Current_Phase (Phase);
Controller.Controllers (Phase).Execute (Context);
exception
when E : others =>
Context.Queue_Exception (E);
end;
-- If exceptions have been raised and queued during the current phase, process them.
-- An exception handler could use them to redirect the current request to another
-- page or navigate to a specific view.
declare
Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access
:= Context.Get_Exception_Handler;
begin
if Ex /= null then
Ex.Handle;
end if;
end;
end loop;
end Execute;
-- ------------------------------
-- Render the response by executing the response phase.
-- ------------------------------
procedure Render (Controller : in Lifecycle;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
Context.Set_Current_Phase (ASF.Events.Phases.RENDER_RESPONSE);
Controller.Controllers (ASF.Events.Phases.RENDER_RESPONSE).Execute (Context);
end Render;
end ASF.Lifecycles;
|
Set the lifecycle phase in the faces context before executing each lifecycle operation
|
Set the lifecycle phase in the faces context before executing each
lifecycle operation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
c020e18559f0174198295461e7eb62d100273c96
|
src/core/util-refs.adb
|
src/core/util-refs.adb
|
-----------------------------------------------------------------------
-- util-refs -- Reference Counting
-- Copyright (C) 2010, 2011, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Refs is
package body Indefinite_References is
-- ------------------------------
-- Create an element and return a reference to that element.
-- ------------------------------
function Create (Value : in Element_Access) return Ref is
begin
return Result : Ref do
Result.Target := Value;
Util.Concurrent.Counters.Increment (Result.Target.Ref_Counter);
end return;
end Create;
-- ------------------------------
-- Get the element access value.
-- ------------------------------
function Value (Object : in Ref'Class) return Element_Access is
begin
return Object.Target;
end Value;
-- ------------------------------
-- Returns true if the reference does not contain any element.
-- ------------------------------
function Is_Null (Object : in Ref'Class) return Boolean is
begin
return Object.Target = null;
end Is_Null;
protected body Atomic_Ref is
-- ------------------------------
-- Get the reference
-- ------------------------------
function Get return Ref is
begin
return Value;
end Get;
-- ------------------------------
-- Change the reference
-- ------------------------------
procedure Set (Object : in Ref) is
begin
Value := Object;
end Set;
end Atomic_Ref;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Element_Type,
Name => Element_Access);
-- ------------------------------
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Ref) is
Release : Boolean;
begin
if Obj.Target /= null then
Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release);
if Release then
Obj.Target.Finalize;
Free (Obj.Target);
else
Obj.Target := null;
end if;
end if;
end Finalize;
-- ------------------------------
-- Update the reference counter after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Ref) is
begin
if Obj.Target /= null then
Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter);
end if;
end Adjust;
end Indefinite_References;
package body References is
-- ------------------------------
-- Create an element and return a reference to that element.
-- ------------------------------
function Create return Ref is
begin
return IR.Create (new Element_Type);
end Create;
end References;
package body General_References is
-- ------------------------------
-- Create an element and return a reference to that element.
-- ------------------------------
function Create return Ref is
begin
return Result : Ref do
Result.Target := new Ref_Data;
Util.Concurrent.Counters.Increment (Result.Target.Ref_Counter);
end return;
end Create;
-- ------------------------------
-- Get the element access value.
-- ------------------------------
function Value (Object : in Ref'Class) return access Element_Type is
begin
if Object.Target /= null then
return Object.Target.Data'Access;
else
raise Constraint_Error;
end if;
end Value;
-- ------------------------------
-- Returns true if the reference does not contain any element.
-- ------------------------------
function Is_Null (Object : in Ref'Class) return Boolean is
begin
return Object.Target = null;
end Is_Null;
protected body Atomic_Ref is
-- ------------------------------
-- Get the reference
-- ------------------------------
function Get return Ref is
begin
return Value;
end Get;
-- ------------------------------
-- Change the reference
-- ------------------------------
procedure Set (Object : in Ref) is
begin
Value := Object;
end Set;
end Atomic_Ref;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Ref_Data,
Name => Ref_Data_Access);
-- ------------------------------
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Ref) is
Release : Boolean;
begin
if Obj.Target /= null then
Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release);
if Release then
Finalize (Obj.Target.Data);
Free (Obj.Target);
else
Obj.Target := null;
end if;
end if;
end Finalize;
-- ------------------------------
-- Update the reference counter after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Ref) is
begin
if Obj.Target /= null then
Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter);
end if;
end Adjust;
end General_References;
end Util.Refs;
|
-----------------------------------------------------------------------
-- util-refs -- Reference Counting
-- Copyright (C) 2010, 2011, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Refs is
package body Indefinite_References is
-- ------------------------------
-- Create an element and return a reference to that element.
-- ------------------------------
function Create (Value : in Element_Access) return Ref is
begin
return Result : Ref do
Result.Target := Value;
Util.Concurrent.Counters.Increment (Result.Target.Ref_Counter);
end return;
end Create;
-- ------------------------------
-- Get the element access value.
-- ------------------------------
function Value (Object : in Ref'Class) return Element_Accessor is
begin
return Element_Accessor '(Element => Object.Target);
end Value;
-- ------------------------------
-- Returns true if the reference does not contain any element.
-- ------------------------------
function Is_Null (Object : in Ref'Class) return Boolean is
begin
return Object.Target = null;
end Is_Null;
function "=" (Left, Right : in Ref'Class) return Boolean is
begin
return Left.Target = Right.Target;
end "=";
package body Atomic is
protected body Atomic_Ref is
-- ------------------------------
-- Get the reference
-- ------------------------------
function Get return Ref is
begin
return Value;
end Get;
-- ------------------------------
-- Change the reference
-- ------------------------------
procedure Set (Object : in Ref) is
begin
Value := Object;
end Set;
end Atomic_Ref;
end Atomic;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Element_Type,
Name => Element_Access);
-- ------------------------------
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Ref) is
Release : Boolean;
begin
if Obj.Target /= null then
Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release);
if Release then
Obj.Target.Finalize;
Free (Obj.Target);
else
Obj.Target := null;
end if;
end if;
end Finalize;
-- ------------------------------
-- Update the reference counter after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Ref) is
begin
if Obj.Target /= null then
Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter);
end if;
end Adjust;
end Indefinite_References;
package body References is
-- ------------------------------
-- Create an element and return a reference to that element.
-- ------------------------------
function Create return Ref is
begin
return IR.Create (new Element_Type);
end Create;
end References;
package body General_References is
-- ------------------------------
-- Create an element and return a reference to that element.
-- ------------------------------
function Create return Ref is
begin
return Result : Ref do
Result.Target := new Ref_Data;
Util.Concurrent.Counters.Increment (Result.Target.Ref_Counter);
end return;
end Create;
-- ------------------------------
-- Get the element access value.
-- ------------------------------
function Value (Object : in Ref'Class) return Element_Accessor is
begin
if Object.Target /= null then
return Element_Accessor '(Element => Object.Target.Data'Access);
else
raise Constraint_Error;
end if;
end Value;
-- ------------------------------
-- Returns true if the reference does not contain any element.
-- ------------------------------
function Is_Null (Object : in Ref'Class) return Boolean is
begin
return Object.Target = null;
end Is_Null;
function "=" (Left, Right : in Ref'Class) return Boolean is
begin
return Left.Target = Right.Target;
end "=";
package body Atomic is
protected body Atomic_Ref is
-- ------------------------------
-- Get the reference
-- ------------------------------
function Get return Ref is
begin
return Value;
end Get;
-- ------------------------------
-- Change the reference
-- ------------------------------
procedure Set (Object : in Ref) is
begin
Value := Object;
end Set;
end Atomic_Ref;
end Atomic;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Ref_Data,
Name => Ref_Data_Access);
-- ------------------------------
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Ref) is
Release : Boolean;
begin
if Obj.Target /= null then
Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release);
if Release then
Finalize (Obj.Target.Data);
Free (Obj.Target);
else
Obj.Target := null;
end if;
end if;
end Finalize;
-- ------------------------------
-- Update the reference counter after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Ref) is
begin
if Obj.Target /= null then
Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter);
end if;
end Adjust;
end General_References;
end Util.Refs;
|
Refactor references to use Implicit_Dereference aspect
|
Refactor references to use Implicit_Dereference aspect
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
975223a03cbdbd528fa85b840781ed7b19653cfb
|
src/http/util-mail.ads
|
src/http/util-mail.ads
|
-----------------------------------------------------------------------
-- util-mail -- Mail Utility Library
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Introduction ==
-- The <tt>Util.Mail</tt> package provides various operations related to sending email.
package Util.Mail is
type Email_Address is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Address : Ada.Strings.Unbounded.Unbounded_String;
end record;
-- Parse the email address and separate the name from the address.
function Parse_Address (E_Mail : in String) return Email_Address;
end Util.Mail;
|
-----------------------------------------------------------------------
-- util-mail -- Mail Utility Library
-- 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 Ada.Strings.Unbounded;
-- == Introduction ==
-- The <tt>Util.Mail</tt> package provides various operations related to sending email.
package Util.Mail is
type Email_Address is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Address : Ada.Strings.Unbounded.Unbounded_String;
end record;
-- Parse the email address and separate the name from the address.
function Parse_Address (E_Mail : in String) return Email_Address;
-- Extract a first name from the email address.
function Get_First_Name (From : in Email_Address) return String;
end Util.Mail;
|
Declare the Get_First_Name function
|
Declare the Get_First_Name function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
5c33cc57277ccdddff6aff52d73e135a0c07a96a
|
src/natools-web-comment_cookies.adb
|
src/natools-web-comment_cookies.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Parsers;
with Natools.S_Expressions.Printers.Pretty;
package body Natools.Web.Comment_Cookies is
Parameters : constant Natools.S_Expressions.Printers.Pretty.Parameters
:= (Width => 0,
Newline_At => (others => (others => False)),
Space_At => (others => (others => False)),
Tab_Stop => <>,
Indentation => 0,
Indent => <>,
Quoted => S_Expressions.Printers.Pretty.No_Quoted,
Token => S_Expressions.Printers.Pretty.Extended_Token,
Hex_Casing => <>,
Quoted_Escape => <>,
Char_Encoding => <>,
Fallback => S_Expressions.Printers.Pretty.Verbatim,
Newline => S_Expressions.Printers.Pretty.LF);
function Create (A : S_Expressions.Atom)
return S_Expressions.Atom_Refs.Immutable_Reference
renames S_Expressions.Atom_Ref_Constructors.Create;
procedure Set_Atom
(Info : in out Comment_Info;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
function To_Atom (Kind : in Atom_Kind) return S_Expressions.Atom;
procedure Initialize is new S_Expressions.Interpreter_Loop
(Comment_Info, Meaningless_Type, Set_Atom);
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Set_Atom
(Info : in out Comment_Info;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use type S_Expressions.Events.Event;
Kind : Atom_Kind;
begin
if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then
return;
end if;
declare
S_Name : constant String := S_Expressions.To_String (Name);
begin
Kind := Atom_Kind'Value (S_Name);
exception
when Constraint_Error =>
Log (Severities.Error, "Unknown comment atom kind """
& S_Name & '"');
end;
Info.Refs (Kind) := Create (Arguments.Current_Atom);
end Set_Atom;
function To_Atom (Kind : in Atom_Kind) return S_Expressions.Atom is
begin
case Kind is
when Name =>
return (Character'Pos ('N'), Character'Pos ('a'),
Character'Pos ('m'), Character'Pos ('e'));
when Mail =>
return (Character'Pos ('M'), Character'Pos ('a'),
Character'Pos ('i'), Character'Pos ('l'));
when Link =>
return (Character'Pos ('L'), Character'Pos ('n'),
Character'Pos ('n'), Character'Pos ('k'));
when Filter =>
return (Character'Pos ('F'), Character'Pos ('i'),
Character'Pos ('l'), Character'Pos ('t'),
Character'Pos ('e'), Character'Pos ('r'));
end case;
end To_Atom;
-----------------------------------
-- Comment Info Public Interface --
-----------------------------------
function Create
(Name : in S_Expressions.Atom_Refs.Immutable_Reference;
Mail : in S_Expressions.Atom_Refs.Immutable_Reference;
Link : in S_Expressions.Atom_Refs.Immutable_Reference;
Filter : in S_Expressions.Atom_Refs.Immutable_Reference)
return Comment_Info is
begin
return (Refs =>
(Comment_Cookies.Name => Name,
Comment_Cookies.Mail => Mail,
Comment_Cookies.Link => Link,
Comment_Cookies.Filter => Filter));
end Create;
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Comment_Info
is
use type S_Expressions.Events.Event;
Result : Comment_Info := Null_Info;
Event : S_Expressions.Events.Event;
begin
case Expression.Current_Event is
when S_Expressions.Events.Add_Atom =>
for Kind in Result.Refs'Range loop
Result.Refs (Kind) := Create (Expression.Current_Atom);
Expression.Next (Event);
exit when Event /= S_Expressions.Events.Add_Atom;
end loop;
when S_Expressions.Events.Open_List =>
Initialize (Expression, Result, Meaningless_Value);
when S_Expressions.Events.Close_List
| S_Expressions.Events.End_Of_Input
| S_Expressions.Events.Error
=>
null;
end case;
return Result;
end Create;
function Named_Serialization (Info : in Comment_Info)
return S_Expressions.Atom
is
Buffer : aliased S_Expressions.Atom_Buffers.Atom_Buffer;
Printer : S_Expressions.Printers.Pretty.Stream_Printer (Buffer'Access);
begin
Printer.Set_Parameters (Parameters);
Buffer.Preallocate (120);
for Kind in Atom_Kind loop
if not Info.Refs (Kind).Is_Empty then
Printer.Open_List;
Printer.Append_Atom (To_Atom (Kind));
Printer.Append_Atom (Info.Refs (Kind).Query);
Printer.Close_List;
end if;
end loop;
return Buffer.Data;
end Named_Serialization;
function Positional_Serialization (Info : in Comment_Info)
return S_Expressions.Atom
is
Buffer : aliased S_Expressions.Atom_Buffers.Atom_Buffer;
Printer : S_Expressions.Printers.Pretty.Stream_Printer (Buffer'Access);
Last : Atom_Kind;
begin
Printer.Set_Parameters (Parameters);
Buffer.Preallocate (120);
Last := Atom_Kind'Last;
while Info.Refs (Last).Is_Empty loop
if Last = Atom_Kind'First then
return S_Expressions.Null_Atom;
else
Last := Atom_Kind'Pred (Last);
end if;
end loop;
for Kind in Atom_Kind'First .. Last loop
if Info.Refs (Kind).Is_Empty then
Printer.Append_Atom (S_Expressions.Null_Atom);
else
Printer.Append_Atom (Info.Refs (Kind).Query);
end if;
end loop;
return Buffer.Data;
end Positional_Serialization;
-------------------------------
-- Codec DB Public Interface --
-------------------------------
function Decode
(DB : in Codec_DB;
Cookie : in String)
return Comment_Info
is
Cursor : Decoder_Maps.Cursor;
begin
if Cookie'Length = 0 then
return Null_Info;
end if;
Cursor := DB.Dec.Find (Cookie (Cookie'First));
if not Decoder_Maps.Has_Element (Cursor) then
return Null_Info;
end if;
declare
use type S_Expressions.Atom;
Parser : S_Expressions.Parsers.Memory_Parser
:= S_Expressions.Parsers.Create
(Decoder_Maps.Element (Cursor).all (Cookie) & (1 => 0));
begin
Parser.Next;
return Create (Parser);
end;
end Decode;
function Encode
(DB : in Codec_DB;
Info : in Comment_Info)
return String is
begin
if DB.Enc = null then
raise Program_Error
with "Comment_Cookie.Encode called before Set_Encoder";
end if;
case DB.Serialization is
when Named =>
return DB.Enc.all (Named_Serialization (Info));
when Positional =>
return DB.Enc.all (Positional_Serialization (Info));
end case;
end Encode;
procedure Register
(DB : in out Codec_DB;
Key : in Character;
Filter : in not null Decoder) is
begin
DB.Dec := Decoder_Maps.Include (DB.Dec, Key, Filter);
end Register;
procedure Set_Encoder
(DB : in out Codec_DB;
Filter : in not null Encoder;
Serialization : in Serialization_Kind) is
begin
DB.Enc := Filter;
DB.Serialization := Serialization;
end Set_Encoder;
end Natools.Web.Comment_Cookies;
|
------------------------------------------------------------------------------
-- Copyright (c) 2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Encodings;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Parsers;
with Natools.S_Expressions.Printers.Pretty;
package body Natools.Web.Comment_Cookies is
Parameters : constant Natools.S_Expressions.Printers.Pretty.Parameters
:= (Width => 0,
Newline_At => (others => (others => False)),
Space_At => (others => (others => False)),
Tab_Stop => <>,
Indentation => 0,
Indent => <>,
Quoted => S_Expressions.Printers.Pretty.When_Shorter,
Token => S_Expressions.Printers.Pretty.Extended_Token,
Hex_Casing => S_Expressions.Encodings.Lower,
Quoted_Escape => S_Expressions.Printers.Pretty.Hex_Escape,
Char_Encoding => S_Expressions.Printers.Pretty.Latin,
Fallback => S_Expressions.Printers.Pretty.Verbatim,
Newline => S_Expressions.Printers.Pretty.LF);
function Create (A : S_Expressions.Atom)
return S_Expressions.Atom_Refs.Immutable_Reference
renames S_Expressions.Atom_Ref_Constructors.Create;
procedure Set_Atom
(Info : in out Comment_Info;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
function To_Atom (Kind : in Atom_Kind) return S_Expressions.Atom;
procedure Initialize is new S_Expressions.Interpreter_Loop
(Comment_Info, Meaningless_Type, Set_Atom);
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Set_Atom
(Info : in out Comment_Info;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use type S_Expressions.Events.Event;
Kind : Atom_Kind;
begin
if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then
return;
end if;
declare
S_Name : constant String := S_Expressions.To_String (Name);
begin
Kind := Atom_Kind'Value (S_Name);
exception
when Constraint_Error =>
Log (Severities.Error, "Unknown comment atom kind """
& S_Name & '"');
end;
Info.Refs (Kind) := Create (Arguments.Current_Atom);
end Set_Atom;
function To_Atom (Kind : in Atom_Kind) return S_Expressions.Atom is
begin
case Kind is
when Name =>
return (Character'Pos ('N'), Character'Pos ('a'),
Character'Pos ('m'), Character'Pos ('e'));
when Mail =>
return (Character'Pos ('M'), Character'Pos ('a'),
Character'Pos ('i'), Character'Pos ('l'));
when Link =>
return (Character'Pos ('L'), Character'Pos ('n'),
Character'Pos ('n'), Character'Pos ('k'));
when Filter =>
return (Character'Pos ('F'), Character'Pos ('i'),
Character'Pos ('l'), Character'Pos ('t'),
Character'Pos ('e'), Character'Pos ('r'));
end case;
end To_Atom;
-----------------------------------
-- Comment Info Public Interface --
-----------------------------------
function Create
(Name : in S_Expressions.Atom_Refs.Immutable_Reference;
Mail : in S_Expressions.Atom_Refs.Immutable_Reference;
Link : in S_Expressions.Atom_Refs.Immutable_Reference;
Filter : in S_Expressions.Atom_Refs.Immutable_Reference)
return Comment_Info is
begin
return (Refs =>
(Comment_Cookies.Name => Name,
Comment_Cookies.Mail => Mail,
Comment_Cookies.Link => Link,
Comment_Cookies.Filter => Filter));
end Create;
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Comment_Info
is
use type S_Expressions.Events.Event;
Result : Comment_Info := Null_Info;
Event : S_Expressions.Events.Event;
begin
case Expression.Current_Event is
when S_Expressions.Events.Add_Atom =>
for Kind in Result.Refs'Range loop
Result.Refs (Kind) := Create (Expression.Current_Atom);
Expression.Next (Event);
exit when Event /= S_Expressions.Events.Add_Atom;
end loop;
when S_Expressions.Events.Open_List =>
Initialize (Expression, Result, Meaningless_Value);
when S_Expressions.Events.Close_List
| S_Expressions.Events.End_Of_Input
| S_Expressions.Events.Error
=>
null;
end case;
return Result;
end Create;
function Named_Serialization (Info : in Comment_Info)
return S_Expressions.Atom
is
Buffer : aliased S_Expressions.Atom_Buffers.Atom_Buffer;
Printer : S_Expressions.Printers.Pretty.Stream_Printer (Buffer'Access);
begin
Printer.Set_Parameters (Parameters);
Buffer.Preallocate (120);
for Kind in Atom_Kind loop
if not Info.Refs (Kind).Is_Empty then
Printer.Open_List;
Printer.Append_Atom (To_Atom (Kind));
Printer.Append_Atom (Info.Refs (Kind).Query);
Printer.Close_List;
end if;
end loop;
return Buffer.Data;
end Named_Serialization;
function Positional_Serialization (Info : in Comment_Info)
return S_Expressions.Atom
is
Buffer : aliased S_Expressions.Atom_Buffers.Atom_Buffer;
Printer : S_Expressions.Printers.Pretty.Stream_Printer (Buffer'Access);
Last : Atom_Kind;
begin
Printer.Set_Parameters (Parameters);
Buffer.Preallocate (120);
Last := Atom_Kind'Last;
while Info.Refs (Last).Is_Empty loop
if Last = Atom_Kind'First then
return S_Expressions.Null_Atom;
else
Last := Atom_Kind'Pred (Last);
end if;
end loop;
for Kind in Atom_Kind'First .. Last loop
if Info.Refs (Kind).Is_Empty then
Printer.Append_Atom (S_Expressions.Null_Atom);
else
Printer.Append_Atom (Info.Refs (Kind).Query);
end if;
end loop;
return Buffer.Data;
end Positional_Serialization;
-------------------------------
-- Codec DB Public Interface --
-------------------------------
function Decode
(DB : in Codec_DB;
Cookie : in String)
return Comment_Info
is
Cursor : Decoder_Maps.Cursor;
begin
if Cookie'Length = 0 then
return Null_Info;
end if;
Cursor := DB.Dec.Find (Cookie (Cookie'First));
if not Decoder_Maps.Has_Element (Cursor) then
return Null_Info;
end if;
declare
use type S_Expressions.Atom;
Parser : S_Expressions.Parsers.Memory_Parser
:= S_Expressions.Parsers.Create
(Decoder_Maps.Element (Cursor).all (Cookie) & (1 => 0));
begin
Parser.Next;
return Create (Parser);
end;
end Decode;
function Encode
(DB : in Codec_DB;
Info : in Comment_Info)
return String is
begin
if DB.Enc = null then
raise Program_Error
with "Comment_Cookie.Encode called before Set_Encoder";
end if;
case DB.Serialization is
when Named =>
return DB.Enc.all (Named_Serialization (Info));
when Positional =>
return DB.Enc.all (Positional_Serialization (Info));
end case;
end Encode;
procedure Register
(DB : in out Codec_DB;
Key : in Character;
Filter : in not null Decoder) is
begin
DB.Dec := Decoder_Maps.Include (DB.Dec, Key, Filter);
end Register;
procedure Set_Encoder
(DB : in out Codec_DB;
Filter : in not null Encoder;
Serialization : in Serialization_Kind) is
begin
DB.Enc := Filter;
DB.Serialization := Serialization;
end Set_Encoder;
end Natools.Web.Comment_Cookies;
|
improve the printer for (hopefully) smaller cookies
|
comment_cookies: improve the printer for (hopefully) smaller cookies
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
0cb4071cbaa8acbd2ef216826bc7067c2f7daf9a
|
awa/src/awa-audits-services.adb
|
awa/src/awa-audits-services.adb
|
-----------------------------------------------------------------------
-- 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.Calendar;
with Ada.Strings.Hash;
with Util.Strings;
with Util.Beans.Objects;
with Util.Log.Loggers;
with ADO.Objects;
with ADO.Schemas;
with ADO.Sessions.Entities;
with AWA.Audits.Models;
with AWA.Services.Contexts;
package body AWA.Audits.Services is
package ASC renames AWA.Services.Contexts;
package UBO renames Util.Beans.Objects;
use type ASC.Service_Context_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Audits.Services");
function Hash (Item : in Field_Key) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
begin
return Ada.Containers.Hash_Type (Item.Entity) + Ada.Strings.Hash (Item.Name);
end Hash;
-- ------------------------------
-- 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) is
Context : constant ASC.Service_Context_Access := ASC.Current;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Class : constant ADO.Schemas.Class_Mapping_Access
:= Object.Get_Key.Of_Class;
Kind : constant ADO.Entity_Type
:= ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key);
begin
for C of Changes loop
declare
Audit : AWA.Audits.Models.Audit_Ref;
Field : constant Util.Strings.Name_Access := Class.Members (C.Field);
begin
Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key));
Audit.Set_Entity_Type (Kind);
Audit.Set_Field (Manager.Get_Audit_Field (Field.all, Kind));
if UBO.Is_Null (C.Old_Value) then
Audit.Set_Old_Value (ADO.Null_String);
else
Audit.Set_Old_Value (UBO.To_String (C.Old_Value));
end if;
if UBO.Is_Null (C.New_Value) then
Audit.Set_New_Value (ADO.Null_String);
else
Audit.Set_New_Value (UBO.To_String (C.New_Value));
end if;
Audit.Set_Date (Now);
if Context /= null then
Audit.Set_Session (Context.Get_User_Session);
end if;
Audit.Save (Session);
end;
end loop;
end Save;
-- ------------------------------
-- 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 is
Key : constant Field_Key := Field_Key '(Len => Name'Length,
Name => Name,
Entity => Entity);
Pos : constant Audit_Field_Maps.Cursor := Manager.Fields.Find (Key);
begin
if Audit_Field_Maps.Has_Element (Pos) then
return Audit_Field_Maps.Element (Pos);
else
Log.Warn ("Audit field {0} for {1} not found", Name, ADO.Entity_Type'Image (Entity));
return ADO.NO_IDENTIFIER;
end if;
end Get_Audit_Field;
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.Calendar;
with Ada.Strings.Hash;
with Util.Strings;
with Util.Beans.Objects;
with Util.Log.Loggers;
with ADO.Objects;
with ADO.Schemas;
with ADO.Statements;
with ADO.Sessions.Entities;
with AWA.Audits.Models;
with AWA.Services.Contexts;
package body AWA.Audits.Services is
package ASC renames AWA.Services.Contexts;
package UBO renames Util.Beans.Objects;
use type ASC.Service_Context_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Audits.Services");
function Hash (Item : in Field_Key) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
begin
return Ada.Containers.Hash_Type (Item.Entity) + Ada.Strings.Hash (Item.Name);
end Hash;
-- ------------------------------
-- 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) is
Context : constant ASC.Service_Context_Access := ASC.Current;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Class : constant ADO.Schemas.Class_Mapping_Access
:= Object.Get_Key.Of_Class;
Kind : constant ADO.Entity_Type
:= ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key);
begin
for C of Changes loop
declare
Audit : AWA.Audits.Models.Audit_Ref;
Field : constant Util.Strings.Name_Access := Class.Members (C.Field);
begin
Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key));
Audit.Set_Entity_Type (Kind);
Audit.Set_Field (Manager.Get_Audit_Field (Field.all, Kind));
if UBO.Is_Null (C.Old_Value) then
Audit.Set_Old_Value (ADO.Null_String);
else
Audit.Set_Old_Value (UBO.To_String (C.Old_Value));
end if;
if UBO.Is_Null (C.New_Value) then
Audit.Set_New_Value (ADO.Null_String);
else
Audit.Set_New_Value (UBO.To_String (C.New_Value));
end if;
Audit.Set_Date (Now);
if Context /= null then
Audit.Set_Session (Context.Get_User_Session);
end if;
Audit.Save (Session);
end;
end loop;
end Save;
-- ------------------------------
-- 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 is
Key : constant Field_Key := Field_Key '(Len => Name'Length,
Name => Name,
Entity => Entity);
Pos : constant Audit_Field_Maps.Cursor := Manager.Fields.Find (Key);
begin
if Audit_Field_Maps.Has_Element (Pos) then
return Audit_Field_Maps.Element (Pos);
else
Log.Warn ("Audit field {0} for{1} not found", Name, ADO.Entity_Type'Image (Entity));
return 0;
end if;
end Get_Audit_Field;
-- ------------------------------
-- Initialize the audit manager.
-- ------------------------------
procedure Initialize (Manager : in out Audit_Manager;
App : in Application_Access) is
DB : constant ADO.Sessions.Session := App.Get_Session;
Stmt : ADO.Statements.Query_Statement
:= DB.Create_Statement ("SELECT id, entity_type, name FROM awa_audit_field");
Count : Natural := 0;
begin
Stmt.Execute;
while Stmt.Has_Elements loop
declare
Id : constant Integer := Stmt.Get_Integer (0);
Kind : constant ADO.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (1));
Name : constant String := Stmt.Get_String (2);
begin
Log.Debug ("Field {0} of{1} ={2}",
Name, ADO.Entity_Type'Image (Kind), Integer'Image (Id));
Manager.Fields.Insert (Key => (Len => Name'Length, Name => Name, Entity => Kind),
New_Item => Id);
end;
Count := Count + 1;
Stmt.Next;
end loop;
Log.Info ("Loaded{0} audit fields", Natural'Image (Count));
end Initialize;
end AWA.Audits.Services;
|
Implement the Initialize procedure to load the audit fields
|
Implement the Initialize procedure to load the audit fields
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
822f1cb66d6b75531cb730a6d8b154666353b6da
|
regtests/systems/util-systems-os-tests.adb
|
regtests/systems/util-systems-os-tests.adb
|
-----------------------------------------------------------------------
-- util-systems-os-tests -- Unit tests for OS specific operations
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
with Util.Systems.Types;
with Interfaces.C.Strings;
package body Util.Systems.OS.Tests is
package Caller is new Util.Test_Caller (Test, "Systems.OS");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Systems.Os.Sys_Stat (File)",
Test_Stat'Access);
Caller.Add_Test (Suite, "Test Util.Systems.Os.Sys_Stat (Directory)",
Test_Stat_Directory'Access);
end Add_Tests;
-- ------------------------------
-- Test the Sys_Stat operation.
-- ------------------------------
procedure Test_Stat (T : in out Test) is
use Interfaces.C;
use Util.Systems.Types;
Info : array (1 .. 2) of aliased Util.Systems.Types.Stat_Type;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/test-1.json");
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
Res : Integer;
begin
Info (2).st_dev := 16#12345678#;
Res := Sys_Stat (Name, Info (1)'Unchecked_Access);
T.Assert (Res = 0, "Sys_Stat must return 0");
T.Assert (Info (1).st_size > 0, "Sys_Stat must return the correct size");
T.Assert (Info (2).St_Dev = 16#12345678#, "Suspecting invalid size for Stat_Type");
T.Assert (Info (1).St_Size = off_t (Ada.Directories.Size (Path)),
"Invalid size returned by Sys_Stat");
T.Assert ((Info (1).St_Mode and S_IFMT) = S_IFREG, "st_mode must indicate a regular file");
Interfaces.C.Strings.Free (Name);
end Test_Stat;
-- ------------------------------
-- Test the Sys_Stat operation.
-- ------------------------------
procedure Test_Stat_Directory (T : in out Test) is
use Interfaces.C;
use Util.Systems.Types;
Stat : aliased Util.Systems.Types.Stat_Type;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files");
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
Res : Integer;
begin
Res := Sys_Stat (Name, Stat'Unchecked_Access);
T.Assert (Res = 0, "Sys_Stat must return 0");
T.Assert ((Stat.St_Mode and S_IFMT) = S_IFDIR, "st_mode must indicate a directory");
Interfaces.C.Strings.Free (Name);
end Test_Stat_Directory;
end Util.Systems.OS.Tests;
|
-----------------------------------------------------------------------
-- util-systems-os-tests -- Unit tests for OS specific operations
-- 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.Directories;
with Util.Test_Caller;
with Util.Systems.Types;
with Interfaces.C.Strings;
package body Util.Systems.Os.Tests is
package Caller is new Util.Test_Caller (Test, "Systems.OS");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Systems.Os.Sys_Stat (File)",
Test_Stat'Access);
Caller.Add_Test (Suite, "Test Util.Systems.Os.Sys_Stat (Directory)",
Test_Stat_Directory'Access);
end Add_Tests;
-- ------------------------------
-- Test the Sys_Stat operation.
-- ------------------------------
procedure Test_Stat (T : in out Test) is
use Interfaces.C;
use Util.Systems.Types;
Info : array (1 .. 2) of aliased Util.Systems.Types.Stat_Type;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/test-1.json");
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
Res : Integer;
begin
Info (2).st_dev := 16#12345678#;
Res := Sys_Stat (Name, Info (1)'Unchecked_Access);
T.Assert (Res = 0, "Sys_Stat must return 0");
T.Assert (Info (1).st_size > 0, "Sys_Stat must return the correct size");
T.Assert (Info (2).st_dev = 16#12345678#, "Suspecting invalid size for Stat_Type");
T.Assert (Info (1).st_size = off_t (Ada.Directories.Size (Path)),
"Invalid size returned by Sys_Stat");
T.Assert ((Info (1).st_mode and S_IFMT) = S_IFREG, "st_mode must indicate a regular file");
Interfaces.C.Strings.Free (Name);
end Test_Stat;
-- ------------------------------
-- Test the Sys_Stat operation.
-- ------------------------------
procedure Test_Stat_Directory (T : in out Test) is
use Interfaces.C;
use Util.Systems.Types;
Stat : aliased Util.Systems.Types.Stat_Type;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files");
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
Res : Integer;
begin
Res := Sys_Stat (Name, Stat'Unchecked_Access);
T.Assert (Res = 0, "Sys_Stat must return 0");
T.Assert ((Stat.st_mode and S_IFMT) = S_IFDIR, "st_mode must indicate a directory");
Interfaces.C.Strings.Free (Name);
end Test_Stat_Directory;
end Util.Systems.Os.Tests;
|
Fix style warning
|
Fix style warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
87e9a2da4ecc2cdec27d2aa5da468ff6e6b5bd45
|
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 ADO.Queries;
with ADO.Statements;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Tags.Models;
package body AWA.Tags.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Tag_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (Integer (From.List.Length));
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out 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;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Tag_List_Bean) return Natural is
begin
return Natural (From.List.Length);
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Tag_List_Bean;
Index : in Natural) is
begin
From.Current := Index;
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Tag_List_Bean) return Util.Beans.Objects.Object is
begin
return From.List.Element (From.Current);
end Get_Row;
-- ------------------------------
-- 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;
-- Session : constant ADO.Sessions.Session := Into.Module.Get_Session;
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;
-- ------------------------------
-- 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;
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 ADO.Queries;
with ADO.Statements;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Tags.Models;
package body AWA.Tags.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Tag_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (Integer (From.List.Length));
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out 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;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Tag_List_Bean) return Natural is
begin
return Natural (From.List.Length);
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Tag_List_Bean;
Index : in Natural) is
begin
From.Current := Index;
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Tag_List_Bean) return Util.Beans.Objects.Object is
begin
return From.List.Element (From.Current);
end Get_Row;
-- ------------------------------
-- 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;
-- ------------------------------
-- 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;
-- Session : constant ADO.Sessions.Session := Into.Module.Get_Session;
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;
-- ------------------------------
-- 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;
end AWA.Tags.Beans;
|
Implement the Set_Entity_Type procedure
|
Implement the Set_Entity_Type procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
39ef46b0f95968573e38afe4a4750ec12f1b4af8
|
awa/src/awa-permissions-services.ads
|
awa/src/awa-permissions-services.ads
|
-----------------------------------------------------------------------
-- awa-permissions-services -- Permissions controller
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Applications;
with Util.Beans.Objects;
with EL.Functions;
with ADO;
with ADO.Sessions;
with ADO.Objects;
with Security.Policies;
with Security.Contexts;
package AWA.Permissions.Services is
-- Register the security EL functions in the EL mapper.
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
type Permission_Manager is new Security.Policies.Policy_Manager with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
-- Get the permission manager associated with the security context.
-- Returns null if there is none.
function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class)
return Permission_Manager_Access;
-- Get the application instance.
function Get_Application (Manager : in Permission_Manager)
return AWA.Applications.Application_Access;
-- Set the application instance.
procedure Set_Application (Manager : in out Permission_Manager;
App : in AWA.Applications.Application_Access);
-- Add a permission for the current user to access the entity identified by
-- <b>Entity</b> and <b>Kind</b>.
procedure Add_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type);
-- Check that the current user has the specified permission.
-- Raise NO_PERMISSION exception if the user does not have the permission.
procedure Check_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type);
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b> which is of type <b>Kind</b>.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type := READ);
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b>.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Objects.Object_Ref'Class;
Permission : in Permission_Type := READ);
-- Create a permission manager for the given application.
function Create_Permission_Manager (App : in AWA.Applications.Application_Access)
return Security.Policies.Policy_Manager_Access;
-- Check if the permission with the name <tt>Name</tt> is granted for the current user.
-- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified.
-- Returns True if the user is granted the given permission.
function Has_Permission (Name : in Util.Beans.Objects.Object;
Entity : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
private
type Permission_Manager is new Security.Policies.Policy_Manager with record
App : AWA.Applications.Application_Access := null;
end record;
end AWA.Permissions.Services;
|
-----------------------------------------------------------------------
-- awa-permissions-services -- Permissions controller
-- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Applications;
with Util.Beans.Objects;
with EL.Functions;
with ADO;
with ADO.Sessions;
with ADO.Objects;
with Security.Policies;
with Security.Contexts;
package AWA.Permissions.Services is
-- Register the security EL functions in the EL mapper.
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
type Permission_Manager is new Security.Policies.Policy_Manager with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
-- Get the permission manager associated with the security context.
-- Returns null if there is none.
function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class)
return Permission_Manager_Access;
-- Get the application instance.
function Get_Application (Manager : in Permission_Manager)
return AWA.Applications.Application_Access;
-- Set the application instance.
procedure Set_Application (Manager : in out Permission_Manager;
App : in AWA.Applications.Application_Access);
-- Add a permission for the current user to access the entity identified by
-- <b>Entity</b> and <b>Kind</b> in the <b>Workspace</b>.
procedure Add_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Workspace : in ADO.Identifier;
Permission : in Permission_Type);
-- Check that the current user has the specified permission.
-- Raise NO_PERMISSION exception if the user does not have the permission.
procedure Check_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type);
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b> which is of type <b>Kind</b>.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Workspace : in ADO.Identifier;
Permission : in Permission_Type := READ);
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b>.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Objects.Object_Ref'Class;
Workspace : in ADO.Identifier;
Permission : in Permission_Type := READ);
-- Create a permission manager for the given application.
function Create_Permission_Manager (App : in AWA.Applications.Application_Access)
return Security.Policies.Policy_Manager_Access;
-- Check if the permission with the name <tt>Name</tt> is granted for the current user.
-- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified.
-- Returns True if the user is granted the given permission.
function Has_Permission (Name : in Util.Beans.Objects.Object;
Entity : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
private
type Permission_Manager is new Security.Policies.Policy_Manager with record
App : AWA.Applications.Application_Access := null;
end record;
end AWA.Permissions.Services;
|
Add a workspace identifier parameter to the Add_Permission procedures
|
Add a workspace identifier parameter to the Add_Permission procedures
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
44f9cafc2adb84850062775fdff656713e4140b3
|
src/gen-model-projects.adb
|
src/gen-model-projects.adb
|
-----------------------------------------------------------------------
-- gen-model-projects -- Projects meta data
-- 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.IO_Exceptions;
with Ada.Directories;
with Util.Files;
with Util.Log.Loggers;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Streams.Buffered;
with Util.Streams.Texts;
with Util.Strings.Transforms;
package body Gen.Model.Projects is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Projects");
-- ------------------------------
-- 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 : Project_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (From.Name);
elsif From.Props.Exists (Name) then
return Util.Beans.Objects.To_Object (String '(From.Props.Get (Name)));
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the project name.
-- ------------------------------
function Get_Project_Name (Project : in Project_Definition) return String is
begin
return To_String (Project.Name);
end Get_Project_Name;
-- ------------------------------
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
-- ------------------------------
function Find_Project (From : in Project_Definition;
Path : in String) return Project_Definition_Access is
Iter : Project_Vectors.Cursor := From.Modules.First;
begin
while Project_Vectors.Has_Element (Iter) loop
declare
P : constant Project_Definition_Access := Project_Vectors.Element (Iter);
begin
if P.Path = Path then
return P;
end if;
end;
Project_Vectors.Next (Iter);
end loop;
return null;
end Find_Project;
-- ------------------------------
-- Save the project description and parameters.
-- ------------------------------
procedure Save (Project : in out Project_Definition;
Path : in String) is
use Util.Streams.Buffered;
use Util.Streams;
procedure Save_Module (Pos : in Project_Vectors.Cursor);
procedure Read_Property_Line (Line : in String);
Output : Util.Serialize.IO.XML.Output_Stream;
Prop_Output : Util.Streams.Texts.Print_Stream;
procedure Save_Module (Pos : in Project_Vectors.Cursor) is
Module : constant Project_Definition_Access := Project_Vectors.Element (Pos);
begin
Output.Start_Entity (Name => "module");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Module.Path));
Output.End_Entity (Name => "module");
end Save_Module;
-- ------------------------------
-- Read the application property file to remove all the dynamo.* properties
-- ------------------------------
procedure Read_Property_Line (Line : in String) is
begin
if Line'Length < 7 or else Line (Line'First .. Line'First + 6) /= "dynamo_" then
Prop_Output.Write (Line);
Prop_Output.Write (ASCII.LF);
end if;
end Read_Property_Line;
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Name : constant Util.Beans.Objects.Object := Project.Get_Value ("name");
Prop_Name : constant String := Util.Beans.Objects.To_String (Name) & ".properties";
Prop_Path : constant String := Ada.Directories.Compose (Dir, Prop_Name);
begin
Prop_Output.Initialize (Size => 100000);
Output.Initialize (Size => 10000);
-- Read the current project property file, ignoring the dynamo.* properties.
begin
Util.Files.Read_File (Prop_Path, Read_Property_Line'Access);
exception
when Ada.IO_Exceptions.Name_Error =>
null;
end;
-- Start building the new dynamo.xml content.
-- At the same time, we append in the project property file the list of dynamo properties.
Output.Start_Entity (Name => "project");
Output.Write_Entity (Name => "name", Value => Name);
declare
Names : constant Util.Properties.Name_Array := Project.Props.Get_Names;
begin
for I in Names'Range loop
Output.Write (ASCII.LF);
Output.Start_Entity (Name => "property");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Names (I)));
Output.Write_String (Value => Util.Strings.Transforms.Escape_Xml
(To_String (Project.Props.Get (Names (I)))));
Output.End_Entity (Name => "property");
Prop_Output.Write ("dynamo_");
Prop_Output.Write (Names (I));
Prop_Output.Write ("=");
Prop_Output.Write (To_String (Project.Props.Get (Names (I))));
Prop_Output.Write (ASCII.LF);
end loop;
end;
Project.Modules.Iterate (Save_Module'Access);
Output.End_Entity (Name => "project");
Util.Files.Write_File (Content => Texts.To_String (Buffered_Stream (Output)),
Path => Path);
Util.Files.Write_File (Content => Texts.To_String (Buffered_Stream (Prop_Output)),
Path => Prop_Path);
end Save;
-- ------------------------------
-- Read the XML project description into the project description.
-- ------------------------------
procedure Read_Project (Project : in out Project_Definition) is
type Project_Fields is (FIELD_PROJECT_NAME,
FIELD_PROPERTY_NAME,
FIELD_PROPERTY_VALUE,
FIELD_MODULE_NAME);
type Project_Loader is record
Name : Unbounded_String;
end record;
type Project_Loader_Access is access all Project_Loader;
procedure Set_Member (Closure : in out Project_Loader;
Field : in Project_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Closure : in out Project_Loader;
Field : in Project_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_PROJECT_NAME =>
Project.Name := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_MODULE_NAME =>
declare
P : constant Model.Projects.Project_Definition_Access
:= new Model.Projects.Project_Definition;
begin
P.Name := Util.Beans.Objects.To_Unbounded_String (Value);
Project.Modules.Append (P);
end;
when FIELD_PROPERTY_NAME =>
Closure.Name := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_PROPERTY_VALUE =>
Project.Props.Set (Closure.Name, Util.Beans.Objects.To_Unbounded_String (Value));
end case;
end Set_Member;
package Project_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Project_Loader,
Element_Type_Access => Project_Loader_Access,
Fields => Project_Fields,
Set_Member => Set_Member);
Path : constant String := To_String (Project.Path);
Loader : aliased Project_Loader;
Mapper : aliased Project_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
begin
Log.Info ("Reading project file '{0}'", Path);
-- Create the mapping to load the XML project file.
Mapper.Add_Mapping ("name", FIELD_PROJECT_NAME);
Mapper.Add_Mapping ("property/@name", FIELD_PROPERTY_NAME);
Mapper.Add_Mapping ("property", FIELD_PROPERTY_VALUE);
Mapper.Add_Mapping ("module/@name", FIELD_MODULE_NAME);
Reader.Add_Mapping ("project", Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Project_Mapper.Set_Context (Reader, Loader'Access);
Project.Name := Null_Unbounded_String;
-- Read the XML query file.
Reader.Parse (Path);
--
-- if Length (Into.Name) = 0 then
-- H.Error ("Project file {0} does not contain the project name.", Path);
-- end if;
exception
when Ada.IO_Exceptions.Name_Error =>
-- H.Error ("Project file {0} does not exist", Path);
Log.Error ("Project file {0} does not exist", Path);
end Read_Project;
end Gen.Model.Projects;
|
-----------------------------------------------------------------------
-- gen-model-projects -- Projects meta data
-- 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.IO_Exceptions;
with Ada.Directories;
with Util.Files;
with Util.Log.Loggers;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Streams.Buffered;
with Util.Streams.Texts;
with Util.Strings.Transforms;
package body Gen.Model.Projects is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Projects");
-- ------------------------------
-- 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 : Project_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (From.Name);
elsif From.Props.Exists (Name) then
return Util.Beans.Objects.To_Object (String '(From.Props.Get (Name)));
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the project name.
-- ------------------------------
function Get_Project_Name (Project : in Project_Definition) return String is
begin
return To_String (Project.Name);
end Get_Project_Name;
-- ------------------------------
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
-- ------------------------------
function Find_Project (From : in Project_Definition;
Path : in String) return Project_Definition_Access is
Iter : Project_Vectors.Cursor := From.Modules.First;
begin
while Project_Vectors.Has_Element (Iter) loop
declare
P : constant Project_Definition_Access := Project_Vectors.Element (Iter);
begin
if P.Path = Path then
return P;
end if;
end;
Project_Vectors.Next (Iter);
end loop;
return null;
end Find_Project;
-- ------------------------------
-- Save the project description and parameters.
-- ------------------------------
procedure Save (Project : in out Project_Definition;
Path : in String) is
use Util.Streams.Buffered;
use Util.Streams;
procedure Save_Module (Pos : in Project_Vectors.Cursor);
procedure Read_Property_Line (Line : in String);
Output : Util.Serialize.IO.XML.Output_Stream;
Prop_Output : Util.Streams.Texts.Print_Stream;
procedure Save_Module (Pos : in Project_Vectors.Cursor) is
Module : constant Project_Definition_Access := Project_Vectors.Element (Pos);
begin
if Length (Module.Path) > 0 then
Output.Write_String (ASCII.LF & " ");
Output.Start_Entity (Name => "module");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Module.Path));
Output.End_Entity (Name => "module");
end if;
end Save_Module;
-- ------------------------------
-- Read the application property file to remove all the dynamo.* properties
-- ------------------------------
procedure Read_Property_Line (Line : in String) is
begin
if Line'Length < 7 or else Line (Line'First .. Line'First + 6) /= "dynamo_" then
Prop_Output.Write (Line);
Prop_Output.Write (ASCII.LF);
end if;
end Read_Property_Line;
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Name : constant Util.Beans.Objects.Object := Project.Get_Value ("name");
Prop_Name : constant String := Util.Beans.Objects.To_String (Name) & ".properties";
Prop_Path : constant String := Ada.Directories.Compose (Dir, Prop_Name);
begin
Prop_Output.Initialize (Size => 100000);
Output.Initialize (Size => 10000);
-- Read the current project property file, ignoring the dynamo.* properties.
begin
Util.Files.Read_File (Prop_Path, Read_Property_Line'Access);
exception
when Ada.IO_Exceptions.Name_Error =>
null;
end;
-- Start building the new dynamo.xml content.
-- At the same time, we append in the project property file the list of dynamo properties.
Output.Start_Entity (Name => "project");
Output.Write_String (ASCII.LF & " ");
Output.Write_Entity (Name => "name", Value => Name);
declare
Names : constant Util.Properties.Name_Array := Project.Props.Get_Names;
begin
for I in Names'Range loop
Output.Write_String (ASCII.LF & " ");
Output.Start_Entity (Name => "property");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Names (I)));
Output.Write_String (Value => Util.Strings.Transforms.Escape_Xml
(To_String (Project.Props.Get (Names (I)))));
Output.End_Entity (Name => "property");
Prop_Output.Write ("dynamo_");
Prop_Output.Write (Names (I));
Prop_Output.Write ("=");
Prop_Output.Write (To_String (Project.Props.Get (Names (I))));
Prop_Output.Write (ASCII.LF);
end loop;
end;
Project.Modules.Iterate (Save_Module'Access);
Output.Write_String (ASCII.LF & "");
Output.End_Entity (Name => "project");
Util.Files.Write_File (Content => Texts.To_String (Buffered_Stream (Output)),
Path => Path);
Util.Files.Write_File (Content => Texts.To_String (Buffered_Stream (Prop_Output)),
Path => Prop_Path);
end Save;
-- ------------------------------
-- Read the XML project description into the project description.
-- ------------------------------
procedure Read_Project (Project : in out Project_Definition) is
type Project_Fields is (FIELD_PROJECT_NAME,
FIELD_PROPERTY_NAME,
FIELD_PROPERTY_VALUE,
FIELD_MODULE_NAME);
type Project_Loader is record
Name : Unbounded_String;
end record;
type Project_Loader_Access is access all Project_Loader;
procedure Set_Member (Closure : in out Project_Loader;
Field : in Project_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Closure : in out Project_Loader;
Field : in Project_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_PROJECT_NAME =>
Project.Name := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_MODULE_NAME =>
declare
P : constant Model.Projects.Project_Definition_Access
:= new Model.Projects.Project_Definition;
begin
P.Name := Util.Beans.Objects.To_Unbounded_String (Value);
Project.Modules.Append (P);
end;
when FIELD_PROPERTY_NAME =>
Closure.Name := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_PROPERTY_VALUE =>
Project.Props.Set (Closure.Name, Util.Beans.Objects.To_Unbounded_String (Value));
end case;
end Set_Member;
package Project_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Project_Loader,
Element_Type_Access => Project_Loader_Access,
Fields => Project_Fields,
Set_Member => Set_Member);
Path : constant String := To_String (Project.Path);
Loader : aliased Project_Loader;
Mapper : aliased Project_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
begin
Log.Info ("Reading project file '{0}'", Path);
-- Create the mapping to load the XML project file.
Mapper.Add_Mapping ("name", FIELD_PROJECT_NAME);
Mapper.Add_Mapping ("property/@name", FIELD_PROPERTY_NAME);
Mapper.Add_Mapping ("property", FIELD_PROPERTY_VALUE);
Mapper.Add_Mapping ("module/@name", FIELD_MODULE_NAME);
Reader.Add_Mapping ("project", Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Project_Mapper.Set_Context (Reader, Loader'Access);
Project.Name := Null_Unbounded_String;
-- Read the XML query file.
Reader.Parse (Path);
--
-- if Length (Into.Name) = 0 then
-- H.Error ("Project file {0} does not contain the project name.", Path);
-- end if;
exception
when Ada.IO_Exceptions.Name_Error =>
-- H.Error ("Project file {0} does not exist", Path);
Log.Error ("Project file {0} does not exist", Path);
end Read_Project;
end Gen.Model.Projects;
|
Write the dynamo.xml with some indentation Avoid writing empty module references
|
Write the dynamo.xml with some indentation
Avoid writing empty module references
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
9b7175a1c86636c73516ab8600bd66f98db71080
|
src/http/aws/util-http-clients-web.adb
|
src/http/aws/util-http-clients-web.adb
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- 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 AWS.Headers.Set;
with AWS.Client;
with AWS.Messages;
with Util.Log.Loggers;
package body Util.Http.Clients.Web is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web");
Manager : aliased AWS_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural is
use AWS.Messages;
begin
case Code is
when S100 =>
return 100;
when S101 =>
return 101;
when S102 =>
return 102;
when S200 =>
return 200;
when S201 =>
return 201;
when S203 =>
return 203;
when S204 =>
return 204;
when S205 =>
return 205;
when S206 =>
return 206;
when S207 =>
return 207;
when S300 =>
return 300;
when S301 =>
return 301;
when S302 =>
return 302;
when S303 =>
return 303;
when S304 =>
return 304;
when S305 =>
return 305;
when S307 =>
return 307;
when S400 =>
return 400;
when S401 =>
return 401;
when S402 =>
return 402;
when S403 =>
return 403;
when S404 =>
return 404;
when S405 =>
return 405;
when S406 =>
return 406;
when S407 =>
return 407;
when S408 =>
return 408;
when S409 =>
return 409;
when S410 =>
return 410;
when S411 =>
return 411;
when S412 =>
return 412;
when S413 =>
return 413;
when S414 =>
return 414;
when S415 =>
return 415;
when S416 =>
return 416;
when S417 =>
return 417;
when S422 =>
return 422;
when S423 =>
return 423;
when S424 =>
return 424;
when S500 =>
return 500;
when S501 =>
return 501;
when S502 =>
return 502;
when S503 =>
return 503;
when S504 =>
return 504;
when S505 =>
return 505;
when S507 =>
return 507;
when others =>
return 500;
end case;
end To_Status;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new AWS_Http_Request;
end Create;
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Get {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers);
end Do_Get;
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Post {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers);
end Do_Post;
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Put {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers);
end Do_Put;
-- Set the timeout for the connection.
overriding
procedure Set_Timeout (Manager : in AWS_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
begin
null;
end Set_Timeout;
-- ------------------------------
-- Returns a boolean indicating whether the named request header has already
-- been set.
-- ------------------------------
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean is
begin
raise Program_Error with "Contains_Header is not implemented";
return False;
end Contains_Header;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String is
begin
return "";
end Get_Header;
-- ------------------------------
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Add_Header;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean is
begin
return AWS.Response.Header (Reply.Data, Name) /= "";
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String is
begin
return AWS.Response.Header (Reply.Data, Name);
end Get_Header;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Set_Header;
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Add_Header;
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
function Get_Body (Reply : in AWS_Http_Response) return String is
begin
return AWS.Response.Message_Body (Reply.Data);
end Get_Body;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural is
begin
return To_Status (AWS.Response.Status_Code (Reply.Data));
end Get_Status;
end Util.Http.Clients.Web;
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- 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 AWS.Headers.Set;
with AWS.Messages;
with Util.Log.Loggers;
package body Util.Http.Clients.Web is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web");
Manager : aliased AWS_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural is
use AWS.Messages;
begin
case Code is
when S100 =>
return 100;
when S101 =>
return 101;
when S102 =>
return 102;
when S200 =>
return 200;
when S201 =>
return 201;
when S203 =>
return 203;
when S204 =>
return 204;
when S205 =>
return 205;
when S206 =>
return 206;
when S207 =>
return 207;
when S300 =>
return 300;
when S301 =>
return 301;
when S302 =>
return 302;
when S303 =>
return 303;
when S304 =>
return 304;
when S305 =>
return 305;
when S307 =>
return 307;
when S400 =>
return 400;
when S401 =>
return 401;
when S402 =>
return 402;
when S403 =>
return 403;
when S404 =>
return 404;
when S405 =>
return 405;
when S406 =>
return 406;
when S407 =>
return 407;
when S408 =>
return 408;
when S409 =>
return 409;
when S410 =>
return 410;
when S411 =>
return 411;
when S412 =>
return 412;
when S413 =>
return 413;
when S414 =>
return 414;
when S415 =>
return 415;
when S416 =>
return 416;
when S417 =>
return 417;
when S422 =>
return 422;
when S423 =>
return 423;
when S424 =>
return 424;
when S500 =>
return 500;
when S501 =>
return 501;
when S502 =>
return 502;
when S503 =>
return 503;
when S504 =>
return 504;
when S505 =>
return 505;
when S507 =>
return 507;
when others =>
return 500;
end case;
end To_Status;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new AWS_Http_Request;
end Create;
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Get {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Get;
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Post {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Post (URL => URI, Data => Data,
Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Post;
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Put {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Put;
-- ------------------------------
-- Set the timeout for the connection.
-- ------------------------------
overriding
procedure Set_Timeout (Manager : in AWS_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
begin
AWS_Http_Request'Class (Http.Delegate.all).Timeouts
:= AWS.Client.Timeouts (Connect => Timeout,
Send => Timeout,
Receive => Timeout,
Response => Timeout);
end Set_Timeout;
-- ------------------------------
-- Returns a boolean indicating whether the named request header has already
-- been set.
-- ------------------------------
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean is
begin
raise Program_Error with "Contains_Header is not implemented";
return False;
end Contains_Header;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String is
begin
return "";
end Get_Header;
-- ------------------------------
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Add_Header;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean is
begin
return AWS.Response.Header (Reply.Data, Name) /= "";
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String is
begin
return AWS.Response.Header (Reply.Data, Name);
end Get_Header;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Set_Header;
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Add_Header;
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
function Get_Body (Reply : in AWS_Http_Response) return String is
begin
return AWS.Response.Message_Body (Reply.Data);
end Get_Body;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural is
begin
return To_Status (AWS.Response.Status_Code (Reply.Data));
end Get_Status;
end Util.Http.Clients.Web;
|
Implement the Set_Timeout procedure Use the timeout that was configured for the Get/Post/Put operations
|
Implement the Set_Timeout procedure
Use the timeout that was configured for the Get/Post/Put operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
24ed0162377403fe3aabdc031ad7bacbea945b1c
|
src/asf-navigations-mappers.adb
|
src/asf-navigations-mappers.adb
|
-----------------------------------------------------------------------
-- asf-navigations-reader -- Read XML navigation files
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Navigations.Redirect;
with ASF.Navigations.Render;
package body ASF.Navigations.Mappers is
use Util.Beans.Objects;
Empty : constant Util.Beans.Objects.Object := To_Object (String '(""));
-- ------------------------------
-- Reset the navigation config before parsing a new rule.
-- ------------------------------
procedure Reset (N : in out Nav_Config) is
begin
N.To_View := Empty;
N.Outcome := Empty;
N.Action := Empty;
N.Condition := Empty;
N.Redirect := False;
end Reset;
-- ------------------------------
-- Save in the navigation config object the value associated with the given field.
-- When the <b>NAVIGATION_CASE</b> field is reached, insert the new navigation rule
-- that was collected in the navigation handler.
-- ------------------------------
procedure Set_Member (N : in out Nav_Config;
Field : in Navigation_Case_Fields;
Value : in Util.Beans.Objects.Object) is
use ASF.Navigations.Redirect;
use ASF.Navigations.Render;
begin
case Field is
when OUTCOME =>
N.Outcome := Value;
when ACTION =>
N.Action := Value;
when TO_VIEW =>
N.To_View := Value;
when FROM_VIEW_ID =>
N.From_View := Value;
when REDIRECT =>
N.Redirect := True;
when CONDITION =>
N.Condition := Value;
null;
when CONTENT =>
N.Content := Value;
when CONTENT_TYPE =>
N.Content_Type := Value;
when NAVIGATION_CASE =>
declare
Navigator : Navigation_Access;
begin
if N.Redirect then
Navigator := Create_Redirect_Navigator (To_String (N.To_View), N.Context.all);
else
Navigator := Create_Render_Navigator (To_String (N.To_View));
end if;
N.Handler.Add_Navigation_Case (Navigator => Navigator,
From => To_String (N.From_View),
Outcome => To_String (N.Outcome),
Action => To_String (N.Action),
Condition => To_String (N.Condition),
Context => N.Context.all);
end;
Reset (N);
when NAVIGATION_RULE =>
N.From_View := Empty;
end case;
end Set_Member;
Mapping : aliased Navigation_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the navigation rules.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("faces-config", Mapping'Access);
Reader.Add_Mapping ("module", Mapping'Access);
Reader.Add_Mapping ("web-app", Mapping'Access);
Config.Handler := Handler;
Config.Context := Context;
Config.From_View := Empty;
Reset (Config);
Navigation_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
-- <navigation-rule> mapping
Mapping.Add_Mapping ("navigation-rule/from-view-id", FROM_VIEW_ID);
Mapping.Add_Mapping ("navigation-rule/navigation-case/from-action", ACTION);
Mapping.Add_Mapping ("navigation-rule/navigation-case/from-outcome", OUTCOME);
Mapping.Add_Mapping ("navigation-rule/navigation-case/to-view-id", TO_VIEW);
Mapping.Add_Mapping ("navigation-rule/navigation-case/if", CONDITION);
-- Mapping.Add_Mapping ("navigation-case/redirect/view-param/name", VIEW_PARAM_NAME);
-- Mapping.Add_Mapping ("navigation-case/redirect/view-param/value", VIEW_PARAM_VALUE);
-- Mapping.Add_Mapping ("navigation-case/redirect/include-view-params", INCLUDE_VIEW_PARAMS);
Mapping.Add_Mapping ("navigation-rule/navigation-case/redirect", REDIRECT);
Mapping.Add_Mapping ("navigation-rule/navigation-case/content", CONTENT);
Mapping.Add_Mapping ("navigation-rule/navigation-case/content/@type", CONTENT_TYPE);
Mapping.Add_Mapping ("navigation-rule/navigation-case", NAVIGATION_CASE);
Mapping.Add_Mapping ("navigation-rule", NAVIGATION_RULE);
end ASF.Navigations.Mappers;
|
-----------------------------------------------------------------------
-- asf-navigations-reader -- Read XML navigation files
-- Copyright (C) 2010, 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Navigations.Redirect;
with ASF.Navigations.Render;
package body ASF.Navigations.Mappers is
use Util.Beans.Objects;
Empty : constant Util.Beans.Objects.Object := To_Object (String '(""));
-- ------------------------------
-- Reset the navigation config before parsing a new rule.
-- ------------------------------
procedure Reset (N : in out Nav_Config) is
begin
N.To_View := Empty;
N.Outcome := Empty;
N.Action := Empty;
N.Condition := Empty;
N.Redirect := False;
end Reset;
-- ------------------------------
-- Save in the navigation config object the value associated with the given field.
-- When the <b>NAVIGATION_CASE</b> field is reached, insert the new navigation rule
-- that was collected in the navigation handler.
-- ------------------------------
procedure Set_Member (N : in out Nav_Config;
Field : in Navigation_Case_Fields;
Value : in Util.Beans.Objects.Object) is
use ASF.Navigations.Redirect;
use ASF.Navigations.Render;
begin
case Field is
when OUTCOME =>
N.Outcome := Value;
when ACTION =>
N.Action := Value;
when TO_VIEW =>
N.To_View := Value;
when FROM_VIEW_ID =>
N.From_View := Value;
when REDIRECT =>
N.Redirect := True;
when CONDITION =>
N.Condition := Value;
null;
when CONTENT =>
N.Content := Value;
when CONTENT_TYPE =>
N.Content_Type := Value;
when NAVIGATION_CASE =>
declare
Navigator : Navigation_Access;
begin
if N.Redirect then
Navigator := Create_Redirect_Navigator (To_String (N.To_View), N.Context.all);
else
Navigator := Create_Render_Navigator (To_String (N.To_View));
end if;
N.Handler.Add_Navigation_Case (Navigator => Navigator,
From => To_String (N.From_View),
Outcome => To_String (N.Outcome),
Action => To_String (N.Action),
Condition => To_String (N.Condition),
Context => N.Context.all);
end;
Reset (N);
when NAVIGATION_RULE =>
N.From_View := Empty;
end case;
end Set_Member;
Mapping : aliased Navigation_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the navigation rules.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", Mapping'Access);
Mapper.Add_Mapping ("module", Mapping'Access);
Mapper.Add_Mapping ("web-app", Mapping'Access);
Config.Handler := Handler;
Config.Context := Context;
Config.From_View := Empty;
Reset (Config);
Navigation_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
-- <navigation-rule> mapping
Mapping.Add_Mapping ("navigation-rule/from-view-id", FROM_VIEW_ID);
Mapping.Add_Mapping ("navigation-rule/navigation-case/from-action", ACTION);
Mapping.Add_Mapping ("navigation-rule/navigation-case/from-outcome", OUTCOME);
Mapping.Add_Mapping ("navigation-rule/navigation-case/to-view-id", TO_VIEW);
Mapping.Add_Mapping ("navigation-rule/navigation-case/if", CONDITION);
-- Mapping.Add_Mapping ("navigation-case/redirect/view-param/name", VIEW_PARAM_NAME);
-- Mapping.Add_Mapping ("navigation-case/redirect/view-param/value", VIEW_PARAM_VALUE);
-- Mapping.Add_Mapping ("navigation-case/redirect/include-view-params", INCLUDE_VIEW_PARAMS);
Mapping.Add_Mapping ("navigation-rule/navigation-case/redirect", REDIRECT);
Mapping.Add_Mapping ("navigation-rule/navigation-case/content", CONTENT);
Mapping.Add_Mapping ("navigation-rule/navigation-case/content/@type", CONTENT_TYPE);
Mapping.Add_Mapping ("navigation-rule/navigation-case", NAVIGATION_CASE);
Mapping.Add_Mapping ("navigation-rule", NAVIGATION_RULE);
end ASF.Navigations.Mappers;
|
Update the Reader_Config to use the new parser/mapper interface
|
Update the Reader_Config to use the new parser/mapper interface
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
dd9c96ec219a51fe1c4d67f60c830bf7b8817c48
|
src/orka/implementation/orka-loops.adb
|
src/orka/implementation/orka-loops.adb
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
package body Orka.Loops is
use Ada.Real_Time;
procedure Free is new Ada.Unchecked_Deallocation
(Behaviors.Behavior_Array, Behaviors.Behavior_Array_Access);
function Behavior_Hash (Element : Behaviors.Behavior_Ptr) return Ada.Containers.Hash_Type is
function Convert is new Ada.Unchecked_Conversion
(Source => System.Address, Target => Long_Integer);
begin
return Ada.Containers.Hash_Type (Convert (Element.all'Address));
end Behavior_Hash;
procedure Fixed_Update (Delta_Time : Time_Span; Scene : not null Behaviors.Behavior_Array_Access) is
DT : constant Duration := To_Duration (Delta_Time);
begin
for Behavior of Scene.all loop
Behavior.Fixed_Update (DT);
end loop;
end Fixed_Update;
procedure Update (Delta_Time : Time_Span; Scene : not null Behaviors.Behavior_Array_Access) is
DT : constant Duration := To_Duration (Delta_Time);
begin
for Behavior of Scene.all loop
Behavior.Update (DT);
end loop;
for Behavior of Scene.all loop
Behavior.After_Update (DT);
end loop;
end Update;
protected body Handler is
procedure Stop is
begin
Stop_Flag := True;
end Stop;
procedure Set_Frame_Limit (Value : Time_Span) is
begin
Limit := Value;
end Set_Frame_Limit;
function Frame_Limit return Time_Span is
(Limit);
function Should_Stop return Boolean is
(Stop_Flag);
end Handler;
protected body Scene is
procedure Add (Object : Behaviors.Behavior_Ptr) is
begin
Behaviors_Set.Insert (Object);
Modified_Flag := True;
end Add;
procedure Remove (Object : Behaviors.Behavior_Ptr) is
begin
Behaviors_Set.Delete (Object);
Modified_Flag := True;
end Remove;
procedure Replace_Array (Target : in out Behaviors.Behavior_Array_Access) is
Index : Positive := 1;
begin
Free (Target);
Target := new Behaviors.Behavior_Array (1 .. Positive (Behaviors_Set.Length));
-- Copy the elements from the set to the array
-- for faster iteration by the game loop
for Element of Behaviors_Set loop
Target (Index) := Element;
Index := Index + 1;
end loop;
Modified_Flag := False;
end Replace_Array;
function Modified return Boolean is
(Modified_Flag);
procedure Set_Camera (Camera : Cameras.Camera_Ptr) is
begin
Scene_Camera := Camera;
end Set_Camera;
function Camera return Cameras.Camera_Ptr is
(Scene_Camera);
end Scene;
procedure Run_Loop is
Previous_Time : Time := Clock;
Lag : Time_Span := Time_Span_Zero;
Next_Time : Time := Previous_Time;
Scene_Array : Behaviors.Behavior_Array_Access := new Behaviors.Behavior_Array (1 .. 0);
begin
-- Based on http://gameprogrammingpatterns.com/game-loop.html
loop
-- TODO Move Window.Swap_Buffers to here?
declare
Current_Time : constant Time := Clock;
Elapsed : constant Time_Span := Current_Time - Previous_Time;
begin
Previous_Time := Current_Time;
Lag := Lag + Elapsed;
Window.Process_Input;
exit when Handler.Should_Stop or Window.Should_Close;
while Lag > Time_Step loop
Fixed_Update (Time_Step, Scene_Array);
Lag := Lag - Time_Step;
end loop;
Scene.Camera.Update (To_Duration (Lag));
Update (Lag, Scene_Array);
Window.Swap_Buffers;
-- Render the scene *after* having swapped buffers (sync point)
-- so that rendering on GPU happens in parallel with CPU work
-- during the next frame
Render (Scene_Array, Scene.Camera);
if Scene.Modified then
-- TODO Deallocation and allocation should not be done in render loop
Scene.Replace_Array (Scene_Array);
end if;
declare
New_Elapsed : constant Time_Span := Clock - Current_Time;
begin
if New_Elapsed > Handler.Frame_Limit then
Next_Time := Current_Time;
else
Next_Time := Next_Time + Handler.Frame_Limit;
delay until Next_Time;
end if;
end;
end;
end loop;
end Run_Loop;
end Orka.Loops;
|
-- 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.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
package body Orka.Loops is
use Ada.Real_Time;
procedure Free is new Ada.Unchecked_Deallocation
(Behaviors.Behavior_Array, Behaviors.Behavior_Array_Access);
function Behavior_Hash (Element : Behaviors.Behavior_Ptr) return Ada.Containers.Hash_Type is
function Convert is new Ada.Unchecked_Conversion
(Source => System.Address, Target => Long_Integer);
begin
return Ada.Containers.Hash_Type (Convert (Element.all'Address));
end Behavior_Hash;
procedure Fixed_Update (Delta_Time : Time_Span; Scene : not null Behaviors.Behavior_Array_Access) is
DT : constant Duration := To_Duration (Delta_Time);
begin
for Behavior of Scene.all loop
Behavior.Fixed_Update (DT);
end loop;
end Fixed_Update;
procedure Update (Delta_Time : Time_Span; Scene : not null Behaviors.Behavior_Array_Access) is
DT : constant Duration := To_Duration (Delta_Time);
begin
for Behavior of Scene.all loop
Behavior.Update (DT);
end loop;
for Behavior of Scene.all loop
Behavior.After_Update (DT);
end loop;
end Update;
protected body Handler is
procedure Stop is
begin
Stop_Flag := True;
end Stop;
procedure Set_Frame_Limit (Value : Time_Span) is
begin
Limit := Value;
end Set_Frame_Limit;
function Frame_Limit return Time_Span is
(Limit);
function Should_Stop return Boolean is
(Stop_Flag);
end Handler;
protected body Scene is
procedure Add (Object : Behaviors.Behavior_Ptr) is
begin
Behaviors_Set.Insert (Object);
Modified_Flag := True;
end Add;
procedure Remove (Object : Behaviors.Behavior_Ptr) is
begin
Behaviors_Set.Delete (Object);
Modified_Flag := True;
end Remove;
procedure Replace_Array (Target : in out Behaviors.Behavior_Array_Access) is
Index : Positive := 1;
Count : constant Positive := Positive (Behaviors_Set.Length);
begin
Free (Target);
Target := new Behaviors.Behavior_Array'(1 .. Count => Behaviors.Null_Behavior);
-- Copy the elements from the set to the array
-- for faster iteration by the game loop
for Element of Behaviors_Set loop
Target (Index) := Element;
Index := Index + 1;
end loop;
Modified_Flag := False;
end Replace_Array;
function Modified return Boolean is
(Modified_Flag);
procedure Set_Camera (Camera : Cameras.Camera_Ptr) is
begin
Scene_Camera := Camera;
end Set_Camera;
function Camera return Cameras.Camera_Ptr is
(Scene_Camera);
end Scene;
procedure Run_Loop is
Previous_Time : Time := Clock;
Lag : Time_Span := Time_Span_Zero;
Next_Time : Time := Previous_Time;
Scene_Array : Behaviors.Behavior_Array_Access := new Behaviors.Behavior_Array (1 .. 0);
begin
-- Based on http://gameprogrammingpatterns.com/game-loop.html
loop
-- TODO Move Window.Swap_Buffers to here?
declare
Current_Time : constant Time := Clock;
Elapsed : constant Time_Span := Current_Time - Previous_Time;
begin
Previous_Time := Current_Time;
Lag := Lag + Elapsed;
Window.Process_Input;
exit when Handler.Should_Stop or Window.Should_Close;
while Lag > Time_Step loop
Fixed_Update (Time_Step, Scene_Array);
Lag := Lag - Time_Step;
end loop;
Scene.Camera.Update (To_Duration (Lag));
Update (Lag, Scene_Array);
Window.Swap_Buffers;
-- Render the scene *after* having swapped buffers (sync point)
-- so that rendering on GPU happens in parallel with CPU work
-- during the next frame
Render (Scene_Array, Scene.Camera);
if Scene.Modified then
Scene.Replace_Array (Scene_Array);
end if;
declare
New_Elapsed : constant Time_Span := Clock - Current_Time;
begin
if New_Elapsed > Handler.Frame_Limit then
Next_Time := Current_Time;
else
Next_Time := Next_Time + Handler.Frame_Limit;
delay until Next_Time;
end if;
end;
end;
end loop;
end Run_Loop;
end Orka.Loops;
|
Fix access check failure
|
orka: Fix access check failure
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
98a9771496fb329c61d1cb76b2e9f14d7cdb017d
|
src/el-objects-enums.adb
|
src/el-objects-enums.adb
|
-----------------------------------------------------------------------
-- EL.Objects.Enums -- Helper conversion for discrete types
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
package body EL.Objects.Enums is
use Ada.Characters.Conversions;
Value_Range : constant Long_Long_Integer := T'Pos (T'Last) - T'Pos (T'First) + 1;
NAME : aliased constant String := "Enum";
Value_Type : aliased constant Basic_Type := Basic_Type '(Name => NAME'Access);
-- ------------------------------
-- Create an object from the given value.
-- ------------------------------
function To_Object (Value : in T) return Object is
begin
return Object '(Controlled with
V => Object_Value '(Of_Type => TYPE_INTEGER,
Int_Value => Long_Long_Integer (T'Pos (Value))),
Type_Def => Value_Type'Access);
end To_Object;
-- ------------------------------
-- Convert the object into a value.
-- Raises Constraint_Error if the object cannot be converter to the target type.
-- ------------------------------
function To_Value (Value : in EL.Objects.Object) return T is
begin
case Value.V.Of_Type is
when TYPE_INTEGER =>
if ROUND_VALUE then
return T'Val (Value.V.Int_Value mod Value_Range);
else
return T'Val (Value.V.Int_Value);
end if;
when TYPE_BOOLEAN =>
return T'Val (Boolean'Pos (Value.V.Bool_Value));
when TYPE_FLOAT =>
if ROUND_VALUE then
return T'Val (To_Long_Long_Integer (Value) mod Value_Range);
else
return T'Val (To_Long_Long_Integer (Value));
end if;
when TYPE_STRING =>
if Value.V.Proxy = null then
raise Constraint_Error with "The object value is null";
end if;
return T'Value (Value.V.Proxy.String_Value.all);
when TYPE_WIDE_STRING =>
if Value.V.Proxy = null then
raise Constraint_Error with "The object value is null";
end if;
return T'Value (To_String (Value.V.Proxy.Wide_String_Value.all));
when TYPE_NULL =>
raise Constraint_Error with "The object value is null";
when TYPE_TIME =>
raise Constraint_Error with "Cannot convert a date into a discrete type";
when TYPE_BEAN =>
raise Constraint_Error with "Cannot convert a bean into a discrete type";
end case;
end To_Value;
end EL.Objects.Enums;
|
-----------------------------------------------------------------------
-- EL.Objects.Enums -- Helper conversion for discrete types
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
package body EL.Objects.Enums is
use Ada.Characters.Conversions;
Value_Range : constant Long_Long_Integer := T'Pos (T'Last) - T'Pos (T'First) + 1;
-- ------------------------------
-- Integer Type
-- ------------------------------
type Enum_Type is new Int_Type with null record;
-- Get the type name
overriding
function Get_Name (Type_Def : in Enum_Type) return String;
overriding
function To_String (Type_Def : in Enum_Type;
Value : in Object_Value) return String;
-- ------------------------------
-- Get the type name
-- ------------------------------
overriding
function Get_Name (Type_Def : Enum_Type) return String is
pragma Unreferenced (Type_Def);
begin
return "Enum";
end Get_Name;
-- ------------------------------
-- Convert the value into a string.
-- ------------------------------
overriding
function To_String (Type_Def : in Enum_Type;
Value : in Object_Value) return String is
pragma Unreferenced (Type_Def);
begin
return T'Image (T'Val (Value.Int_Value));
end To_String;
Value_Type : aliased constant Enum_Type := Enum_Type '(others => <>);
-- ------------------------------
-- Create an object from the given value.
-- ------------------------------
function To_Object (Value : in T) return Object is
begin
return Object '(Controlled with
V => Object_Value '(Of_Type => TYPE_INTEGER,
Int_Value => Long_Long_Integer (T'Pos (Value))),
Type_Def => Value_Type'Access);
end To_Object;
-- ------------------------------
-- Convert the object into a value.
-- Raises Constraint_Error if the object cannot be converter to the target type.
-- ------------------------------
function To_Value (Value : in EL.Objects.Object) return T is
begin
case Value.V.Of_Type is
when TYPE_INTEGER =>
if ROUND_VALUE then
return T'Val (Value.V.Int_Value mod Value_Range);
else
return T'Val (Value.V.Int_Value);
end if;
when TYPE_BOOLEAN =>
return T'Val (Boolean'Pos (Value.V.Bool_Value));
when TYPE_FLOAT =>
if ROUND_VALUE then
return T'Val (To_Long_Long_Integer (Value) mod Value_Range);
else
return T'Val (To_Long_Long_Integer (Value));
end if;
when TYPE_STRING =>
if Value.V.Proxy = null then
raise Constraint_Error with "The object value is null";
end if;
return T'Value (Value.V.Proxy.String_Value.all);
when TYPE_WIDE_STRING =>
if Value.V.Proxy = null then
raise Constraint_Error with "The object value is null";
end if;
return T'Value (To_String (Value.V.Proxy.Wide_String_Value.all));
when TYPE_NULL =>
raise Constraint_Error with "The object value is null";
when TYPE_TIME =>
raise Constraint_Error with "Cannot convert a date into a discrete type";
when TYPE_BEAN =>
raise Constraint_Error with "Cannot convert a bean into a discrete type";
end case;
end To_Value;
end EL.Objects.Enums;
|
Implement the necessary functions for the enum type definition.
|
Implement the necessary functions for the enum type definition.
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
b4923ba54537ed9463eb454058c8cffa2097da7b
|
src/gen-model-tables.adb
|
src/gen-model-tables.adb
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Util.Strings;
package body Gen.Model.Tables 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 : Column_Definition;
Name : String) return Util.Beans.Objects.Object is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if Name = "type" and From.Type_Mapping /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "index" then
return Util.Beans.Objects.To_Object (From.Number);
elsif Name = "isUnique" then
return Util.Beans.Objects.To_Object (From.Unique);
elsif Name = "isNull" then
return Util.Beans.Objects.To_Object (not From.Not_Null);
elsif Name = "isInserted" then
return Util.Beans.Objects.To_Object (From.Is_Inserted);
elsif Name = "isUpdated" then
return Util.Beans.Objects.To_Object (From.Is_Updated);
elsif Name = "sqlType" then
return Util.Beans.Objects.To_Object (From.Sql_Type);
elsif Name = "sqlName" then
return Util.Beans.Objects.To_Object (From.Sql_Name);
elsif Name = "isVersion" then
return Util.Beans.Objects.To_Object (From.Is_Version);
elsif Name = "isReadable" then
return Util.Beans.Objects.To_Object (From.Is_Readable);
elsif Name = "isPrimaryKey" then
return Util.Beans.Objects.To_Object (From.Is_Key);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Is_Basic_Type);
elsif Name = "generator" then
return From.Generator;
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Returns true if the column type is a basic type.
-- ------------------------------
function Is_Basic_Type (From : Column_Definition) return Boolean is
use type Gen.Model.Mappings.Mapping_Definition_Access;
use type Gen.Model.Mappings.Basic_Type;
Name : constant String := To_String (From.Type_Name);
begin
if From.Type_Mapping /= null then
return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB;
end if;
return Name = "int" or Name = "String"
or Name = "ADO.Identifier" or Name = "Timestamp"
or Name = "Integer"
or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time";
end Is_Basic_Type;
-- ------------------------------
-- Returns the column type.
-- ------------------------------
function Get_Type (From : Column_Definition) return String is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if From.Type_Mapping /= null then
return To_String (From.Type_Mapping.Target);
else
return To_String (From.Type_Name);
end if;
end Get_Type;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Column_Definition) is
begin
O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name);
end Prepare;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
return Column_Definition (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Table_Definition) is
begin
O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Create a table with the given name.
-- ------------------------------
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is
Table : constant Table_Definition_Access := new Table_Definition;
begin
Table.Name := Name;
declare
Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1);
Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end;
return Table;
end Create_Table;
-- ------------------------------
-- Create a table column with the given name and add it to the table.
-- ------------------------------
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access) is
begin
Column := new Column_Definition;
Column.Name := Name;
Column.Number := Table.Members.Get_Count;
Table.Members.Append (Column);
if Name = "version" then
Table.Version_Column := Column;
Column.Is_Version := True;
Column.Is_Updated := False;
Column.Is_Inserted := False;
elsif Name = "id" then
Table.Id_Column := Column;
Column.Is_Key := True;
end if;
end Add_Column;
-- ------------------------------
-- Get the table unique name.
-- ------------------------------
overriding
function Get_Name (From : in Table_Definition) return String is
begin
return From.Get_Attribute ("table");
end Get_Name;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Table_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" or Name = "columns" then
return From.Members_Bean;
elsif Name = "id" and From.Id_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "version" and From.Version_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= From.Version_Column.all'Unchecked_Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "hasAssociations" then
return Util.Beans.Objects.To_Object (From.Has_Associations);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (From.Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Table_Definition) is
Iter : Column_List.Cursor := O.Members.First;
begin
while Column_List.Has_Element (Iter) loop
Column_List.Element (Iter).Prepare;
Column_List.Next (Iter);
end loop;
end Prepare;
-- ------------------------------
-- Set the table name and determines the package name.
-- ------------------------------
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
Table.Name := To_Unbounded_String (Name);
if Pos > 0 then
Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1));
Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end Set_Table_Name;
end Gen.Model.Tables;
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Util.Strings;
package body Gen.Model.Tables 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 : Column_Definition;
Name : String) return Util.Beans.Objects.Object is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if Name = "type" and From.Type_Mapping /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "index" then
return Util.Beans.Objects.To_Object (From.Number);
elsif Name = "isUnique" then
return Util.Beans.Objects.To_Object (From.Unique);
elsif Name = "isNull" then
return Util.Beans.Objects.To_Object (not From.Not_Null);
elsif Name = "isInserted" then
return Util.Beans.Objects.To_Object (From.Is_Inserted);
elsif Name = "isUpdated" then
return Util.Beans.Objects.To_Object (From.Is_Updated);
elsif Name = "sqlType" then
return Util.Beans.Objects.To_Object (From.Sql_Type);
elsif Name = "sqlName" then
return Util.Beans.Objects.To_Object (From.Sql_Name);
elsif Name = "isVersion" then
return Util.Beans.Objects.To_Object (From.Is_Version);
elsif Name = "isReadable" then
return Util.Beans.Objects.To_Object (From.Is_Readable);
elsif Name = "isPrimaryKey" then
return Util.Beans.Objects.To_Object (From.Is_Key);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Is_Basic_Type);
elsif Name = "generator" then
return From.Generator;
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Returns true if the column type is a basic type.
-- ------------------------------
function Is_Basic_Type (From : Column_Definition) return Boolean is
use type Gen.Model.Mappings.Mapping_Definition_Access;
use type Gen.Model.Mappings.Basic_Type;
Name : constant String := To_String (From.Type_Name);
begin
if From.Type_Mapping /= null then
return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB;
end if;
return Name = "int" or Name = "String"
or Name = "ADO.Identifier" or Name = "Timestamp"
or Name = "Integer"
or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time";
end Is_Basic_Type;
-- ------------------------------
-- Returns the column type.
-- ------------------------------
function Get_Type (From : Column_Definition) return String is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if From.Type_Mapping /= null then
return To_String (From.Type_Mapping.Target);
else
return To_String (From.Type_Name);
end if;
end Get_Type;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Column_Definition) is
begin
O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name);
end Prepare;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
return Column_Definition (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Table_Definition) is
begin
O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Create a table with the given name.
-- ------------------------------
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is
Table : constant Table_Definition_Access := new Table_Definition;
begin
Table.Name := Name;
declare
Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1);
Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end;
return Table;
end Create_Table;
-- ------------------------------
-- Create a table column with the given name and add it to the table.
-- ------------------------------
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access) is
begin
Column := new Column_Definition;
Column.Name := Name;
Column.Sql_Name := Name;
Column.Number := Table.Members.Get_Count;
Table.Members.Append (Column);
if Name = "version" then
Table.Version_Column := Column;
Column.Is_Version := True;
Column.Is_Updated := False;
Column.Is_Inserted := False;
elsif Name = "id" then
Table.Id_Column := Column;
Column.Is_Key := True;
end if;
end Add_Column;
-- ------------------------------
-- Get the table unique name.
-- ------------------------------
overriding
function Get_Name (From : in Table_Definition) return String is
begin
return From.Get_Attribute ("table");
end Get_Name;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Table_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" or Name = "columns" then
return From.Members_Bean;
elsif Name = "id" and From.Id_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "version" and From.Version_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= From.Version_Column.all'Unchecked_Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "hasAssociations" then
return Util.Beans.Objects.To_Object (From.Has_Associations);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (From.Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Table_Definition) is
Iter : Column_List.Cursor := O.Members.First;
begin
while Column_List.Has_Element (Iter) loop
Column_List.Element (Iter).Prepare;
Column_List.Next (Iter);
end loop;
end Prepare;
-- ------------------------------
-- Set the table name and determines the package name.
-- ------------------------------
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
Table.Name := To_Unbounded_String (Name);
if Pos > 0 then
Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1));
Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end Set_Table_Name;
end Gen.Model.Tables;
|
Set the SQL name when building the column
|
Set the SQL name when building the column
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
663b5b1b4d9def8697625745527cfb68d0ed4c3a
|
awa/src/awa-modules-reader.adb
|
awa/src/awa-modules-reader.adb
|
-----------------------------------------------------------------------
-- awa-modules-reader -- Read module configuration files
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.XML;
with AWA.Applications.Configs;
-- The <b>AWA.Modules.Reader</b> package reads the module configuration files
-- and initializes the module.
package body AWA.Modules.Reader is
-- ------------------------------
-- Read the module configuration file and configure the components
-- ------------------------------
procedure Read_Configuration (Plugin : in out Module'Class;
File : in String;
Context : in EL.Contexts.Default.Default_Context_Access) is
Reader : Util.Serialize.IO.XML.Parser;
package Config is
new AWA.Applications.Configs.Reader_Config (Reader,
Plugin.App.all'Unchecked_Access,
Context);
pragma Warnings (Off, Config);
begin
Log.Info ("Reading module configuration file {0}", File);
if AWA.Modules.Log.Get_Level >= Util.Log.DEBUG_LEVEL then
Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
end if;
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
exception
when others =>
Log.Error ("Error while reading {0}", File);
raise;
end Read_Configuration;
end AWA.Modules.Reader;
|
-----------------------------------------------------------------------
-- awa-modules-reader -- Read module configuration files
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.XML;
with AWA.Applications.Configs;
with Security.Policies;
-- The <b>AWA.Modules.Reader</b> package reads the module configuration files
-- and initializes the module.
package body AWA.Modules.Reader is
-- ------------------------------
-- Read the module configuration file and configure the components
-- ------------------------------
procedure Read_Configuration (Plugin : in out Module'Class;
File : in String;
Context : in EL.Contexts.Default.Default_Context_Access) is
Reader : Util.Serialize.IO.XML.Parser;
package Config is
new AWA.Applications.Configs.Reader_Config (Reader,
Plugin.App.all'Unchecked_Access,
Context);
pragma Warnings (Off, Config);
Sec : constant Security.Policies.Policy_Manager_Access := Plugin.App.Get_Security_Manager;
begin
Log.Info ("Reading module configuration file {0}", File);
Sec.Prepare_Config (Reader);
if AWA.Modules.Log.Get_Level >= Util.Log.DEBUG_LEVEL then
Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
end if;
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
Sec.Finish_Config (Reader);
exception
when others =>
Log.Error ("Error while reading {0}", File);
raise;
end Read_Configuration;
end AWA.Modules.Reader;
|
Call Prepare_Config on the security manager before reading the module XML configuration
|
Call Prepare_Config on the security manager before reading the module XML configuration
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
30b79df04edbb9cd94c12f689c37b8dad2a0bd76
|
testutil/aunit/util-tests-reporter.ads
|
testutil/aunit/util-tests-reporter.ads
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A U N I T . R E P O R T E R . X M L --
-- --
-- S p e c --
-- --
-- --
-- Copyright (C) 2000-2008, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT is maintained by AdaCore (http://www.adacore.com) --
-- --
------------------------------------------------------------------------------
with AUnit.Reporter;
with AUnit.Test_Results;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
-- XML reporter (fix AUnit issues and generate in a separate file instead of stdout).
package Util.Tests.Reporter is
type XML_Reporter is new AUnit.Reporter.Reporter with record
File : Ada.Strings.Unbounded.Unbounded_String;
end record;
procedure Report (Engine : XML_Reporter;
R : in out AUnit.Test_Results.Result'Class);
procedure Report (Engine : XML_Reporter;
File : in out Ada.Text_IO.File_Type;
R : in out AUnit.Test_Results.Result'Class);
end Util.Tests.Reporter;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A U N I T . R E P O R T E R . X M L --
-- --
-- S p e c --
-- --
-- --
-- Copyright (C) 2000-2008, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT is maintained by AdaCore (http://www.adacore.com) --
-- --
------------------------------------------------------------------------------
with AUnit.Reporter;
with AUnit.Test_Results;
with AUnit.Options;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
-- XML reporter (fix AUnit issues and generate in a separate file instead of stdout).
package Util.Tests.Reporter is
type XML_Reporter is new AUnit.Reporter.Reporter with record
File : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Report (Engine : in XML_Reporter;
R : in out AUnit.Test_Results.Result'Class;
Options : in AUnit.Options.AUnit_Options := AUnit.Options.Default_Options);
procedure Report (Engine : XML_Reporter;
File : in out Ada.Text_IO.File_Type;
R : in out AUnit.Test_Results.Result'Class);
end Util.Tests.Reporter;
|
Fix compilation with AUnit 2014
|
Fix compilation with AUnit 2014
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f0021d2167f8af24ba57a5c4f2bbefa9024a63b6
|
tools/druss-gateways.adb
|
tools/druss-gateways.adb
|
-----------------------------------------------------------------------
-- druss-gateways -- Gateway management
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties.Basic;
with Util.Strings;
with Util.Log.Loggers;
with Util.Http.Clients;
with Bbox.API;
package body Druss.Gateways is
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Gateways");
protected body Gateway_State is
function Get_State return State_Type is
begin
return State;
end Get_State;
end Gateway_State;
function "=" (Left, Right : in Gateway_Ref) return Boolean is
begin
if Left.Value = Right.Value then
return True;
elsif Left.Is_Null or Right.Is_Null then
return False;
else
return Left.Value.IP = Right.Value.IP;
end if;
end "=";
package Int_Property renames Util.Properties.Basic.Integer_Property;
package Bool_Property renames Util.Properties.Basic.Boolean_Property;
-- ------------------------------
-- Initalize the list of gateways from the property list.
-- ------------------------------
procedure Initialize (Config : in Util.Properties.Manager;
List : in out Gateway_Vector) is
Count : constant Natural := Int_Property.Get (Config, "druss.bbox.count", 0);
begin
for I in 1 .. Count loop
declare
Gw : constant Gateway_Ref := Gateway_Refs.Create;
Base : constant String := "druss.bbox." & Util.Strings.Image (I);
begin
Gw.Value.Ip := Config.Get (Base & ".ip");
if Config.Exists (Base & ".images") then
Gw.Value.Images := Config.Get (Base & ".images");
end if;
Gw.Value.Passwd := Config.Get (Base & ".password");
Gw.Value.Serial := Config.Get (Base & ".serial");
Gw.Value.Enable := Bool_Property.Get (Config, Base & ".enable", True);
List.Append (Gw);
exception
when Util.Properties.NO_PROPERTY =>
Log.Debug ("Ignoring gatway {0}", Base);
end;
end loop;
end Initialize;
-- ------------------------------
-- Save the list of gateways.
-- ------------------------------
procedure Save_Gateways (Config : in out Util.Properties.Manager;
List : in Druss.Gateways.Gateway_Vector) is
Pos : Natural := 0;
begin
for Gw of List loop
Pos := Pos + 1;
declare
Base : constant String := "druss.bbox." & Util.Strings.Image (Pos);
begin
Config.Set (Base & ".ip", Gw.Value.Ip);
Config.Set (Base & ".password", Gw.Value.Passwd);
Config.Set (Base & ".serial", Gw.Value.Serial);
Bool_Property.Set (Config, Base & ".enable", Gw.Value.Enable);
exception
when Util.Properties.NO_PROPERTY =>
null;
end;
end loop;
Util.Properties.Basic.Integer_Property.Set (Config, "druss.bbox.count", Pos);
end Save_Gateways;
-- ------------------------------
-- Refresh the information by using the Bbox API.
-- ------------------------------
procedure Refresh (Gateway : in out Gateway_Type) is
Box : Bbox.API.Client_Type;
begin
if Gateway.State.Get_State = BUSY then
return;
end if;
Box.Set_Server (To_String (Gateway.IP));
if Ada.Strings.Unbounded.Length (Gateway.Passwd) > 0 then
Box.Login (To_String (Gateway.Passwd));
end if;
Box.Get ("wan/ip", Gateway.Wan);
Box.Get ("lan/ip", Gateway.Lan);
Box.Get ("device", Gateway.Device);
Box.Get ("wireless", Gateway.Wifi);
Box.Get ("voip", Gateway.Voip);
Box.Get ("iptv", Gateway.IPtv);
Box.Get ("hosts", Gateway.Hosts);
if Gateway.Device.Exists ("device.serialnumber") then
Gateway.Serial := Gateway.Device.Get ("device.serialnumber");
end if;
exception
when Util.Http.Clients.Connection_Error =>
Log.Error ("Cannot connect to {0}", To_String (Gateway.IP));
end Refresh;
-- ------------------------------
-- Refresh the information by using the Bbox API.
-- ------------------------------
procedure Refresh (Gateway : in Gateway_Ref) is
begin
Gateway.Value.Refresh;
end Refresh;
-- ------------------------------
-- Iterate over the list of gateways and execute the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterate (List : in Gateway_Vector;
Mode : in Iterate_Type := ITER_ALL;
Process : not null access procedure (G : in out Gateway_Type)) is
Expect : constant Boolean := Mode = ITER_ENABLE;
begin
for G of List loop
if Mode = ITER_ALL or else G.Value.Enable = Expect then
Process (G.Value.all);
end if;
end loop;
end Iterate;
Null_Gateway : Gateway_Ref;
-- ------------------------------
-- Find the gateway with the given IP address.
-- ------------------------------
function Find_IP (List : in Gateway_Vector;
IP : in String) return Gateway_Ref is
begin
for G of List loop
if G.Value.IP = IP then
return G;
end if;
end loop;
-- raise Not_Found;
return Null_Gateway;
end Find_IP;
end Druss.Gateways;
|
-----------------------------------------------------------------------
-- druss-gateways -- Gateway management
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties.Basic;
with Util.Strings;
with Util.Log.Loggers;
with Util.Http.Clients;
package body Druss.Gateways is
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Gateways");
protected body Gateway_State is
function Get_State return State_Type is
begin
return State;
end Get_State;
end Gateway_State;
function "=" (Left, Right : in Gateway_Ref) return Boolean is
begin
if Left.Value = Right.Value then
return True;
elsif Left.Is_Null or Right.Is_Null then
return False;
else
return Left.Value.Ip = Right.Value.Ip;
end if;
end "=";
package Int_Property renames Util.Properties.Basic.Integer_Property;
package Bool_Property renames Util.Properties.Basic.Boolean_Property;
-- ------------------------------
-- Initalize the list of gateways from the property list.
-- ------------------------------
procedure Initialize (Config : in Util.Properties.Manager;
List : in out Gateway_Vector) is
Count : constant Natural := Int_Property.Get (Config, "druss.bbox.count", 0);
begin
for I in 1 .. Count loop
declare
Gw : constant Gateway_Ref := Gateway_Refs.Create;
Base : constant String := "druss.bbox." & Util.Strings.Image (I);
begin
Gw.Value.Ip := Config.Get (Base & ".ip");
if Config.Exists (Base & ".images") then
Gw.Value.Images := Config.Get (Base & ".images");
end if;
Gw.Value.Passwd := Config.Get (Base & ".password");
Gw.Value.Serial := Config.Get (Base & ".serial");
Gw.Value.Enable := Bool_Property.Get (Config, Base & ".enable", True);
List.Append (Gw);
exception
when Util.Properties.NO_PROPERTY =>
Log.Debug ("Ignoring gatway {0}", Base);
end;
end loop;
end Initialize;
-- ------------------------------
-- Save the list of gateways.
-- ------------------------------
procedure Save_Gateways (Config : in out Util.Properties.Manager;
List : in Druss.Gateways.Gateway_Vector) is
Pos : Natural := 0;
begin
for Gw of List loop
Pos := Pos + 1;
declare
Base : constant String := "druss.bbox." & Util.Strings.Image (Pos);
begin
Config.Set (Base & ".ip", Gw.Value.Ip);
Config.Set (Base & ".password", Gw.Value.Passwd);
Config.Set (Base & ".serial", Gw.Value.Serial);
Bool_Property.Set (Config, Base & ".enable", Gw.Value.Enable);
exception
when Util.Properties.NO_PROPERTY =>
null;
end;
end loop;
Util.Properties.Basic.Integer_Property.Set (Config, "druss.bbox.count", Pos);
end Save_Gateways;
-- ------------------------------
-- Refresh the information by using the Bbox API.
-- ------------------------------
procedure Refresh (Gateway : in out Gateway_Type) is
Box : Bbox.API.Client_Type;
begin
if Gateway.State.Get_State = BUSY then
return;
end if;
Box.Set_Server (To_String (Gateway.Ip));
if Ada.Strings.Unbounded.Length (Gateway.Passwd) > 0 then
Box.Login (To_String (Gateway.Passwd));
end if;
Box.Get ("wan/ip", Gateway.Wan);
Box.Get ("lan/ip", Gateway.Lan);
Box.Get ("device", Gateway.Device);
Box.Get ("wireless", Gateway.Wifi);
Box.Get ("voip", Gateway.Voip);
Box.Get ("iptv", Gateway.IPtv);
Box.Get ("hosts", Gateway.Hosts);
if Gateway.Device.Exists ("device.serialnumber") then
Gateway.Serial := Gateway.Device.Get ("device.serialnumber");
end if;
exception
when Util.Http.Clients.Connection_Error =>
Log.Error ("Cannot connect to {0}", To_String (Gateway.Ip));
end Refresh;
-- ------------------------------
-- Refresh the information by using the Bbox API.
-- ------------------------------
procedure Refresh (Gateway : in Gateway_Ref) is
begin
Gateway.Value.Refresh;
end Refresh;
-- ------------------------------
-- Iterate over the list of gateways and execute the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterate (List : in Gateway_Vector;
Mode : in Iterate_Type := ITER_ALL;
Process : not null access procedure (G : in out Gateway_Type)) is
Expect : constant Boolean := Mode = ITER_ENABLE;
begin
for G of List loop
if Mode = ITER_ALL or else G.Value.Enable = Expect then
Process (G.Value.all);
end if;
end loop;
end Iterate;
Null_Gateway : Gateway_Ref;
-- ------------------------------
-- Find the gateway with the given IP address.
-- ------------------------------
function Find_IP (List : in Gateway_Vector;
IP : in String) return Gateway_Ref is
begin
for G of List loop
if G.Value.Ip = IP then
return G;
end if;
end loop;
Log.Debug ("No gateway with IP {0}", IP);
return Null_Gateway;
end Find_IP;
end Druss.Gateways;
|
Fix compilation warnings and add a debug log message
|
Fix compilation warnings and add a debug log message
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
7a8f3c873524dbc9aab147b135327d2ee0f983f1
|
regtests/asf-applications-tests.ads
|
regtests/asf-applications-tests.ads
|
-----------------------------------------------------------------------
-- asf-applications-tests - ASF Application tests using ASFUnit
-- 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;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Methods;
with Util.Beans.Basic.Lists;
with Ada.Strings.Unbounded;
package ASF.Applications.Tests is
use Ada.Strings.Unbounded;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Initialize the test application
overriding
procedure Set_Up (T : in out Test);
-- Test a GET request on a static file served by the File_Servlet.
procedure Test_Get_File (T : in out Test);
-- Test a GET 404 error on missing static file served by the File_Servlet.
procedure Test_Get_404 (T : in out Test);
-- Test a GET request on the measure servlet
procedure Test_Get_Measures (T : in out Test);
-- Test an invalid HTTP request.
procedure Test_Invalid_Request (T : in out Test);
-- Test a GET+POST request with submitted values and an action method called on the bean.
procedure Test_Form_Post (T : in out Test);
-- Test a POST request with an invalid submitted value
procedure Test_Form_Post_Validation_Error (T : in out Test);
-- Test a GET+POST request with form having <h:selectOneMenu> element.
procedure Test_Form_Post_Select (T : in out Test);
-- Test a POST request to invoke a bean method.
procedure Test_Ajax_Action (T : in out Test);
-- Test a POST request to invoke a bean method.
-- Verify that invalid requests raise an error.
procedure Test_Ajax_Action_Error (T : in out Test);
-- Test a POST/REDIRECT/GET request with a flash information passed in between.
procedure Test_Flash_Object (T : in out Test);
-- Test a GET+POST request with the default navigation rule based on the outcome.
procedure Test_Default_Navigation_Rule (T : in out Test);
-- Test a GET request with meta data and view parameters.
procedure Test_View_Params (T : in out Test);
-- Test a GET request with meta data and view action.
procedure Test_View_Action (T : in out Test);
type Form_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record
Name : Unbounded_String;
Password : Unbounded_String;
Email : Unbounded_String;
Called : Natural := 0;
Gender : Unbounded_String;
Use_Flash : Boolean := False;
Def_Nav : Boolean := False;
end record;
type Form_Bean_Access is access all Form_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Form_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Form_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Form_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Action to save the form
procedure Save (Data : in out Form_Bean;
Outcome : in out Unbounded_String);
-- Create a list of forms.
package Form_Lists is
new Util.Beans.Basic.Lists (Form_Bean);
-- Create a list of forms.
function Create_Form_List return Util.Beans.Basic.Readonly_Bean_Access;
-- Initialize the ASF application for the unit test.
procedure Initialize_Test_Application;
end ASF.Applications.Tests;
|
-----------------------------------------------------------------------
-- asf-applications-tests - ASF Application tests using ASFUnit
-- 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;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Methods;
with Util.Beans.Basic.Lists;
with Ada.Strings.Unbounded;
package ASF.Applications.Tests is
use Ada.Strings.Unbounded;
Test_Exception : exception;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Initialize the test application
overriding
procedure Set_Up (T : in out Test);
-- Test a GET request on a static file served by the File_Servlet.
procedure Test_Get_File (T : in out Test);
-- Test a GET 404 error on missing static file served by the File_Servlet.
procedure Test_Get_404 (T : in out Test);
-- Test a GET request on the measure servlet
procedure Test_Get_Measures (T : in out Test);
-- Test an invalid HTTP request.
procedure Test_Invalid_Request (T : in out Test);
-- Test a GET+POST request with submitted values and an action method called on the bean.
procedure Test_Form_Post (T : in out Test);
-- Test a POST request with an invalid submitted value
procedure Test_Form_Post_Validation_Error (T : in out Test);
-- Test a GET+POST request with form having <h:selectOneMenu> element.
procedure Test_Form_Post_Select (T : in out Test);
-- Test a POST request to invoke a bean method.
procedure Test_Ajax_Action (T : in out Test);
-- Test a POST request to invoke a bean method.
-- Verify that invalid requests raise an error.
procedure Test_Ajax_Action_Error (T : in out Test);
-- Test a POST/REDIRECT/GET request with a flash information passed in between.
procedure Test_Flash_Object (T : in out Test);
-- Test a GET+POST request with the default navigation rule based on the outcome.
procedure Test_Default_Navigation_Rule (T : in out Test);
-- Test a GET request with meta data and view parameters.
procedure Test_View_Params (T : in out Test);
-- Test a GET request with meta data and view action.
procedure Test_View_Action (T : in out Test);
type Form_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record
Name : Unbounded_String;
Password : Unbounded_String;
Email : Unbounded_String;
Called : Natural := 0;
Gender : Unbounded_String;
Use_Flash : Boolean := False;
Def_Nav : Boolean := False;
Perm_Error : Boolean := False;
end record;
type Form_Bean_Access is access all Form_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Form_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Form_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Form_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Action to save the form
procedure Save (Data : in out Form_Bean;
Outcome : in out Unbounded_String);
-- Create a list of forms.
package Form_Lists is
new Util.Beans.Basic.Lists (Form_Bean);
-- Create a list of forms.
function Create_Form_List return Util.Beans.Basic.Readonly_Bean_Access;
-- Initialize the ASF application for the unit test.
procedure Initialize_Test_Application;
end ASF.Applications.Tests;
|
Add flag on form bean to raise an exception in the action bean
|
Add flag on form bean to raise an exception in the action bean
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
be39e6df61414449417b76a3b093e208821d09c2
|
src/wiki-render-html.adb
|
src/wiki-render-html.adb
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Util.Strings;
package body Wiki.Render.Html is
package ACC renames Ada.Characters.Conversions;
-- ------------------------------
-- Set the output stream.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the link renderer.
-- ------------------------------
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access) is
begin
Document.Links := Links;
end Set_Link_Renderer;
-- ------------------------------
-- Render the node instance from the document.
-- ------------------------------
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Add_Header (Header => Node.Header,
Level => Node.Level);
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Output.Start_Element ("br");
Engine.Output.End_Element ("br");
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
Engine.Output.Start_Element ("hr");
Engine.Output.End_Element ("hr");
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
when Wiki.Nodes.N_INDENT =>
Engine.Indent_Level := Node.Level;
when Wiki.Nodes.N_TEXT =>
if Engine.Empty_Line and Engine.Indent_Level /= 0 then
for I in 1 .. Engine.Indent_Level loop
Engine.Output.Write (' ');
end loop;
end if;
Engine.Output.Write (Node.Text);
Engine.Empty_Line := False;
when Wiki.Nodes.N_QUOTE =>
Engine.Open_Paragraph;
Engine.Output.Write (Node.Quote);
Engine.Empty_Line := False;
when Wiki.Nodes.N_LINK =>
Engine.Add_Link (Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_IMAGE =>
null;
when Wiki.Nodes.N_BLOCKQUOTE =>
null;
when Wiki.Nodes.N_TAG_START =>
if Node.Children /= null then
if Node.Tag_Start = Wiki.Nodes.DT_TAG then
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
elsif Node.Tag_Start = Wiki.Nodes.DD_TAG then
Engine.Close_Paragraph;
Engine.Empty_Line := True;
Engine.Indent_Level := 4;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
else
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.Nodes.DL_TAG then
Engine.Close_Paragraph;
Engine.New_Line;
end if;
end if;
end if;
end case;
end Render;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
case Level is
when 1 =>
Engine.Output.Write_Wide_Element ("h1", Header);
when 2 =>
Engine.Output.Write_Wide_Element ("h2", Header);
when 3 =>
Engine.Output.Write_Wide_Element ("h3", Header);
when 4 =>
Engine.Output.Write_Wide_Element ("h4", Header);
when 5 =>
Engine.Output.Write_Wide_Element ("h5", Header);
when 6 =>
Engine.Output.Write_Wide_Element ("h6", Header);
when others =>
Engine.Output.Write_Wide_Element ("h3", Header);
end case;
end Add_Header;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Writer.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Writer.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Writer.Start_Element ("ol");
else
Document.Writer.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Writer.End_Element ("ol");
else
Document.Writer.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Need_Paragraph then
Document.Writer.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Writer.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
Exists : Boolean;
URI : Unbounded_Wide_Wide_String;
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("a");
if Length (Title) > 0 then
Document.Writer.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
Document.Links.Make_Page_Link (Link, URI, Exists);
Document.Writer.Write_Wide_Attribute ("href", URI);
Document.Writer.Write_Wide_Text (Name);
Document.Writer.End_Element ("a");
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
URI : Unbounded_Wide_Wide_String;
Width : Natural;
Height : Natural;
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("img");
if Length (Alt) > 0 then
Document.Writer.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Links.Make_Image_Link (Link, URI, Width, Height);
Document.Writer.Write_Wide_Attribute ("src", URI);
if Width > 0 then
Document.Writer.Write_Attribute ("width", Natural'Image (Width));
end if;
if Height > 0 then
Document.Writer.Write_Attribute ("height", Natural'Image (Height));
end if;
Document.Writer.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("q");
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Writer.Write_Wide_Attribute ("cite", Link);
end if;
Document.Writer.Write_Wide_Text (Quote);
Document.Writer.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(Documents.BOLD => HTML_BOLD'Access,
Documents.ITALIC => HTML_ITALIC'Access,
Documents.CODE => HTML_CODE'Access,
Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access,
Documents.STRIKEOUT => HTML_STRIKEOUT'Access,
Documents.PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
Document.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Document.Writer.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Document.Writer.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Document.Writer.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Writer.Write (Text);
else
Document.Writer.Start_Element ("pre");
Document.Writer.Write_Wide_Text (Text);
Document.Writer.End_Element ("pre");
end if;
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Attributes);
begin
Document.Html_Level := Document.Html_Level + 1;
if Name = "p" then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
Document.Writer.Start_Element (ACC.To_String (To_Wide_Wide_String (Name)));
while Wiki.Attributes.Has_Element (Iter) loop
Document.Writer.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
end Start_Element;
overriding
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Html_Level := Document.Html_Level - 1;
if Name = "p" then
Document.Has_Paragraph := False;
Document.Need_Paragraph := True;
end if;
Document.Writer.End_Element (ACC.To_String (To_Wide_Wide_String (Name)));
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Renderer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Util.Strings;
package body Wiki.Render.Html is
package ACC renames Ada.Characters.Conversions;
-- ------------------------------
-- Set the output stream.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the link renderer.
-- ------------------------------
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access) is
begin
Document.Links := Links;
end Set_Link_Renderer;
-- ------------------------------
-- Render the node instance from the document.
-- ------------------------------
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Add_Header (Header => Node.Header,
Level => Node.Level);
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Output.Start_Element ("br");
Engine.Output.End_Element ("br");
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
Engine.Output.Start_Element ("hr");
Engine.Output.End_Element ("hr");
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
when Wiki.Nodes.N_INDENT =>
-- Engine.Indent_Level := Node.Level;
null;
when Wiki.Nodes.N_TEXT =>
Engine.Add_Text (Text => Node.Text,
Format => Node.Format);
when Wiki.Nodes.N_QUOTE =>
Engine.Open_Paragraph;
Engine.Output.Write (Node.Quote);
when Wiki.Nodes.N_LINK =>
Engine.Add_Link (Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_IMAGE =>
null;
when Wiki.Nodes.N_BLOCKQUOTE =>
null;
when Wiki.Nodes.N_TAG_START =>
Engine.Render_Tag (Doc, Node);
end case;
end Render;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start);
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes);
begin
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := True;
Engine.Need_Paragraph := False;
end if;
Engine.Output.Start_Element (Name.all);
while Wiki.Attributes.Has_Element (Iter) loop
Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := False;
Engine.Need_Paragraph := True;
end if;
Engine.Output.End_Element (Name.all);
end Render_Tag;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
case Level is
when 1 =>
Engine.Output.Write_Wide_Element ("h1", Header);
when 2 =>
Engine.Output.Write_Wide_Element ("h2", Header);
when 3 =>
Engine.Output.Write_Wide_Element ("h3", Header);
when 4 =>
Engine.Output.Write_Wide_Element ("h4", Header);
when 5 =>
Engine.Output.Write_Wide_Element ("h5", Header);
when 6 =>
Engine.Output.Write_Wide_Element ("h6", Header);
when others =>
Engine.Output.Write_Wide_Element ("h3", Header);
end case;
end Add_Header;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Output.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Output.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Output.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Output.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Output.Start_Element ("ol");
else
Document.Output.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Has_Paragraph then
Document.Output.End_Element ("p");
end if;
if Document.Has_Item then
Document.Output.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Output.End_Element ("ol");
else
Document.Output.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Need_Paragraph then
Document.Output.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Output.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
Exists : Boolean;
URI : Unbounded_Wide_Wide_String;
begin
Document.Open_Paragraph;
Document.Output.Start_Element ("a");
if Length (Title) > 0 then
Document.Output.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Output.Write_Wide_Attribute ("lang", Language);
end if;
Document.Links.Make_Page_Link (Link, URI, Exists);
Document.Output.Write_Wide_Attribute ("href", URI);
Document.Output.Write_Wide_Text (Name);
Document.Output.End_Element ("a");
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
URI : Unbounded_Wide_Wide_String;
Width : Natural;
Height : Natural;
begin
Document.Open_Paragraph;
Document.Output.Start_Element ("img");
if Length (Alt) > 0 then
Document.Output.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Output.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Links.Make_Image_Link (Link, URI, Width, Height);
Document.Output.Write_Wide_Attribute ("src", URI);
if Width > 0 then
Document.Output.Write_Attribute ("width", Natural'Image (Width));
end if;
if Height > 0 then
Document.Output.Write_Attribute ("height", Natural'Image (Height));
end if;
Document.Output.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Output.Start_Element ("q");
if Length (Language) > 0 then
Document.Output.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Output.Write_Wide_Attribute ("cite", Link);
end if;
Document.Output.Write_Wide_Text (Quote);
Document.Output.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(Documents.BOLD => HTML_BOLD'Access,
Documents.ITALIC => HTML_ITALIC'Access,
Documents.CODE => HTML_CODE'Access,
Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access,
Documents.STRIKEOUT => HTML_STRIKEOUT'Access,
Documents.PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Documents.Format_Map) is
begin
Engine.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Engine.Output.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Engine.Output.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Engine.Output.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Output.Write (Text);
else
Document.Output.Start_Element ("pre");
-- Document.Output.Write_Wide_Text (Text);
Document.Output.End_Element ("pre");
end if;
end Add_Preformatted;
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Attributes);
begin
Document.Html_Level := Document.Html_Level + 1;
if Name = "p" then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
Document.Output.Start_Element (ACC.To_String (To_Wide_Wide_String (Name)));
while Wiki.Attributes.Has_Element (Iter) loop
Document.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
end Start_Element;
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Html_Level := Document.Html_Level - 1;
if Name = "p" then
Document.Has_Paragraph := False;
Document.Need_Paragraph := True;
end if;
Document.Output.End_Element (ACC.To_String (To_Wide_Wide_String (Name)));
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Renderer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end Wiki.Render.Html;
|
Implement the Render_Tag operation
|
Implement the Render_Tag operation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
ececc1786a1c5955db6a429b222662419696f742
|
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;
-- == Introduction ==
-- 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");
--
-- === Connection string ===
-- The database connection string is an URI that specifies the database driver to use as well
-- as the information for the database driver to connect to the database.
-- The driver connection is a string of the form:
--
-- driver://[host][:port]/[database][?property1][=value1]...
--
-- The database connection string is passed to the session factory that maintains connections
-- to the database (see ADO.Sessions.Factory).
--
package ADO.Drivers is
use Ada.Strings.Unbounded;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- Raised for all errors reported by the database
DB_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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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 when the connection URI is invalid.
Connection_Error : exception;
-- Raised for all errors reported by the database
DB_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 some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
d081090a5dc4aed384d382141feba638fbb02a77
|
awa/plugins/awa-wikis/regtests/awa-wikis-tests.ads
|
awa/plugins/awa-wikis/regtests/awa-wikis-tests.ads
|
-----------------------------------------------------------------------
-- awa-wikis-tests -- Unit tests for wikis module
-- Copyright (C) 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with AWA.Tests;
with Servlet.requests.Mockup;
with Servlet.Responses.Mockup;
with Ada.Strings.Unbounded;
package AWA.Wikis.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Wiki_Ident : Ada.Strings.Unbounded.Unbounded_String;
Page_Ident : Ada.Strings.Unbounded.Unbounded_String;
Image_Ident : Ada.Strings.Unbounded.Unbounded_String;
end record;
-- Setup an image for the wiki page.
procedure Make_Wiki_Image (T : in out Test);
-- Create a wiki page.
procedure Create_Page (T : in out Test;
Request : in out Servlet.Requests.Mockup.Request;
Reply : in out Servlet.Responses.Mockup.Response;
Name : in String;
Title : in String);
-- Get some access on the wiki page as anonymous users.
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String);
-- Verify that the wiki lists contain the given page.
procedure Verify_List_Contains (T : in out Test;
Page : in String);
-- Test access to the wiki as anonymous user.
procedure Test_Anonymous_Access (T : in out Test);
-- Test creation of wiki space and page by simulating web requests.
procedure Test_Create_Wiki (T : in out Test);
-- Test getting a wiki page which does not exist.
procedure Test_Missing_Page (T : in out Test);
-- Test creation of wiki page with an image.
procedure Test_Page_With_Image (T : in out Test);
end AWA.Wikis.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-tests -- Unit tests for wikis module
-- 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;
with AWA.Tests;
with Servlet.requests.Mockup;
with Servlet.Responses.Mockup;
with Ada.Strings.Unbounded;
package AWA.Wikis.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Wiki_Ident : Ada.Strings.Unbounded.Unbounded_String;
Page_Ident : Ada.Strings.Unbounded.Unbounded_String;
Image_Ident : Ada.Strings.Unbounded.Unbounded_String;
Image_Link : Ada.Strings.Unbounded.Unbounded_String;
end record;
-- Setup an image for the wiki page.
procedure Make_Wiki_Image (T : in out Test);
-- Create a wiki page.
procedure Create_Page (T : in out Test;
Request : in out Servlet.Requests.Mockup.Request;
Reply : in out Servlet.Responses.Mockup.Response;
Name : in String;
Title : in String);
-- Get some access on the wiki page as anonymous users.
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String);
-- Verify that the wiki lists contain the given page.
procedure Verify_List_Contains (T : in out Test;
Page : in String);
-- Test access to the wiki as anonymous user.
procedure Test_Anonymous_Access (T : in out Test);
-- Test creation of wiki space and page by simulating web requests.
procedure Test_Create_Wiki (T : in out Test);
-- Test getting a wiki page which does not exist.
procedure Test_Missing_Page (T : in out Test);
-- Test creation of wiki page with an image.
procedure Test_Page_With_Image (T : in out Test);
end AWA.Wikis.Tests;
|
Add Image_Link in the Test record
|
Add Image_Link in the Test record
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b5534bb4a994c3ed3616e3d78921422cafbfe6de
|
src/mysql/ado-drivers-connections-mysql.ads
|
src/mysql/ado-drivers-connections-mysql.ads
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- 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 Mysql.Mysql; use Mysql.Mysql;
package ADO.Drivers.Connections.Mysql is
type Mysql_Driver is limited private;
-- Initialize the Mysql driver.
procedure Initialize;
private
-- Create a new MySQL connection using the configuration parameters.
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : out Database_Connection_Access);
type Mysql_Driver is new ADO.Drivers.Connections.Driver with null record;
-- Deletes the Mysql driver.
overriding
procedure Finalize (D : in out Mysql_Driver);
-- Database connection implementation
type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record
Name : Unbounded_String := Null_Unbounded_String;
Server_Name : Unbounded_String := Null_Unbounded_String;
Login_Name : Unbounded_String := Null_Unbounded_String;
Password : Unbounded_String := Null_Unbounded_String;
Connected : Boolean := False;
Server : Mysql_Access := null;
-- MySQL autocommit flag
Autocommit : Boolean := True;
end record;
type Database_Connection_Access is access all Database_Connection'Class;
-- Get the database driver which manages this connection.
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access;
-- Create a delete statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access;
-- Create an insert statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access;
-- Create an update statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access;
-- Start a transaction.
overriding
procedure Begin_Transaction (Database : in out Database_Connection);
-- Commit the current transaction.
overriding
procedure Commit (Database : in out Database_Connection);
-- Rollback the current transaction.
overriding
procedure Rollback (Database : in out Database_Connection);
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String);
-- Closes the database connection
overriding
procedure Close (Database : in out Database_Connection);
overriding
procedure Finalize (Database : in out Database_Connection);
-- Load the database schema definition for the current database.
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition);
end ADO.Drivers.Connections.Mysql;
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- 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 Mysql.Mysql; use Mysql.Mysql;
package ADO.Drivers.Connections.Mysql is
type Mysql_Driver is limited private;
-- Initialize the Mysql driver.
procedure Initialize;
private
-- Create a new MySQL connection using the configuration parameters.
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : out Database_Connection_Access);
type Mysql_Driver is new ADO.Drivers.Connections.Driver with record
Id : Natural := 0;
end record;
-- Deletes the Mysql driver.
overriding
procedure Finalize (D : in out Mysql_Driver);
-- Database connection implementation
type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record
Name : Unbounded_String := Null_Unbounded_String;
Server_Name : Unbounded_String := Null_Unbounded_String;
Login_Name : Unbounded_String := Null_Unbounded_String;
Password : Unbounded_String := Null_Unbounded_String;
Server : Mysql_Access := null;
Connected : Boolean := False;
-- MySQL autocommit flag
Autocommit : Boolean := True;
end record;
type Database_Connection_Access is access all Database_Connection'Class;
-- Get the database driver which manages this connection.
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access;
-- Create a delete statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access;
-- Create an insert statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access;
-- Create an update statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access;
-- Start a transaction.
overriding
procedure Begin_Transaction (Database : in out Database_Connection);
-- Commit the current transaction.
overriding
procedure Commit (Database : in out Database_Connection);
-- Rollback the current transaction.
overriding
procedure Rollback (Database : in out Database_Connection);
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String);
-- Closes the database connection
overriding
procedure Close (Database : in out Database_Connection);
overriding
procedure Finalize (Database : in out Database_Connection);
-- Load the database schema definition for the current database.
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition);
end ADO.Drivers.Connections.Mysql;
|
Add a connection identifier
|
Add a connection identifier
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
e7d02a1cc2114950c4a4c4e6fe6620879c395bd9
|
src/asf-components-core-factory.ads
|
src/asf-components-core-factory.ads
|
-----------------------------------------------------------------------
-- core-factory -- Factory for UI Core Components
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Factory;
package ASF.Components.Core.Factory is
use ASF;
-- Get the Core component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
end ASF.Components.Core.Factory;
|
-----------------------------------------------------------------------
-- core-factory -- Factory for UI Core Components
-- Copyright (C) 2009, 2010, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Factory;
package ASF.Components.Core.Factory is
-- Register the Core component factory.
procedure Register (Factory : in out ASF.Factory.Component_Factory);
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
|
49e2ad2495988c97031ce5e59fcddd3756dbc9b3
|
awa/plugins/awa-storages/src/awa-storages-stores-databases.adb
|
awa/plugins/awa-storages/src/awa-storages-stores-databases.adb
|
-----------------------------------------------------------------------
-- awa-storages-stores-databases -- Database store
-- Copyright (C) 2012, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Util.Log.Loggers;
package body AWA.Storages.Stores.Databases is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Stores.Files");
-- Create a storage
procedure Create (Storage : in Database_Store;
Session : in out ADO.Sessions.Master_Session;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File) is
begin
Storage.Tmp.Create (Session, From, Into);
end Create;
-- ------------------------------
-- 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 Database_Store;
Session : in out ADO.Sessions.Master_Session;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is
pragma Unreferenced (Storage);
Store : AWA.Storages.Models.Storage_Data_Ref;
Blob : constant ADO.Blob_Ref := ADO.Create_Blob (Path);
begin
Log.Info ("Save database file {0}", Path);
Store.Set_Data (Blob);
Store.Save (Session);
Into.Set_Store_Data (Store);
end Save;
procedure Load (Storage : in Database_Store;
Session : in out ADO.Sessions.Session'Class;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File) is
Store : AWA.Storages.Models.Storage_Data_Ref'Class := From.Get_Store_Data;
File : Ada.Streams.Stream_IO.File_Type;
DB : ADO.Sessions.Master_Session := ADO.Sessions.Master_Session (Session);
begin
Storage.Tmp.Create (DB, From, Into);
Log.Info ("Load database file {0} to {1}",
ADO.Identifier'Image (Store.Get_Id), Get_Path (Into));
Store.Load (Session, Store.Get_Id);
Ada.Streams.Stream_IO.Create (File => File,
Mode => Ada.Streams.Stream_IO.Out_File,
Name => Get_Path (Into));
Ada.Streams.Stream_IO.Write (File, Store.Get_Data.Value.Data);
Ada.Streams.Stream_IO.Close (File);
end Load;
-- ------------------------------
-- Delete the content associate with the storage represented by `From`.
-- ------------------------------
procedure Delete (Storage : in Database_Store;
Session : in out ADO.Sessions.Master_Session;
From : in out AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Storage);
Store : AWA.Storages.Models.Storage_Data_Ref'Class := From.Get_Store_Data;
begin
if not Store.Is_Null then
Log.Info ("Delete file {0}", ADO.Identifier'Image (From.Get_Id));
Store.Delete (Session);
end if;
end Delete;
end AWA.Storages.Stores.Databases;
|
-----------------------------------------------------------------------
-- awa-storages-stores-databases -- Database store
-- Copyright (C) 2012, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Util.Log.Loggers;
package body AWA.Storages.Stores.Databases is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Stores.Files");
-- Create a storage
procedure Create (Storage : in Database_Store;
Session : in out ADO.Sessions.Master_Session;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File) is
begin
Storage.Tmp.Create (Session, From, Into);
end Create;
-- ------------------------------
-- 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 Database_Store;
Session : in out ADO.Sessions.Master_Session;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is
pragma Unreferenced (Storage);
Store : AWA.Storages.Models.Storage_Data_Ref;
Blob : constant ADO.Blob_Ref := ADO.Create_Blob (Path);
begin
Log.Info ("Save database file {0}", Path);
Store.Set_Data (Blob);
Store.Save (Session);
Into.Set_File_Size (Natural (Blob.Value.Len));
Into.Set_Store_Data (Store);
end Save;
procedure Load (Storage : in Database_Store;
Session : in out ADO.Sessions.Session'Class;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File) is
Store : AWA.Storages.Models.Storage_Data_Ref'Class := From.Get_Store_Data;
File : Ada.Streams.Stream_IO.File_Type;
DB : ADO.Sessions.Master_Session := ADO.Sessions.Master_Session (Session);
begin
Storage.Tmp.Create (DB, From, Into);
Log.Info ("Load database file {0} to {1}",
ADO.Identifier'Image (Store.Get_Id), Get_Path (Into));
Store.Load (Session, Store.Get_Id);
Ada.Streams.Stream_IO.Create (File => File,
Mode => Ada.Streams.Stream_IO.Out_File,
Name => Get_Path (Into));
Ada.Streams.Stream_IO.Write (File, Store.Get_Data.Value.Data);
Ada.Streams.Stream_IO.Close (File);
end Load;
-- ------------------------------
-- Delete the content associate with the storage represented by `From`.
-- ------------------------------
procedure Delete (Storage : in Database_Store;
Session : in out ADO.Sessions.Master_Session;
From : in out AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Storage);
Store : AWA.Storages.Models.Storage_Data_Ref'Class := From.Get_Store_Data;
begin
if not Store.Is_Null then
Log.Info ("Delete file {0}", ADO.Identifier'Image (From.Get_Id));
Store.Delete (Session);
end if;
end Delete;
end AWA.Storages.Stores.Databases;
|
Update the file size when we save the blob
|
Update the file size when we save the blob
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b236dd3b6373c5808ac5ea894ae4e1129a1338bb
|
src/core/texts/util-texts-builders.ads
|
src/core/texts/util-texts-builders.ads
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Finalization;
-- == Text Builders ==
-- The `Util.Texts.Builders` generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The `Builder` type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an `Append` procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the `Iterate` operation that allows to get the content
-- collected by the builder. When using the `Iterate` operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that receives
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the `Iterate` operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
generic
type Element_Type is (<>);
type Input is array (Positive range <>) of Element_Type;
Chunk_Size : Positive := 80;
package Util.Texts.Builders is
pragma Preelaborate;
type Builder (Len : Positive) is limited private;
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Input);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Element_Type);
generic
with procedure Process (Content : in out Input; Last : out Natural);
procedure Inline_Append (Source : in out Builder);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input));
generic
with procedure Process (Content : in Input);
procedure Inline_Iterate (Source : in Builder);
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Input;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Input;
-- Get the element at the given position.
function Element (Source : in Builder;
Position : in Positive) return Element_Type;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Input);
procedure Get (Source : in Builder);
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
generic
type Value is limited private;
type Value_List is array (Positive range <>) of Value;
with procedure Append (Input : in out Builder; Item : in Value);
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List);
private
pragma Inline (Length);
pragma Inline (Iterate);
type Block;
type Block_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Block_Access;
Last : Natural := 0;
Content : Input (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Block_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Block (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
end Util.Texts.Builders;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Finalization;
-- == Text Builders ==
-- The `Util.Texts.Builders` generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The `Builder` type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an `Append` procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the `Iterate` operation that allows to get the content
-- collected by the builder. When using the `Iterate` operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that receives
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the `Iterate` operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
generic
type Element_Type is (<>);
type Input is array (Positive range <>) of Element_Type;
Chunk_Size : Positive := 80;
package Util.Texts.Builders is
pragma Preelaborate;
type Builder (Len : Positive) is limited private;
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Input);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Element_Type);
generic
with procedure Process (Content : in out Input; Last : out Natural);
procedure Inline_Append (Source : in out Builder);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input));
generic
with procedure Process (Content : in Input);
procedure Inline_Iterate (Source : in Builder);
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Input;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Input;
-- Get the element at the given position.
function Element (Source : in Builder;
Position : in Positive) return Element_Type;
-- Find the position of some content by running the `Index` function.
-- The `Index` function is called with chunks starting at the given position and
-- until it returns a positive value or we reach the last chunk. It must return
-- the found position in the chunk.
generic
with function Index (Content : in Input) return Natural;
function Find (Source : in Builder;
Position : in Positive) return Natural;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Input);
procedure Get (Source : in Builder);
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
generic
type Value is limited private;
type Value_List is array (Positive range <>) of Value;
with procedure Append (Input : in out Builder; Item : in Value);
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List);
private
pragma Inline (Length);
pragma Inline (Iterate);
type Block;
type Block_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Block_Access;
Last : Natural := 0;
Content : Input (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Block_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Block (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
end Util.Texts.Builders;
|
Add the Find generic function to find some content using an Index function
|
Add the Find generic function to find some content using an Index function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8c2ae617ad950338d2cdb33a9f861b7260a80d61
|
src/sys/streams/util-streams-pipes.adb
|
src/sys/streams/util-streams-pipes.adb
|
-----------------------------------------------------------------------
-- util-streams-raw -- Raw streams for Unix based systems
-- Copyright (C) 2011, 2013, 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;
package body Util.Streams.Pipes is
-- -----------------------
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
-- -----------------------
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String) is
begin
Util.Processes.Set_Shell (Stream.Proc, Shell);
end Set_Shell;
-- -----------------------
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
-- -----------------------
procedure Set_Input_Stream (Stream : in out Pipe_Stream;
File : in String) is
begin
Util.Processes.Set_Input_Stream (Stream.Proc, File);
end Set_Input_Stream;
-- -----------------------
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
-- -----------------------
procedure Set_Output_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False) is
begin
Util.Processes.Set_Output_Stream (Stream.Proc, File, Append);
end Set_Output_Stream;
-- -----------------------
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
-- -----------------------
procedure Set_Error_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False) is
begin
Util.Processes.Set_Error_Stream (Stream.Proc, File, Append);
end Set_Error_Stream;
-- -----------------------
-- Closes the given file descriptor in the child process before executing the command.
-- -----------------------
procedure Add_Close (Stream : in out Pipe_Stream;
Fd : in Util.Processes.File_Type) is
begin
Util.Processes.Add_Close (Stream.Proc, Fd);
end Add_Close;
-- -----------------------
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
-- -----------------------
procedure Set_Working_Directory (Stream : in out Pipe_Stream;
Path : in String) is
begin
Util.Processes.Set_Working_Directory (Stream.Proc, Path);
end Set_Working_Directory;
-- -----------------------
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
-- -----------------------
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ) is
begin
Util.Processes.Spawn (Stream.Proc, Command, Mode);
end Open;
-- -----------------------
-- Close the pipe and wait for the external process to terminate.
-- -----------------------
overriding
procedure Close (Stream : in out Pipe_Stream) is
begin
Util.Processes.Wait (Stream.Proc);
end Close;
-- -----------------------
-- Get the process exit status.
-- -----------------------
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer is
begin
return Util.Processes.Get_Exit_Status (Stream.Proc);
end Get_Exit_Status;
-- -----------------------
-- Returns True if the process is running.
-- -----------------------
function Is_Running (Stream : in Pipe_Stream) return Boolean is
begin
return Util.Processes.Is_Running (Stream.Proc);
end Is_Running;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Output : constant Streams.Output_Stream_Access := Processes.Get_Input_Stream (Stream.Proc);
begin
if Output = null then
raise Ada.IO_Exceptions.Status_Error with "Process is not launched";
end if;
Output.Write (Buffer);
end Write;
-- -----------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- -----------------------
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Input : constant Streams.Input_Stream_Access := Processes.Get_Output_Stream (Stream.Proc);
begin
if Input = null then
raise Ada.IO_Exceptions.Status_Error with "Process is not launched";
end if;
Input.Read (Into, Last);
end Read;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Pipe_Stream) is
begin
null;
end Finalize;
end Util.Streams.Pipes;
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 2013, 2016, 2017, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
package body Util.Streams.Pipes is
-- -----------------------
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
-- -----------------------
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String) is
begin
Util.Processes.Set_Shell (Stream.Proc, Shell);
end Set_Shell;
-- -----------------------
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
-- -----------------------
procedure Set_Input_Stream (Stream : in out Pipe_Stream;
File : in String) is
begin
Util.Processes.Set_Input_Stream (Stream.Proc, File);
end Set_Input_Stream;
-- -----------------------
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
-- -----------------------
procedure Set_Output_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False) is
begin
Util.Processes.Set_Output_Stream (Stream.Proc, File, Append);
end Set_Output_Stream;
-- -----------------------
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
-- -----------------------
procedure Set_Error_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False) is
begin
Util.Processes.Set_Error_Stream (Stream.Proc, File, Append);
end Set_Error_Stream;
-- -----------------------
-- Closes the given file descriptor in the child process before executing the command.
-- -----------------------
procedure Add_Close (Stream : in out Pipe_Stream;
Fd : in Util.Processes.File_Type) is
begin
Util.Processes.Add_Close (Stream.Proc, Fd);
end Add_Close;
-- -----------------------
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
-- -----------------------
procedure Set_Working_Directory (Stream : in out Pipe_Stream;
Path : in String) is
begin
Util.Processes.Set_Working_Directory (Stream.Proc, Path);
end Set_Working_Directory;
-- -----------------------
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
-- -----------------------
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ) is
begin
Util.Processes.Spawn (Stream.Proc, Command, Mode);
end Open;
-- -----------------------
-- Close the pipe and wait for the external process to terminate.
-- -----------------------
overriding
procedure Close (Stream : in out Pipe_Stream) is
begin
Util.Processes.Wait (Stream.Proc);
end Close;
-- -----------------------
-- Get the process exit status.
-- -----------------------
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer is
begin
return Util.Processes.Get_Exit_Status (Stream.Proc);
end Get_Exit_Status;
-- -----------------------
-- Returns True if the process is running.
-- -----------------------
function Is_Running (Stream : in Pipe_Stream) return Boolean is
begin
return Util.Processes.Is_Running (Stream.Proc);
end Is_Running;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Output : constant Streams.Output_Stream_Access := Processes.Get_Input_Stream (Stream.Proc);
begin
if Output = null then
raise Ada.IO_Exceptions.Status_Error with "Process is not launched";
end if;
Output.Write (Buffer);
end Write;
-- -----------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- -----------------------
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Input : Streams.Input_Stream_Access := Processes.Get_Output_Stream (Stream.Proc);
begin
if Input = null then
Input := Processes.Get_Error_Stream (Stream.Proc);
if Input = null then
raise Ada.IO_Exceptions.Status_Error with "Process is not launched";
end if;
end if;
Input.Read (Into, Last);
end Read;
-- -----------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- -----------------------
procedure Stop (Stream : in out Pipe_Stream;
Signal : in Positive := 15) is
begin
Util.Processes.Stop (Stream.Proc, Signal);
end Stop;
end Util.Streams.Pipes;
|
Remove the unused Finalize procedure Add the Stop procedure to send a signal Fix the Read procedure to be able to read the error stream
|
Remove the unused Finalize procedure
Add the Stop procedure to send a signal
Fix the Read procedure to be able to read the error stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ef8664c31629cb62c4a0dfcfdf457c6ed0b3d2ad
|
src/port_specification-makefile.adb
|
src/port_specification-makefile.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Text_IO;
with Ada.Characters.Latin_1;
package body Port_Specification.Makefile is
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
--------------------------------------------------------------------------------------------
-- generator
--------------------------------------------------------------------------------------------
procedure generator
(specs : Portspecs;
variant : String;
opsys : supported_opsys;
arch_standard : supported_arch;
osrelease : String;
osmajor : String;
osversion : String;
option_string : String;
output_file : String
)
is
procedure send (data : String; use_put : Boolean := False);
procedure send (varname, value : String);
procedure send (varname : String; value : HT.Text);
procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1);
procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1);
procedure send (varname : String; value : Boolean; dummy : Boolean);
procedure send (varname : String; value, default : Integer);
procedure print_item (position : string_crate.Cursor);
procedure dump_list (position : list_crate.Cursor);
procedure dump_distfiles (position : string_crate.Cursor);
procedure dump_ext_zip (position : string_crate.Cursor);
procedure dump_ext_7z (position : string_crate.Cursor);
procedure dump_ext_lha (position : string_crate.Cursor);
procedure dump_extract_head_tail (position : list_crate.Cursor);
write_to_file : constant Boolean := (output_file /= "");
makefile_handle : TIO.File_Type;
varname_prefix : HT.Text;
procedure send (data : String; use_put : Boolean := False) is
begin
if write_to_file then
if use_put then
TIO.Put (makefile_handle, data);
else
TIO.Put_Line (makefile_handle, data);
end if;
else
if use_put then
TIO.Put (data);
else
TIO.Put_Line (data);
end if;
end if;
end send;
procedure send (varname, value : String) is
begin
send (varname & LAT.Equals_Sign & value);
end send;
procedure send (varname : String; value : HT.Text) is
begin
if not HT.IsBlank (value) then
send (varname & LAT.Equals_Sign & HT.USS (value));
end if;
end send;
procedure send (varname : String; value : Boolean; dummy : Boolean) is
begin
if value then
send (varname & LAT.Equals_Sign & "yes");
end if;
end send;
procedure send (varname : String; value, default : Integer) is
begin
if value /= default then
send (varname & LAT.Equals_Sign & HT.int2str (value));
end if;
end send;
procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1) is
begin
if crate.Is_Empty then
return;
end if;
case flavor is
when 1 =>
send (varname & "=", True);
crate.Iterate (Process => print_item'Access);
send ("");
when 2 =>
varname_prefix := HT.SUS (varname);
crate.Iterate (Process => dump_distfiles'Access);
when 3 =>
crate.Iterate (Process => dump_ext_zip'Access);
when 4 =>
crate.Iterate (Process => dump_ext_7z'Access);
when 5 =>
crate.Iterate (Process => dump_ext_lha'Access);
when others =>
null;
end case;
end send;
procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1) is
begin
varname_prefix := HT.SUS (varname);
case flavor is
when 1 => crate.Iterate (Process => dump_list'Access);
when 6 => crate.Iterate (Process => dump_extract_head_tail'Access);
when others => null;
end case;
end send;
procedure dump_list (position : list_crate.Cursor)
is
NDX : String := HT.USS (varname_prefix) & "_" &
HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign;
begin
send (NDX, True);
list_crate.Element (position).list.Iterate (Process => print_item'Access);
send ("");
end dump_list;
procedure dump_extract_head_tail (position : list_crate.Cursor)
is
NDX : String := HT.USS (varname_prefix) & "_" &
HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign;
begin
if not list_crate.Element (position).list.Is_Empty then
send (NDX, True);
list_crate.Element (position).list.Iterate (Process => print_item'Access);
send ("");
end if;
end dump_extract_head_tail;
procedure print_item (position : string_crate.Cursor)
is
index : Natural := string_crate.To_Index (position);
begin
if index > 1 then
send (" ", True);
end if;
send (HT.USS (string_crate.Element (position)), True);
end print_item;
procedure dump_distfiles (position : string_crate.Cursor)
is
index : Natural := string_crate.To_Index (position);
NDX : String := HT.USS (varname_prefix) & "_" & HT.int2str (index) & LAT.Equals_Sign;
begin
send (NDX & HT.USS (string_crate.Element (position)));
end dump_distfiles;
procedure dump_ext_zip (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=/usr/bin/unzip -qo");
send ("EXTRACT_TAIL_" & N & "=-d ${EXTRACT_WRKDIR_" & N & "}");
end dump_ext_zip;
procedure dump_ext_7z (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=7z x -bd -y -o${EXTRACT_WRKDIR_" & N & "} >/dev/null");
send ("EXTRACT_TAIL_" & N & "=# empty");
end dump_ext_7z;
procedure dump_ext_lha (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=lha xfpw=${EXTRACT_WRKDIR_" & N & "}");
send ("EXTRACT_TAIL_" & N & "=# empty");
end dump_ext_lha;
begin
if not specs.variant_exists (variant) then
TIO.Put_Line ("Error : Variant '" & variant & "' does not exist!");
return;
end if;
if write_to_file then
TIO.Create (File => makefile_handle,
Mode => TIO.Out_File,
Name => output_file);
end if;
-- TODO: Check these to see if they are actually used.
-- The pkg manifests did use many of these, but they will be generated by ravenadm
send ("# Makefile has been autogenerated by ravenadm tool" & LAT.LF);
send ("NAMEBASE", HT.USS (specs.namebase));
send ("VERSION", HT.USS (specs.version));
send ("REVISION", specs.revision, 0);
send ("EPOCH", specs.epoch, 0);
send ("KEYWORDS", specs.keywords); -- probably remove
send ("VARIANT", variant);
send ("DL_SITES", specs.dl_sites);
send ("DISTFILE", specs.distfiles, 2);
send ("DIST_SUBDIR", specs.dist_subdir);
send ("DISTNAME", specs.distname);
send ("DF_INDEX", specs.df_index);
send ("EXTRACT_ONLY", specs.extract_only);
send ("ZIP-EXTRACT", specs.extract_zip, 3);
send ("7Z-EXTRACT", specs.extract_7z, 4);
send ("LHA-EXTRACT", specs.extract_lha, 5);
send ("EXTRACT_HEAD", specs.extract_head, 6);
send ("EXTRACT_TAIL", specs.extract_tail, 6);
send ("NO_BUILD", specs.skip_build, True);
send ("SINGLE_JOB", specs.single_job, True);
send ("DESTDIR_VIA_ENV", specs.destdir_env, True);
send ("BUILD_WRKSRC", specs.build_wrksrc);
send ("MAKEFILE", specs.makefile);
send ("MAKE_ENV", specs.make_env);
send ("MAKE_ARGS", specs.make_args);
send ("CFLAGS", specs.cflags);
-- TODO: This is not correct, placeholder. rethink.
send (".include " & LAT.Quotation & "/usr/raven/share/mk/raven.mk" & LAT.Quotation);
if write_to_file then
TIO.Close (makefile_handle);
end if;
exception
when others =>
if TIO.Is_Open (makefile_handle) then
TIO.Close (makefile_handle);
end if;
end generator;
end Port_Specification.Makefile;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Text_IO;
with Ada.Characters.Latin_1;
package body Port_Specification.Makefile is
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
--------------------------------------------------------------------------------------------
-- generator
--------------------------------------------------------------------------------------------
procedure generator
(specs : Portspecs;
variant : String;
opsys : supported_opsys;
arch_standard : supported_arch;
osrelease : String;
osmajor : String;
osversion : String;
option_string : String;
output_file : String
)
is
procedure send (data : String; use_put : Boolean := False);
procedure send (varname, value : String);
procedure send (varname : String; value : HT.Text);
procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1);
procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1);
procedure send (varname : String; value : Boolean; dummy : Boolean);
procedure send (varname : String; value, default : Integer);
procedure print_item (position : string_crate.Cursor);
procedure dump_list (position : list_crate.Cursor);
procedure dump_distfiles (position : string_crate.Cursor);
procedure dump_ext_zip (position : string_crate.Cursor);
procedure dump_ext_7z (position : string_crate.Cursor);
procedure dump_ext_lha (position : string_crate.Cursor);
procedure dump_extract_head_tail (position : list_crate.Cursor);
procedure dump_dirty_extract (position : string_crate.Cursor);
write_to_file : constant Boolean := (output_file /= "");
makefile_handle : TIO.File_Type;
varname_prefix : HT.Text;
procedure send (data : String; use_put : Boolean := False) is
begin
if write_to_file then
if use_put then
TIO.Put (makefile_handle, data);
else
TIO.Put_Line (makefile_handle, data);
end if;
else
if use_put then
TIO.Put (data);
else
TIO.Put_Line (data);
end if;
end if;
end send;
procedure send (varname, value : String) is
begin
send (varname & LAT.Equals_Sign & value);
end send;
procedure send (varname : String; value : HT.Text) is
begin
if not HT.IsBlank (value) then
send (varname & LAT.Equals_Sign & HT.USS (value));
end if;
end send;
procedure send (varname : String; value : Boolean; dummy : Boolean) is
begin
if value then
send (varname & LAT.Equals_Sign & "yes");
end if;
end send;
procedure send (varname : String; value, default : Integer) is
begin
if value /= default then
send (varname & LAT.Equals_Sign & HT.int2str (value));
end if;
end send;
procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1) is
begin
if crate.Is_Empty then
return;
end if;
case flavor is
when 1 =>
send (varname & "=", True);
crate.Iterate (Process => print_item'Access);
send ("");
when 2 =>
varname_prefix := HT.SUS (varname);
crate.Iterate (Process => dump_distfiles'Access);
when 3 =>
crate.Iterate (Process => dump_ext_zip'Access);
when 4 =>
crate.Iterate (Process => dump_ext_7z'Access);
when 5 =>
crate.Iterate (Process => dump_ext_lha'Access);
when 7 =>
crate.Iterate (Process => dump_dirty_extract'Access);
when others =>
null;
end case;
end send;
procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1) is
begin
varname_prefix := HT.SUS (varname);
case flavor is
when 1 => crate.Iterate (Process => dump_list'Access);
when 6 => crate.Iterate (Process => dump_extract_head_tail'Access);
when others => null;
end case;
end send;
procedure dump_list (position : list_crate.Cursor)
is
NDX : String := HT.USS (varname_prefix) & "_" &
HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign;
begin
send (NDX, True);
list_crate.Element (position).list.Iterate (Process => print_item'Access);
send ("");
end dump_list;
procedure dump_extract_head_tail (position : list_crate.Cursor)
is
NDX : String := HT.USS (varname_prefix) & "_" &
HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign;
begin
if not list_crate.Element (position).list.Is_Empty then
send (NDX, True);
list_crate.Element (position).list.Iterate (Process => print_item'Access);
send ("");
end if;
end dump_extract_head_tail;
procedure print_item (position : string_crate.Cursor)
is
index : Natural := string_crate.To_Index (position);
begin
if index > 1 then
send (" ", True);
end if;
send (HT.USS (string_crate.Element (position)), True);
end print_item;
procedure dump_distfiles (position : string_crate.Cursor)
is
index : Natural := string_crate.To_Index (position);
NDX : String := HT.USS (varname_prefix) & "_" & HT.int2str (index) & LAT.Equals_Sign;
begin
send (NDX & HT.USS (string_crate.Element (position)));
end dump_distfiles;
procedure dump_ext_zip (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=/usr/bin/unzip -qo");
send ("EXTRACT_TAIL_" & N & "=-d ${EXTRACT_WRKDIR_" & N & "}");
end dump_ext_zip;
procedure dump_ext_7z (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=7z x -bd -y -o${EXTRACT_WRKDIR_" & N & "} >/dev/null");
send ("EXTRACT_TAIL_" & N & "=# empty");
end dump_ext_7z;
procedure dump_ext_lha (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=lha xfpw=${EXTRACT_WRKDIR_" & N & "}");
send ("EXTRACT_TAIL_" & N & "=# empty");
end dump_ext_lha;
procedure dump_dirty_extract (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("DIRTY_EXTRACT_" & N & "=yes");
end dump_dirty_extract;
begin
if not specs.variant_exists (variant) then
TIO.Put_Line ("Error : Variant '" & variant & "' does not exist!");
return;
end if;
if write_to_file then
TIO.Create (File => makefile_handle,
Mode => TIO.Out_File,
Name => output_file);
end if;
-- TODO: Check these to see if they are actually used.
-- The pkg manifests did use many of these, but they will be generated by ravenadm
send ("# Makefile has been autogenerated by ravenadm tool" & LAT.LF);
send ("NAMEBASE", HT.USS (specs.namebase));
send ("VERSION", HT.USS (specs.version));
send ("REVISION", specs.revision, 0);
send ("EPOCH", specs.epoch, 0);
send ("KEYWORDS", specs.keywords); -- probably remove
send ("VARIANT", variant);
send ("DL_SITES", specs.dl_sites);
send ("DISTFILE", specs.distfiles, 2);
send ("DIST_SUBDIR", specs.dist_subdir);
send ("DISTNAME", specs.distname);
send ("DF_INDEX", specs.df_index);
send ("EXTRACT_ONLY", specs.extract_only);
send ("DIRTY_EXTRACT", specs.extract_dirty, 7);
send ("ZIP-EXTRACT", specs.extract_zip, 3);
send ("7Z-EXTRACT", specs.extract_7z, 4);
send ("LHA-EXTRACT", specs.extract_lha, 5);
send ("EXTRACT_HEAD", specs.extract_head, 6);
send ("EXTRACT_TAIL", specs.extract_tail, 6);
send ("NO_BUILD", specs.skip_build, True);
send ("BUILD_WRKSRC", specs.build_wrksrc);
send ("BUILD_TARGET", specs.build_target);
send ("MAKEFILE", specs.makefile);
send ("MAKE_ENV", specs.make_env);
send ("MAKE_ARGS", specs.make_args);
send ("CFLAGS", specs.cflags);
send ("CXXFLAGS", specs.cxxflags);
send ("CPPFLAGS", specs.cppflags);
send ("LDFLAGS", specs.ldflags);
send ("SINGLE_JOB", specs.single_job, True);
send ("DESTDIR_VIA_ENV", specs.destdir_env, True);
send ("DESTDIRNAME", specs.destdirname);
-- TODO: This is not correct, placeholder. rethink.
send (".include " & LAT.Quotation & "/usr/raven/share/mk/raven.mk" & LAT.Quotation);
if write_to_file then
TIO.Close (makefile_handle);
end if;
exception
when others =>
if TIO.Is_Open (makefile_handle) then
TIO.Close (makefile_handle);
end if;
end generator;
end Port_Specification.Makefile;
|
Support DIRTY_EXTRACT and a couple of others
|
Support DIRTY_EXTRACT and a couple of others
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
e0f5a6c070f024f3156dc7cac18372707058d072
|
tools/smaz.adb
|
tools/smaz.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. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Command Line Interface for primitives in Natools.Smaz.Tools. --
------------------------------------------------------------------------------
with Ada.Command_Line;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Ada.Text_IO.Text_Streams;
with Natools.Getopt_Long;
with Natools.S_Expressions.Parsers;
with Natools.S_Expressions.Printers;
with Natools.Smaz.Tools;
with Natools.Smaz.Tools.GNAT;
procedure Smaz is
package Actions is
type Enum is
(Nothing,
Encode);
end Actions;
package Options is
type Id is
(Output_Ada_Dictionary,
Encode,
Output_Hash,
Help);
end Options;
package Getopt is new Natools.Getopt_Long (Options.Id);
type Callback is new Getopt.Handlers.Callback with record
Display_Help : Boolean := False;
Need_Dictionary : Boolean := False;
Action : Actions.Enum := Actions.Nothing;
Ada_Dictionary : Ada.Strings.Unbounded.Unbounded_String;
Hash_Package : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding procedure Option
(Handler : in out Callback;
Id : in Options.Id;
Argument : in String);
overriding procedure Argument
(Handler : in out Callback;
Argument : in String)
is null;
function Getopt_Config return Getopt.Configuration;
-- Build the configuration object
procedure Print_Dictionary
(Filename : in String;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "");
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "");
-- print the given dictionary in the given file
procedure Print_Help
(Opt : in Getopt.Configuration;
Output : in Ada.Text_IO.File_Type);
-- Print the help text to the given file
overriding procedure Option
(Handler : in out Callback;
Id : in Options.Id;
Argument : in String) is
begin
case Id is
when Options.Help =>
Handler.Display_Help := True;
when Options.Encode =>
Handler.Need_Dictionary := True;
Handler.Action := Actions.Encode;
when Options.Output_Ada_Dictionary =>
Handler.Need_Dictionary := True;
if Argument'Length > 0 then
Handler.Ada_Dictionary
:= Ada.Strings.Unbounded.To_Unbounded_String (Argument);
else
Handler.Ada_Dictionary
:= Ada.Strings.Unbounded.To_Unbounded_String ("-");
end if;
when Options.Output_Hash =>
Handler.Need_Dictionary := True;
Handler.Hash_Package
:= Ada.Strings.Unbounded.To_Unbounded_String (Argument);
end case;
end Option;
function Getopt_Config return Getopt.Configuration is
use Getopt;
use Options;
R : Getopt.Configuration;
begin
R.Add_Option ("ada-dict", 'A', Optional_Argument, Output_Ada_Dictionary);
R.Add_Option ("encode", 'e', No_Argument, Encode);
R.Add_Option ("hash-pkg", 'H', Required_Argument, Output_Hash);
R.Add_Option ("help", 'h', No_Argument, Help);
return R;
end Getopt_Config;
procedure Print_Dictionary
(Filename : in String;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "") is
begin
if Filename = "-" then
Print_Dictionary
(Ada.Text_IO.Current_Output, Dictionary, Hash_Package_Name);
elsif Filename'Length > 0 then
declare
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File, Name => Filename);
Print_Dictionary (File, Dictionary, Hash_Package_Name);
Ada.Text_IO.Close (File);
end;
end if;
end Print_Dictionary;
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "")
is
procedure Put_Line (Line : in String);
procedure Put_Line (Line : in String) is
begin
Ada.Text_IO.Put_Line (Output, Line);
end Put_Line;
procedure Print_Dictionary_In_Ada is
new Natools.Smaz.Tools.Print_Dictionary_In_Ada (Put_Line);
begin
if Hash_Package_Name'Length > 0 then
Print_Dictionary_In_Ada
(Dictionary,
Hash_Image => Hash_Package_Name & ".Hash'Access");
else
Print_Dictionary_In_Ada (Dictionary);
end if;
end Print_Dictionary;
procedure Print_Help
(Opt : in Getopt.Configuration;
Output : in Ada.Text_IO.File_Type)
is
use Ada.Text_IO;
Indent : constant String := " ";
begin
Put_Line (Output, "Usage:");
for Id in Options.Id loop
Put (Output, Indent & Opt.Format_Names (Id));
case Id is
when Options.Help =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Display this help text");
when Options.Encode =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Read a list of strings and encode them");
when Options.Output_Ada_Dictionary =>
Put_Line (Output, "=[filename]");
Put_Line (Output, Indent & Indent
& "Output the current dictionary as Ada code in the given");
Put_Line (Output, Indent & Indent
& "file, or standard output if filename is ""-""");
when Options.Output_Hash =>
Put_Line (Output, " <Hash Package Name>");
Put_Line (Output, Indent & Indent
& "Build a package with a perfect hash function for the");
Put_Line (Output, Indent & Indent
& "current dictionary.");
end case;
end loop;
end Print_Help;
Opt_Config : constant Getopt.Configuration := Getopt_Config;
Handler : Callback;
Input_List, Input_Data : Natools.Smaz.Tools.String_Lists.List;
begin
Process_Command_Line :
begin
Opt_Config.Process (Handler);
exception
when Getopt.Option_Error =>
Print_Help (Opt_Config, Ada.Text_IO.Current_Error);
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end Process_Command_Line;
if Handler.Display_Help then
Print_Help (Opt_Config, Ada.Text_IO.Current_Output);
end if;
if not Handler.Need_Dictionary then
return;
end if;
Read_Input_List :
declare
use type Actions.Enum;
Input : constant access Ada.Streams.Root_Stream_Type'Class
:= Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Input);
Parser : Natools.S_Expressions.Parsers.Stream_Parser (Input);
begin
Parser.Next;
Natools.Smaz.Tools.Read_List (Input_List, Parser);
if Handler.Action /= Actions.Nothing then
Parser.Next;
Natools.Smaz.Tools.Read_List (Input_Data, Parser);
end if;
end Read_Input_List;
Build_Dictionary :
declare
Dictionary : Natools.Smaz.Dictionary
:= Natools.Smaz.Tools.To_Dictionary (Input_List, True);
Output : Natools.S_Expressions.Printers.Canonical
(Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Output));
Ada_Dictionary : constant String
:= Ada.Strings.Unbounded.To_String (Handler.Ada_Dictionary);
Hash_Package : constant String
:= Ada.Strings.Unbounded.To_String (Handler.Hash_Package);
begin
Dictionary.Hash := Natools.Smaz.Tools.Linear_Search'Access;
Natools.Smaz.Tools.List_For_Linear_Search := Input_List;
if Ada_Dictionary'Length > 0 then
Print_Dictionary (Ada_Dictionary, Dictionary, Hash_Package);
end if;
if Hash_Package'Length > 0 then
Natools.Smaz.Tools.GNAT.Build_Perfect_Hash (Input_List, Hash_Package);
end if;
case Handler.Action is
when Actions.Nothing => null;
when Actions.Encode =>
Output.Open_List;
for S of Input_Data loop
Output.Append_Atom (Natools.Smaz.Compress (Dictionary, S));
end loop;
Output.Close_List;
end case;
end Build_Dictionary;
end Smaz;
|
------------------------------------------------------------------------------
-- 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. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Command Line Interface for primitives in Natools.Smaz.Tools. --
------------------------------------------------------------------------------
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Ada.Text_IO.Text_Streams;
with Natools.Getopt_Long;
with Natools.S_Expressions.Parsers;
with Natools.S_Expressions.Printers;
with Natools.Smaz.Tools;
with Natools.Smaz.Tools.GNAT;
procedure Smaz is
package Actions is
type Enum is
(Nothing,
Encode);
end Actions;
package Options is
type Id is
(Output_Ada_Dictionary,
Encode,
Output_Hash,
Help,
Stat_Output,
No_Stat_Output,
Sx_Output,
No_Sx_Output);
end Options;
package Getopt is new Natools.Getopt_Long (Options.Id);
type Callback is new Getopt.Handlers.Callback with record
Display_Help : Boolean := False;
Need_Dictionary : Boolean := False;
Stat_Output : Boolean := False;
Sx_Output : Boolean := False;
Action : Actions.Enum := Actions.Nothing;
Ada_Dictionary : Ada.Strings.Unbounded.Unbounded_String;
Hash_Package : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding procedure Option
(Handler : in out Callback;
Id : in Options.Id;
Argument : in String);
overriding procedure Argument
(Handler : in out Callback;
Argument : in String)
is null;
function Getopt_Config return Getopt.Configuration;
-- Build the configuration object
procedure Print_Dictionary
(Filename : in String;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "");
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "");
-- print the given dictionary in the given file
procedure Print_Help
(Opt : in Getopt.Configuration;
Output : in Ada.Text_IO.File_Type);
-- Print the help text to the given file
overriding procedure Option
(Handler : in out Callback;
Id : in Options.Id;
Argument : in String) is
begin
case Id is
when Options.Help =>
Handler.Display_Help := True;
when Options.Encode =>
Handler.Need_Dictionary := True;
Handler.Action := Actions.Encode;
when Options.No_Stat_Output =>
Handler.Stat_Output := False;
when Options.No_Sx_Output =>
Handler.Sx_Output := False;
when Options.Output_Ada_Dictionary =>
Handler.Need_Dictionary := True;
if Argument'Length > 0 then
Handler.Ada_Dictionary
:= Ada.Strings.Unbounded.To_Unbounded_String (Argument);
else
Handler.Ada_Dictionary
:= Ada.Strings.Unbounded.To_Unbounded_String ("-");
end if;
when Options.Output_Hash =>
Handler.Need_Dictionary := True;
Handler.Hash_Package
:= Ada.Strings.Unbounded.To_Unbounded_String (Argument);
when Options.Stat_Output =>
Handler.Stat_Output := True;
when Options.Sx_Output =>
Handler.Sx_Output := True;
end case;
end Option;
function Getopt_Config return Getopt.Configuration is
use Getopt;
use Options;
R : Getopt.Configuration;
begin
R.Add_Option ("ada-dict", 'A', Optional_Argument, Output_Ada_Dictionary);
R.Add_Option ("encode", 'e', No_Argument, Encode);
R.Add_Option ("help", 'h', No_Argument, Help);
R.Add_Option ("hash-pkg", 'H', Required_Argument, Output_Hash);
R.Add_Option ("stats", 's', No_Argument, Stat_Output);
R.Add_Option ("no-stats", 'S', No_Argument, No_Stat_Output);
R.Add_Option ("s-expr", 'x', No_Argument, Sx_Output);
R.Add_Option ("no-s-expr", 'X', No_Argument, No_Sx_Output);
return R;
end Getopt_Config;
procedure Print_Dictionary
(Filename : in String;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "") is
begin
if Filename = "-" then
Print_Dictionary
(Ada.Text_IO.Current_Output, Dictionary, Hash_Package_Name);
elsif Filename'Length > 0 then
declare
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File, Name => Filename);
Print_Dictionary (File, Dictionary, Hash_Package_Name);
Ada.Text_IO.Close (File);
end;
end if;
end Print_Dictionary;
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "")
is
procedure Put_Line (Line : in String);
procedure Put_Line (Line : in String) is
begin
Ada.Text_IO.Put_Line (Output, Line);
end Put_Line;
procedure Print_Dictionary_In_Ada is
new Natools.Smaz.Tools.Print_Dictionary_In_Ada (Put_Line);
begin
if Hash_Package_Name'Length > 0 then
Print_Dictionary_In_Ada
(Dictionary,
Hash_Image => Hash_Package_Name & ".Hash'Access");
else
Print_Dictionary_In_Ada (Dictionary);
end if;
end Print_Dictionary;
procedure Print_Help
(Opt : in Getopt.Configuration;
Output : in Ada.Text_IO.File_Type)
is
use Ada.Text_IO;
Indent : constant String := " ";
begin
Put_Line (Output, "Usage:");
for Id in Options.Id loop
Put (Output, Indent & Opt.Format_Names (Id));
case Id is
when Options.Help =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Display this help text");
when Options.Encode =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Read a list of strings and encode them");
when Options.No_Stat_Output =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Do not output filter statistics");
when Options.No_Sx_Output =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Do not output filtered results in a S-expression");
when Options.Output_Ada_Dictionary =>
Put_Line (Output, "=[filename]");
Put_Line (Output, Indent & Indent
& "Output the current dictionary as Ada code in the given");
Put_Line (Output, Indent & Indent
& "file, or standard output if filename is ""-""");
when Options.Output_Hash =>
Put_Line (Output, " <Hash Package Name>");
Put_Line (Output, Indent & Indent
& "Build a package with a perfect hash function for the");
Put_Line (Output, Indent & Indent
& "current dictionary.");
when Options.Stat_Output =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Output filter statistics");
when Options.Sx_Output =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Output filtered results in a S-expression");
end case;
end loop;
end Print_Help;
Opt_Config : constant Getopt.Configuration := Getopt_Config;
Handler : Callback;
Input_List, Input_Data : Natools.Smaz.Tools.String_Lists.List;
begin
Process_Command_Line :
begin
Opt_Config.Process (Handler);
exception
when Getopt.Option_Error =>
Print_Help (Opt_Config, Ada.Text_IO.Current_Error);
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end Process_Command_Line;
if Handler.Display_Help then
Print_Help (Opt_Config, Ada.Text_IO.Current_Output);
end if;
if not Handler.Need_Dictionary then
return;
end if;
if not (Handler.Stat_Output or Handler.Sx_Output) then
Handler.Sx_Output := True;
end if;
Read_Input_List :
declare
use type Actions.Enum;
Input : constant access Ada.Streams.Root_Stream_Type'Class
:= Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Input);
Parser : Natools.S_Expressions.Parsers.Stream_Parser (Input);
begin
Parser.Next;
Natools.Smaz.Tools.Read_List (Input_List, Parser);
if Handler.Action /= Actions.Nothing then
Parser.Next;
Natools.Smaz.Tools.Read_List (Input_Data, Parser);
end if;
end Read_Input_List;
Build_Dictionary :
declare
Dictionary : Natools.Smaz.Dictionary
:= Natools.Smaz.Tools.To_Dictionary (Input_List, True);
Sx_Output : Natools.S_Expressions.Printers.Canonical
(Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Output));
Ada_Dictionary : constant String
:= Ada.Strings.Unbounded.To_String (Handler.Ada_Dictionary);
Hash_Package : constant String
:= Ada.Strings.Unbounded.To_String (Handler.Hash_Package);
begin
Dictionary.Hash := Natools.Smaz.Tools.Linear_Search'Access;
Natools.Smaz.Tools.List_For_Linear_Search := Input_List;
if Ada_Dictionary'Length > 0 then
Print_Dictionary (Ada_Dictionary, Dictionary, Hash_Package);
end if;
if Hash_Package'Length > 0 then
Natools.Smaz.Tools.GNAT.Build_Perfect_Hash (Input_List, Hash_Package);
end if;
case Handler.Action is
when Actions.Nothing => null;
when Actions.Encode =>
if Handler.Sx_Output then
Sx_Output.Open_List;
for S of Input_Data loop
Sx_Output.Append_Atom
(Natools.Smaz.Compress (Dictionary, S));
end loop;
Sx_Output.Close_List;
end if;
if Handler.Stat_Output then
declare
procedure Print_Line (Original, Output, Base64 : Natural);
procedure Print_Line (Original, Output, Base64 : Natural) is
begin
Ada.Text_IO.Put_Line
(Natural'Image (Original)
& Ada.Characters.Latin_1.HT
& Natural'Image (Output)
& Ada.Characters.Latin_1.HT
& Natural'Image (Base64)
& Ada.Characters.Latin_1.HT
& Float'Image (Float (Output) / Float (Original))
& Ada.Characters.Latin_1.HT
& Float'Image (Float (Base64) / Float (Original)));
end Print_Line;
Original_Total : Natural := 0;
Output_Total : Natural := 0;
Base64_Total : Natural := 0;
begin
for S of Input_Data loop
declare
Original_Size : constant Natural := S'Length;
Output_Size : constant Natural
:= Natools.Smaz.Compress (Dictionary, S)'Length;
Base64_Size : constant Natural
:= ((Output_Size + 2) / 3) * 4;
begin
Print_Line (Original_Size, Output_Size, Base64_Size);
Original_Total := Original_Total + Original_Size;
Output_Total := Output_Total + Output_Size;
Base64_Total := Base64_Total + Base64_Size;
end;
end loop;
Print_Line (Original_Total, Output_Total, Base64_Total);
end;
end if;
end case;
end Build_Dictionary;
end Smaz;
|
add the output of statistics about compression
|
tools/smaz: add the output of statistics about compression
|
Ada
|
isc
|
faelys/natools
|
5c9a8a494ea38fd72e71aaddd3016a246d043c6f
|
regtests/util-log-tests.adb
|
regtests/util-log-tests.adb
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.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");
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, "1000 Log.Info message (output)");
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, "10000 Log.Debug message (no output)");
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");
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;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test 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.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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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");
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, "1000 Log.Info message (output)");
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, "10000 Log.Debug message (no output)");
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;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test 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.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;
|
Update test after removal of a debug log message in Util.Log.Loggers.Finalize
|
Update test after removal of a debug log message in Util.Log.Loggers.Finalize
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
013b62989faa67b13de93b1b211cb55cfb48c95e
|
awa/plugins/awa-comments/src/awa-comments-beans.adb
|
awa/plugins/awa-comments/src/awa-comments-beans.adb
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions.Entities;
with ADO.Queries;
with ADO.Statements;
package body AWA.Comments.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 Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) with which the comments are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a comment on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
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.Comments.Models.Query_Comment_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_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions.Entities;
with ADO.Queries;
with ADO.Statements;
with ADO.Utils;
with AWA.Services.Contexts;
package body AWA.Comments.Beans is
package ASC renames AWA.Services.Contexts;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "comment" then
From.Set_Message (Util.Beans.Objects.To_String (Value));
elsif Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "status" then
From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Module.Load_Comment (From, Id);
end;
end if;
end Set_Value;
-- Create the comment.
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Create_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean);
end Create;
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Save;
-- Delete the comment.
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create a new comment bean instance.
-- ------------------------------
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_Bean_Access := new Comment_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) with which the comments are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a comment on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
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.Comments.Models.Query_Comment_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_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
Implement the Comment_Bean with the create operation
|
Implement the Comment_Bean with the create operation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0194c8d752c259d5923edfed47d6bbc98780fd14
|
mat/src/mat-readers.adb
|
mat/src/mat-readers.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Events;
with MAT.Types;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Message_Handler;
begin
Handler.For_Servant := Reader;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg);
end;
end if;
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
procedure Read_Attributes (Key : in String;
Element : in out Message_Handler) is
begin
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
begin
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
end if;
end loop;
end;
end loop;
end Read_Attributes;
begin
Log.Debug ("Read event definition {0}", Name);
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attributes'Access);
end if;
end Read_Definition;
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Client.Flags := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
end Read_Headers;
end MAT.Readers;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Events;
with MAT.Types;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Message_Handler;
begin
Handler.For_Servant := Reader;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg);
end;
end if;
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
procedure Read_Attributes (Key : in String;
Element : in out Message_Handler) is
begin
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
begin
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
end if;
end loop;
end;
end loop;
end Read_Attributes;
begin
Log.Debug ("Read event definition {0}", Name);
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attributes'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
-- ------------------------------
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
end Read_Headers;
end MAT.Readers;
|
Add documentation on Read_Headers
|
Add documentation on Read_Headers
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
70f83b541d39c54eb6f3c05d5cb1ee0a8a02f578
|
awa/regtests/awa-blogs-modules-tests.adb
|
awa/regtests/awa-blogs-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs 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 Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Blogs.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Blogs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post",
Test_Create_Post'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a blog
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
end Test_Create_Blog;
-- ------------------------------
-- Test creating and updating of a blog post
-- ------------------------------
procedure Test_Create_Post (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Post_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog post",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
for I in 1 .. 5 loop
Manager.Create_Post (Blog_Id => Blog_Id,
Title => "Testing blog title",
URI => "testing-blog-title",
Text => "The blog content",
Status => AWA.Blogs.Models.POST_DRAFT,
Result => Post_Id);
T.Assert (Post_Id > 0, "Invalid post identifier");
Manager.Update_Post (Post_Id => Post_Id,
Title => "New blog post title",
URI => "testing-blog-title",
Text => "The new post content",
Status => AWA.Blogs.Models.POST_DRAFT);
-- Keep the last post in the database.
exit when I = 5;
Manager.Delete_Post (Post_Id => Post_Id);
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Update_Post (Post_Id => Post_Id,
Title => "Something",
Text => "Content",
URI => "testing-blog-title",
Status => AWA.Blogs.Models.POST_DRAFT);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Delete_Post (Post_Id => Post_Id);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
end loop;
end Test_Create_Post;
end AWA.Blogs.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs 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 Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Blogs.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Blogs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post",
Test_Create_Post'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a blog
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
end Test_Create_Blog;
-- ------------------------------
-- Test creating and updating of a blog post
-- ------------------------------
procedure Test_Create_Post (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Post_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog post",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
for I in 1 .. 5 loop
Manager.Create_Post (Blog_Id => Blog_Id,
Title => "Testing blog title",
URI => "testing-blog-title",
Text => "The blog content",
Comment => False,
Status => AWA.Blogs.Models.POST_DRAFT,
Result => Post_Id);
T.Assert (Post_Id > 0, "Invalid post identifier");
Manager.Update_Post (Post_Id => Post_Id,
Title => "New blog post title",
URI => "testing-blog-title",
Text => "The new post content",
Comment => True,
Status => AWA.Blogs.Models.POST_DRAFT);
-- Keep the last post in the database.
exit when I = 5;
Manager.Delete_Post (Post_Id => Post_Id);
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Update_Post (Post_Id => Post_Id,
Title => "Something",
Text => "Content",
URI => "testing-blog-title",
Comment => True,
Status => AWA.Blogs.Models.POST_DRAFT);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Delete_Post (Post_Id => Post_Id);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
end loop;
end Test_Create_Post;
end AWA.Blogs.Modules.Tests;
|
Update the unit tests
|
Update the unit tests
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
1dac57a562a866506a06c4f0b3a9af8b77e95a28
|
src/util-measures.adb
|
src/util-measures.adb
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
use Util.Streams.Buffered;
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Time : constant String := Format (Item.Time);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Unchecked_Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : String; D : Duration) is
use Ada.Containers;
use Ada.Calendar;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title then
Node.Count := Node.Count + 1;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => 1,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) & "ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) & "us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) & "ms";
else
return Duration'Image (D) & "s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
use Util.Streams.Buffered;
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Time : constant String := Format (Item.Time);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Unchecked_Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title, Count);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D, Count);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : in String;
D : in Duration;
Count : in Positive := 1) is
use Ada.Containers;
use Ada.Calendar;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title then
Node.Count := Node.Count + Count;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => Count,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) & "ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) & "us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) & "ms";
else
return Duration'Image (D) & "s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
Use the Count parameter from the Report to keep track of the number of times the measure is made
|
Use the Count parameter from the Report to keep track of the number of times the measure is made
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
4ecbd791629099cd0ede3d741c87628c5a391f82
|
regtests/util-encoders-tests.ads
|
regtests/util-encoders-tests.ads
|
-----------------------------------------------------------------------
-- util-encodes-tests - Test for encoding
-- Copyright (C) 2009, 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.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Encoders.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Hex (T : in out Test);
procedure Test_Base64_Encode (T : in out Test);
procedure Test_Base64_Decode (T : in out Test);
procedure Test_Base64_URL_Encode (T : in out Test);
procedure Test_Base64_URL_Decode (T : in out Test);
procedure Test_Encoder (T : in out Test;
C : in out Util.Encoders.Encoder);
procedure Test_Base64_Benchmark (T : in out Test);
procedure Test_SHA1_Encode (T : in out Test);
procedure Test_SHA256_Encode (T : in out Test);
-- Benchmark test for SHA1
procedure Test_SHA1_Benchmark (T : in out Test);
-- Test HMAC-SHA1
procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test);
-- Test HMAC-SHA256
procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test);
-- Test encoding leb128.
procedure Test_LEB128 (T : in out Test);
-- Test encoding leb128 + base64url.
procedure Test_Base64_LEB128 (T : in out Test);
-- Test encrypt and decrypt operations.
procedure Test_AES (T : in out Test);
end Util.Encoders.Tests;
|
-----------------------------------------------------------------------
-- util-encodes-tests - Test for encoding
-- Copyright (C) 2009, 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.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Encoders.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Hex (T : in out Test);
procedure Test_Base64_Encode (T : in out Test);
procedure Test_Base64_Decode (T : in out Test);
procedure Test_Base64_URL_Encode (T : in out Test);
procedure Test_Base64_URL_Decode (T : in out Test);
procedure Test_Encoder (T : in out Test;
C : in Util.Encoders.Encoder;
D : in Util.Encoders.Decoder);
procedure Test_Base64_Benchmark (T : in out Test);
procedure Test_SHA1_Encode (T : in out Test);
procedure Test_SHA256_Encode (T : in out Test);
-- Benchmark test for SHA1
procedure Test_SHA1_Benchmark (T : in out Test);
-- Test HMAC-SHA1
procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test);
-- Test HMAC-SHA256
procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test);
procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test);
-- Test encoding leb128.
procedure Test_LEB128 (T : in out Test);
-- Test encoding leb128 + base64url.
procedure Test_Base64_LEB128 (T : in out Test);
-- Test encrypt and decrypt operations.
procedure Test_AES (T : in out Test);
end Util.Encoders.Tests;
|
Add a decoder object to Test_Encoder operation
|
Add a decoder object to Test_Encoder operation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
08f57341236f95305127101df7d84c2fbbbb2304
|
regtests/ado-objects-tests.adb
|
regtests/ado-objects-tests.adb
|
-----------------------------------------------------------------------
-- ADO Objects Tests -- Tests for ADO.Objects
-- 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 ADO.Sessions;
with Regtests.Simple.Model;
with Regtests.Comments;
with Regtests.Statements.Model;
package body ADO.Objects.Tests is
use Util.Tests;
use type Ada.Containers.Hash_Type;
-- Test the Set_xxx and Get_xxx operation on various simple times.
generic
Name : String;
type Element_Type (<>) is private;
with function "=" (Left, Right : in Element_Type) return Boolean is <>;
with procedure Set_Value (Item : in out Regtests.Statements.Model.Nullable_Table_Ref;
Val : in Element_Type);
with function Get_Value (Item : in Regtests.Statements.Model.Nullable_Table_Ref)
return Element_Type;
Val1 : Element_Type;
Val2 : Element_Type;
procedure Test_Op (T : in out Test);
procedure Test_Op (T : in out Test) is
Item1 : Regtests.Statements.Model.Nullable_Table_Ref;
Item2 : Regtests.Statements.Model.Nullable_Table_Ref;
Item3 : Regtests.Statements.Model.Nullable_Table_Ref;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
Set_Value (Item1, Val1);
Item1.Save (DB);
T.Assert (Item1.Is_Inserted, Name & " item is created");
-- Util.Tests.Assert_Equals (T, T'Image (Val), T'Image (
-- Load in a second item and check the value.
Item2.Load (DB, Item1.Get_Id);
T.Assert (Item2.Get_Id = Item1.Get_Id, Name & " item2 cannot be loaded");
-- T.Assert (Get_Value (Item2) = Val1, Name & " invalid value loaded in item2");
-- Change the item in database.
Set_Value (Item2, Val2);
Item2.Save (DB);
T.Assert (Get_Value (Item2) = Val2, Name & " invalid value loaded in item2");
-- Load again and compare to check the update.
Item3.Load (DB, Item2.Get_Id);
T.Assert (Get_Value (Item3) = Val2, Name & " invalid value loaded in item3");
end Test_Op;
procedure Test_Object_Nullable_Integer is
new Test_Op ("Nullable_Integer",
Nullable_Integer, "=",
Regtests.Statements.Model.Set_Int_Value,
Regtests.Statements.Model.Get_Int_Value,
Nullable_Integer '(Value => 123, Is_Null => False),
Nullable_Integer '(Value => 0, Is_Null => True));
procedure Test_Object_Nullable_Entity_Type is
new Test_Op ("Nullable_Entity_Type",
Nullable_Entity_Type, "=",
Regtests.Statements.Model.Set_Entity_Value,
Regtests.Statements.Model.Get_Entity_Value,
Nullable_Entity_Type '(Value => 456, Is_Null => False),
Nullable_Entity_Type '(Value => 0, Is_Null => True));
procedure Test_Object_Nullable_Time is
new Test_Op ("Nullable_Time",
Nullable_Time, "=",
Regtests.Statements.Model.Set_Time_Value,
Regtests.Statements.Model.Get_Time_Value,
Nullable_Time '(Value => 456, Is_Null => False),
Nullable_Time '(Value => <>, Is_Null => False));
function Get_Allocate_Key (N : Identifier) return Object_Key;
function Get_Allocate_Key (N : Identifier) return Object_Key is
Result : Object_Key (Of_Type => KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
begin
Set_Value (Result, N);
return Result;
end Get_Allocate_Key;
-- ------------------------------
-- Various tests on Hash and key comparison
-- ------------------------------
procedure Test_Key (T : in out Test) is
K1 : constant Object_Key := Get_Allocate_Key (1);
K2 : Object_Key (Of_Type => KEY_STRING,
Of_Class => Regtests.Simple.Model.USER_TABLE);
K3 : Object_Key := K1;
K4 : Object_Key (Of_Type => KEY_INTEGER,
Of_Class => Regtests.Simple.Model.USER_TABLE);
begin
T.Assert (not (K1 = K2), "Key on different tables must be different");
T.Assert (not (K2 = K4), "Key with different type must be different");
T.Assert (K1 = K3, "Keys are identical");
T.Assert (Equivalent_Elements (K1, K3), "Keys are identical");
T.Assert (Equivalent_Elements (K3, K1), "Keys are identical");
T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical");
Set_Value (K3, 2);
T.Assert (not (K1 = K3), "Keys should be different");
T.Assert (Hash (K1) /= Hash (K3), "Hash should be different");
T.Assert (Hash (K1) /= Hash (K2), "Hash should be different");
Set_Value (K4, 1);
T.Assert (Hash (K1) /= Hash (K4),
"Hash on key with same value and different tables should be different");
T.Assert (not (K4 = K1), "Key on different tables should be different");
Set_Value (K2, 1);
T.Assert (Hash (K1) /= Hash (K2), "Hash should be different");
end Test_Key;
-- ------------------------------
-- Check:
-- Object_Ref := (reference counting)
-- Object_Ref.Copy
-- Object_Ref.Get_xxx generated method
-- Object_Ref.Set_xxx generated method
-- Object_Ref.=
-- ------------------------------
procedure Test_Object_Ref (T : in out Test) is
use type Regtests.Simple.Model.User_Ref;
Obj1 : Regtests.Simple.Model.User_Ref;
Null_Obj : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Obj1 = Null_Obj, "Two null objects are identical");
for I in 1 .. 10 loop
Obj1.Set_Name ("User name");
T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result");
T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object");
declare
Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1;
Obj3 : Regtests.Simple.Model.User_Ref;
begin
Obj1.Copy (Obj3);
Obj3.Set_Id (2);
-- Check the copy
T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy");
T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy");
T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment");
T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy");
-- Change original, make sure it's the same of Obj2.
Obj1.Set_Name ("Second name");
T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy");
T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment");
-- The copy is not modified
T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy");
end;
end loop;
end Test_Object_Ref;
-- ------------------------------
-- Test creation of an object with lazy loading.
-- ------------------------------
procedure Test_Create_Object (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
Cmt : Regtests.Comments.Comment_Ref;
begin
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("Joe");
User.Set_Value (0);
User.Save (S);
S.Commit;
end;
-- Load it from another session.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name),
"Cannot load created object");
Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load");
T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load");
end;
-- Create a comment for the user.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe"));
Cmt.Set_User (User);
Cmt.Set_Entity_Id (2);
Cmt.Set_Entity_Type (1);
-- Cmt.Set_Date (ADO.DEFAULT_TIME);
Cmt.Set_Date (Ada.Calendar.Clock);
Cmt.Save (S);
S.Commit;
end;
-- Load that comment.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
C2 : Regtests.Comments.Comment_Ref;
begin
T.Assert (not C2.Is_Loaded, "Object is not loaded");
C2.Load (S, Cmt.Get_Id);
T.Assert (not C2.Is_Null, "Loading of object failed");
T.Assert (C2.Is_Loaded, "Object is loaded");
T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load");
T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message),
"Invalid message");
T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null");
-- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set");
-- Check that we can access the user name (lazy load)
Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name),
"Cannot load created object");
end;
end Test_Create_Object;
-- ------------------------------
-- Test creation and deletion of an object record
-- ------------------------------
procedure Test_Delete_Object (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
begin
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("Joe (delete)");
User.Set_Value (0);
User.Save (S);
S.Commit;
end;
-- Load it and delete it from another session.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
S.Begin_Transaction;
U2.Delete (S);
S.Commit;
end;
-- Try to load the deleted object.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
T.Assert (False, "Load of a deleted object should raise NOT_FOUND");
exception
when ADO.Objects.NOT_FOUND =>
null;
end;
end Test_Delete_Object;
-- ------------------------------
-- Test Is_Inserted and Is_Null
-- ------------------------------
procedure Test_Is_Inserted (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
begin
T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED");
T.Assert (User.Is_Null, "A null object should be marked as NULL");
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("John");
T.Assert (not User.Is_Null, "User should not be NULL");
T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database");
User.Set_Value (1);
User.Save (S);
S.Commit;
T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED");
T.Assert (not User.Is_Null, "User should not be NULL");
end;
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
John : Regtests.Simple.Model.User_Ref;
begin
John.Load (S, User.Get_Id);
T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED");
T.Assert (not John.Is_Null, "After a load, the object should not be NULL");
end;
end Test_Is_Inserted;
package Caller is new Util.Test_Caller (Test, "ADO.Objects");
-- ------------------------------
-- Add the tests in the test suite
-- ------------------------------
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access);
Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Integer)",
Test_Object_Nullable_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Entity_Type)",
Test_Object_Nullable_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Time)",
Test_Object_Nullable_Time'Access);
end Add_Tests;
end ADO.Objects.Tests;
|
-----------------------------------------------------------------------
-- ADO Objects Tests -- Tests for ADO.Objects
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO.Sessions;
with Regtests.Simple.Model;
with Regtests.Comments;
with Regtests.Statements.Model;
package body ADO.Objects.Tests is
use Util.Tests;
use type Ada.Containers.Hash_Type;
-- Test the Set_xxx and Get_xxx operation on various simple times.
generic
Name : String;
type Element_Type (<>) is private;
with function "=" (Left, Right : in Element_Type) return Boolean is <>;
with procedure Set_Value (Item : in out Regtests.Statements.Model.Nullable_Table_Ref;
Val : in Element_Type);
with function Get_Value (Item : in Regtests.Statements.Model.Nullable_Table_Ref)
return Element_Type;
Val1 : Element_Type;
Val2 : Element_Type;
procedure Test_Op (T : in out Test);
procedure Test_Op (T : in out Test) is
Item1 : Regtests.Statements.Model.Nullable_Table_Ref;
Item2 : Regtests.Statements.Model.Nullable_Table_Ref;
Item3 : Regtests.Statements.Model.Nullable_Table_Ref;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
Set_Value (Item1, Val1);
Item1.Save (DB);
T.Assert (Item1.Is_Inserted, Name & " item is created");
-- Util.Tests.Assert_Equals (T, T'Image (Val), T'Image (
-- Load in a second item and check the value.
Item2.Load (DB, Item1.Get_Id);
T.Assert (Item2.Get_Id = Item1.Get_Id, Name & " item2 cannot be loaded");
-- T.Assert (Get_Value (Item2) = Val1, Name & " invalid value loaded in item2");
-- Change the item in database.
Set_Value (Item2, Val2);
Item2.Save (DB);
T.Assert (Get_Value (Item2) = Val2, Name & " invalid value loaded in item2");
-- Load again and compare to check the update.
Item3.Load (DB, Item2.Get_Id);
T.Assert (Get_Value (Item3) = Val2, Name & " invalid value loaded in item3");
end Test_Op;
procedure Test_Object_Nullable_Integer is
new Test_Op ("Nullable_Integer",
Nullable_Integer, "=",
Regtests.Statements.Model.Set_Int_Value,
Regtests.Statements.Model.Get_Int_Value,
Nullable_Integer '(Value => 123, Is_Null => False),
Nullable_Integer '(Value => 0, Is_Null => True));
procedure Test_Object_Nullable_Entity_Type is
new Test_Op ("Nullable_Entity_Type",
Nullable_Entity_Type, "=",
Regtests.Statements.Model.Set_Entity_Value,
Regtests.Statements.Model.Get_Entity_Value,
Nullable_Entity_Type '(Value => 456, Is_Null => False),
Nullable_Entity_Type '(Value => 0, Is_Null => True));
procedure Test_Object_Nullable_Time is
new Test_Op ("Nullable_Time",
Nullable_Time, "=",
Regtests.Statements.Model.Set_Time_Value,
Regtests.Statements.Model.Get_Time_Value,
Nullable_Time '(Value => 456, Is_Null => False),
Nullable_Time '(Value => <>, Is_Null => True));
function Get_Allocate_Key (N : Identifier) return Object_Key;
function Get_Allocate_Key (N : Identifier) return Object_Key is
Result : Object_Key (Of_Type => KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
begin
Set_Value (Result, N);
return Result;
end Get_Allocate_Key;
-- ------------------------------
-- Various tests on Hash and key comparison
-- ------------------------------
procedure Test_Key (T : in out Test) is
K1 : constant Object_Key := Get_Allocate_Key (1);
K2 : Object_Key (Of_Type => KEY_STRING,
Of_Class => Regtests.Simple.Model.USER_TABLE);
K3 : Object_Key := K1;
K4 : Object_Key (Of_Type => KEY_INTEGER,
Of_Class => Regtests.Simple.Model.USER_TABLE);
begin
T.Assert (not (K1 = K2), "Key on different tables must be different");
T.Assert (not (K2 = K4), "Key with different type must be different");
T.Assert (K1 = K3, "Keys are identical");
T.Assert (Equivalent_Elements (K1, K3), "Keys are identical");
T.Assert (Equivalent_Elements (K3, K1), "Keys are identical");
T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical");
Set_Value (K3, 2);
T.Assert (not (K1 = K3), "Keys should be different");
T.Assert (Hash (K1) /= Hash (K3), "Hash should be different");
T.Assert (Hash (K1) /= Hash (K2), "Hash should be different");
Set_Value (K4, 1);
T.Assert (Hash (K1) /= Hash (K4),
"Hash on key with same value and different tables should be different");
T.Assert (not (K4 = K1), "Key on different tables should be different");
Set_Value (K2, 1);
T.Assert (Hash (K1) /= Hash (K2), "Hash should be different");
end Test_Key;
-- ------------------------------
-- Check:
-- Object_Ref := (reference counting)
-- Object_Ref.Copy
-- Object_Ref.Get_xxx generated method
-- Object_Ref.Set_xxx generated method
-- Object_Ref.=
-- ------------------------------
procedure Test_Object_Ref (T : in out Test) is
use type Regtests.Simple.Model.User_Ref;
Obj1 : Regtests.Simple.Model.User_Ref;
Null_Obj : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Obj1 = Null_Obj, "Two null objects are identical");
for I in 1 .. 10 loop
Obj1.Set_Name ("User name");
T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result");
T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object");
declare
Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1;
Obj3 : Regtests.Simple.Model.User_Ref;
begin
Obj1.Copy (Obj3);
Obj3.Set_Id (2);
-- Check the copy
T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy");
T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy");
T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment");
T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy");
-- Change original, make sure it's the same of Obj2.
Obj1.Set_Name ("Second name");
T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy");
T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment");
-- The copy is not modified
T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy");
end;
end loop;
end Test_Object_Ref;
-- ------------------------------
-- Test creation of an object with lazy loading.
-- ------------------------------
procedure Test_Create_Object (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
Cmt : Regtests.Comments.Comment_Ref;
begin
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("Joe");
User.Set_Value (0);
User.Save (S);
S.Commit;
end;
-- Load it from another session.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name),
"Cannot load created object");
Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load");
T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load");
end;
-- Create a comment for the user.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe"));
Cmt.Set_User (User);
Cmt.Set_Entity_Id (2);
Cmt.Set_Entity_Type (1);
-- Cmt.Set_Date (ADO.DEFAULT_TIME);
Cmt.Set_Date (Ada.Calendar.Clock);
Cmt.Save (S);
S.Commit;
end;
-- Load that comment.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
C2 : Regtests.Comments.Comment_Ref;
begin
T.Assert (not C2.Is_Loaded, "Object is not loaded");
C2.Load (S, Cmt.Get_Id);
T.Assert (not C2.Is_Null, "Loading of object failed");
T.Assert (C2.Is_Loaded, "Object is loaded");
T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load");
T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message),
"Invalid message");
T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null");
-- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set");
-- Check that we can access the user name (lazy load)
Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name),
"Cannot load created object");
end;
end Test_Create_Object;
-- ------------------------------
-- Test creation and deletion of an object record
-- ------------------------------
procedure Test_Delete_Object (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
begin
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("Joe (delete)");
User.Set_Value (0);
User.Save (S);
S.Commit;
end;
-- Load it and delete it from another session.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
S.Begin_Transaction;
U2.Delete (S);
S.Commit;
end;
-- Try to load the deleted object.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
T.Assert (False, "Load of a deleted object should raise NOT_FOUND");
exception
when ADO.Objects.NOT_FOUND =>
null;
end;
end Test_Delete_Object;
-- ------------------------------
-- Test Is_Inserted and Is_Null
-- ------------------------------
procedure Test_Is_Inserted (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
begin
T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED");
T.Assert (User.Is_Null, "A null object should be marked as NULL");
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("John");
T.Assert (not User.Is_Null, "User should not be NULL");
T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database");
User.Set_Value (1);
User.Save (S);
S.Commit;
T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED");
T.Assert (not User.Is_Null, "User should not be NULL");
end;
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
John : Regtests.Simple.Model.User_Ref;
begin
John.Load (S, User.Get_Id);
T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED");
T.Assert (not John.Is_Null, "After a load, the object should not be NULL");
end;
end Test_Is_Inserted;
package Caller is new Util.Test_Caller (Test, "ADO.Objects");
-- ------------------------------
-- Add the tests in the test suite
-- ------------------------------
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access);
Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Integer)",
Test_Object_Nullable_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Entity_Type)",
Test_Object_Nullable_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Time)",
Test_Object_Nullable_Time'Access);
end Add_Tests;
end ADO.Objects.Tests;
|
Fix the unit test on nullable_time
|
Fix the unit test on nullable_time
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
34155e0a74505179db7f5a307de43b26547e0317
|
src/util-encoders-sha256.ads
|
src/util-encoders-sha256.ads
|
-----------------------------------------------------------------------
-- util-encoders-sha256 -- Compute SHA-1 hash
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with GNAT.SHA256;
package Util.Encoders.SHA256 is
-- The SHA-256 binary hash (256-bit).
subtype Hash_Array is Ada.Streams.Stream_Element_Array (0 .. 31);
-- The SHA-256 hash as hexadecimal string.
subtype Digest is String (1 .. 64);
subtype Base64_Digest is String (1 .. 44);
-- ------------------------------
-- SHA256 Context
-- ------------------------------
subtype Context is GNAT.SHA256.Context;
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String) renames GNAT.SHA256.Update;
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array) renames GNAT.SHA256.Update;
-- Computes the SHA256 hash and returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Hash_Array);
-- Computes the SHA256 hash and returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Digest);
-- Computes the SHA256 hash and returns the base64 hash in <b>Hash</b>.
procedure Finish_Base64 (E : in out Context;
Hash : out Base64_Digest);
end Util.Encoders.SHA256;
|
-----------------------------------------------------------------------
-- util-encoders-sha256 -- Compute SHA-256 hash
-- 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 Ada.Streams;
with GNAT.SHA256;
package Util.Encoders.SHA256 is
-- The SHA-256 binary hash (256-bit).
subtype Hash_Array is Ada.Streams.Stream_Element_Array (0 .. 31);
-- The SHA-256 hash as hexadecimal string.
subtype Digest is String (1 .. 64);
subtype Base64_Digest is String (1 .. 44);
-- ------------------------------
-- SHA256 Context
-- ------------------------------
subtype Context is GNAT.SHA256.Context;
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String) renames GNAT.SHA256.Update;
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array) renames GNAT.SHA256.Update;
-- Computes the SHA256 hash and returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Hash_Array);
-- Computes the SHA256 hash and returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Digest);
-- Computes the SHA256 hash and returns the base64 hash in <b>Hash</b>.
procedure Finish_Base64 (E : in out Context;
Hash : out Base64_Digest);
end Util.Encoders.SHA256;
|
Fix header comment
|
Fix header comment
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
61c6a1d0ab2b70265e421037fe507c7e81ed9b67
|
src/asf-servlets-files.adb
|
src/asf-servlets-files.adb
|
-----------------------------------------------------------------------
-- asf.servlets.files -- Static file servlet
-- Copyright (C) 2010, 2011, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Files;
with Util.Log.Loggers;
with Util.Strings;
with Util.Streams;
with Util.Streams.Files;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Directories;
with ASF.Streams;
with ASF.Applications;
package body ASF.Servlets.Files is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Servlets.Files");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out File_Servlet;
Context : in Servlet_Registry'Class) is
Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR);
Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default");
begin
if Dir = "" then
Server.Dir := new String '("./");
else
Server.Dir := new String '(Dir);
end if;
Server.Default_Content_Type := new String '(Def_Type);
Log.Info ("File servlet using directory '{0}'", Server.Dir.all);
end Initialize;
-- ------------------------------
-- Returns the time the Request object was last modified, in milliseconds since
-- midnight January 1, 1970 GMT. If the time is unknown, this method returns
-- a negative number (the default).
--
-- Servlets that support HTTP GET requests and can quickly determine their
-- last modification time should override this method. This makes browser and
-- proxy caches work more effectively, reducing the load on server and network
-- resources.
-- ------------------------------
function Get_Last_Modified (Server : in File_Servlet;
Request : in Requests.Request'Class)
return Ada.Calendar.Time is
pragma Unreferenced (Server, Request);
begin
return Ada.Calendar.Clock;
end Get_Last_Modified;
-- ------------------------------
-- Set the content type associated with the given file
-- ------------------------------
procedure Set_Content_Type (Server : in File_Servlet;
Path : in String;
Response : in out Responses.Response'Class) is
Pos : constant Natural := Util.Strings.Rindex (Path, '.');
begin
if Pos = 0 then
Response.Set_Content_Type (Server.Default_Content_Type.all);
return;
end if;
if Path (Pos .. Path'Last) = ".css" then
Response.Set_Content_Type ("text/css");
return;
end if;
if Path (Pos .. Path'Last) = ".js" then
Response.Set_Content_Type ("text/javascript");
return;
end if;
if Path (Pos .. Path'Last) = ".html" then
Response.Set_Content_Type ("text/html");
return;
end if;
if Path (Pos .. Path'Last) = ".txt" then
Response.Set_Content_Type ("text/plain");
return;
end if;
if Path (Pos .. Path'Last) = ".png" then
Response.Set_Content_Type ("image/png");
return;
end if;
if Path (Pos .. Path'Last) = ".jpg" then
Response.Set_Content_Type ("image/jpg");
return;
end if;
Response.Set_Content_Type (Server.Default_Content_Type.all);
end Set_Content_Type;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
procedure Do_Get (Server : in File_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use Util.Files;
URI : constant String := Request.Get_Servlet_Path;
Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all);
begin
if Path'Length = 0 or else not Ada.Directories.Exists (Path)
or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File
then
Log.Debug ("Servlet file cannot read file {0}", Path);
Response.Send_Error (Responses.SC_NOT_FOUND);
return;
end if;
File_Servlet'Class (Server).Set_Content_Type (Path, Response);
declare
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
Input : Util.Streams.Files.File_Stream;
begin
Input.Open (Name => Path, Mode => In_File);
Util.Streams.Copy (From => Input, Into => Output);
end;
end Do_Get;
end ASF.Servlets.Files;
|
-----------------------------------------------------------------------
-- asf.servlets.files -- Static file servlet
-- Copyright (C) 2010, 2011, 2013, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Files;
with Util.Log.Loggers;
with Util.Strings;
with Util.Streams;
with Util.Streams.Files;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Directories;
with ASF.Streams;
with ASF.Applications;
package body ASF.Servlets.Files is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Servlets.Files");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out File_Servlet;
Context : in Servlet_Registry'Class) is
Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR);
Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default");
begin
if Dir = "" then
Server.Dir := new String '("./");
else
Server.Dir := new String '(Dir);
end if;
Server.Default_Content_Type := new String '(Def_Type);
Log.Info ("File servlet using directory '{0}'", Server.Dir.all);
end Initialize;
-- ------------------------------
-- Returns the time the Request object was last modified, in milliseconds since
-- midnight January 1, 1970 GMT. If the time is unknown, this method returns
-- a negative number (the default).
--
-- Servlets that support HTTP GET requests and can quickly determine their
-- last modification time should override this method. This makes browser and
-- proxy caches work more effectively, reducing the load on server and network
-- resources.
-- ------------------------------
function Get_Last_Modified (Server : in File_Servlet;
Request : in Requests.Request'Class)
return Ada.Calendar.Time is
pragma Unreferenced (Server, Request);
begin
return Ada.Calendar.Clock;
end Get_Last_Modified;
-- ------------------------------
-- Set the content type associated with the given file
-- ------------------------------
procedure Set_Content_Type (Server : in File_Servlet;
Path : in String;
Response : in out Responses.Response'Class) is
Pos : constant Natural := Util.Strings.Rindex (Path, '.');
begin
if Pos = 0 then
Response.Set_Content_Type (Server.Default_Content_Type.all);
return;
end if;
if Path (Pos .. Path'Last) = ".css" then
Response.Set_Content_Type ("text/css");
return;
end if;
if Path (Pos .. Path'Last) = ".js" then
Response.Set_Content_Type ("text/javascript");
return;
end if;
if Path (Pos .. Path'Last) = ".html" then
Response.Set_Content_Type ("text/html");
return;
end if;
if Path (Pos .. Path'Last) = ".txt" then
Response.Set_Content_Type ("text/plain");
return;
end if;
if Path (Pos .. Path'Last) = ".png" then
Response.Set_Content_Type ("image/png");
return;
end if;
if Path (Pos .. Path'Last) = ".jpg" then
Response.Set_Content_Type ("image/jpg");
return;
end if;
if Path (Pos .. Path'Last) = ".pdf" then
Response.Set_Content_Type ("application/pdf");
return;
end if;
if Path (Pos .. Path'Last) = ".svg" then
Response.Set_Content_Type ("image/svg+xml");
return;
end if;
if Path (Pos .. Path'Last) = ".ico" then
Response.Set_Content_Type ("image/vnd.microsoft.icon");
return;
end if;
Response.Set_Content_Type (Server.Default_Content_Type.all);
end Set_Content_Type;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
procedure Do_Get (Server : in File_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use Util.Files;
URI : constant String := Request.Get_Servlet_Path;
Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all);
begin
if Path'Length = 0 or else not Ada.Directories.Exists (Path)
or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File
then
Log.Debug ("Servlet file cannot read file {0}", Path);
Response.Send_Error (Responses.SC_NOT_FOUND);
return;
end if;
File_Servlet'Class (Server).Set_Content_Type (Path, Response);
declare
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
Input : Util.Streams.Files.File_Stream;
begin
Input.Open (Name => Path, Mode => In_File);
Util.Streams.Copy (From => Input, Into => Output);
end;
end Do_Get;
end ASF.Servlets.Files;
|
Add pdf, svg and .ico mime types
|
Add pdf, svg and .ico mime types
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
d8048aacd5228dd7a1f2cf0c04d92060d3697377
|
src/gen-model-enums.ads
|
src/gen-model-enums.ads
|
-----------------------------------------------------------------------
-- gen-model-enums -- Enum definitions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Mappings;
with Gen.Model.Packages;
package Gen.Model.Enums is
use Ada.Strings.Unbounded;
type Enum_Definition;
type Enum_Definition_Access is access all Enum_Definition'Class;
-- ------------------------------
-- Enum value definition
-- ------------------------------
type Value_Definition is new Definition with record
Number : Natural := 0;
Enum : Enum_Definition_Access;
end record;
type Value_Definition_Access is access all Value_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Value_Definition;
Name : String) return Util.Beans.Objects.Object;
package Value_List is new Gen.Model.List (T => Value_Definition,
T_Access => Value_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Enum_Definition is new Mappings.Mapping_Definition with record
Values : aliased Value_List.List_Definition;
Values_Bean : Util.Beans.Objects.Object;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Enum_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Enum_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Enum_Definition);
-- Add an enum value to this enum definition and return the new value.
procedure Add_Value (Enum : in out Enum_Definition;
Name : in String;
Value : out Value_Definition_Access);
-- Create an enum with the given name.
function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access;
end Gen.Model.Enums;
|
-----------------------------------------------------------------------
-- gen-model-enums -- Enum definitions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Gen.Model.List;
with Gen.Model.Mappings;
with Gen.Model.Packages;
package Gen.Model.Enums is
use Ada.Strings.Unbounded;
type Enum_Definition;
type Enum_Definition_Access is access all Enum_Definition'Class;
-- ------------------------------
-- Enum value definition
-- ------------------------------
type Value_Definition is new Definition with record
Number : Natural := 0;
Enum : Enum_Definition_Access;
end record;
type Value_Definition_Access is access all Value_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Value_Definition;
Name : String) return Util.Beans.Objects.Object;
package Value_List is new Gen.Model.List (T => Value_Definition,
T_Access => Value_Definition_Access);
-- ------------------------------
-- Table Definition
-- ------------------------------
type Enum_Definition is new Mappings.Mapping_Definition with record
Values : aliased Value_List.List_Definition;
Values_Bean : Util.Beans.Objects.Object;
Package_Def : Gen.Model.Packages.Package_Definition_Access;
Type_Name : Unbounded_String;
Pkg_Name : Unbounded_String;
Sql_Type : Unbounded_String;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : Enum_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Enum_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Enum_Definition);
-- Add an enum value to this enum definition and return the new value.
procedure Add_Value (Enum : in out Enum_Definition;
Name : in String;
Value : out Value_Definition_Access);
-- Create an enum with the given name.
function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access;
end Gen.Model.Enums;
|
Add an sql type mapping for the enum
|
Add an sql type mapping for the enum
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
3fe825cbacad7e70bb13c9a7e7a6c5e7a4866ff8
|
regtests/asf-contexts-faces-tests.adb
|
regtests/asf-contexts-faces-tests.adb
|
-----------------------------------------------------------------------
-- Faces Context Tests - Unit tests for ASF.Contexts.Faces
-- Copyright (C) 2010, 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 Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with EL.Variables.Default;
with ASF.Contexts.Flash;
with ASF.Contexts.Faces.Mockup;
package body ASF.Contexts.Faces.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Contexts.Faces");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Add_Message",
Test_Add_Message'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Max_Severity",
Test_Max_Severity'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Message",
Test_Get_Messages'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Queue_Exception",
Test_Queue_Exception'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Flash",
Test_Flash_Context'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Attribute",
Test_Get_Attribute'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Bean",
Test_Get_Bean'Access);
Caller.Add_Test (Suite, "Test ASF.Helpers.Beans.Get_Bean",
Test_Get_Bean_Helper'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Mockup",
Test_Mockup_Faces_Context'Access);
end Add_Tests;
-- ------------------------------
-- Setup the faces context for the unit test.
-- ------------------------------
procedure Setup (T : in out Test;
Context : in out Faces_Context) is
begin
T.Form := new ASF.Applications.Tests.Form_Bean;
Context.Set_ELContext (T.ELContext.all'Access);
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("dumbledore"),
EL.Objects.To_Object (String '("albus")));
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("potter"),
EL.Objects.To_Object (String '("harry")));
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("hogwarts"),
EL.Objects.To_Object (T.Form.all'Access,
EL.Objects.STATIC));
end Setup;
-- ------------------------------
-- Cleanup the test instance.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (ASF.Applications.Tests.Form_Bean'Class,
ASF.Applications.Tests.Form_Bean_Access);
begin
ASF.Tests.EL_Test (T).Tear_Down;
Free (T.Form);
end Tear_Down;
-- ------------------------------
-- Test getting an attribute from the faces context.
-- ------------------------------
procedure Test_Get_Attribute (T : in out Test) is
Ctx : Faces_Context;
Name : EL.Objects.Object;
begin
T.Setup (Ctx);
Name := Ctx.Get_Attribute ("dumbledore");
T.Assert (not EL.Objects.Is_Null (Name), "Null attribute returned");
Util.Tests.Assert_Equals (T, "albus", EL.Objects.To_String (Name), "Invalid attribute");
Name := Ctx.Get_Attribute ("potter");
T.Assert (not EL.Objects.Is_Null (Name), "Null attribute returned");
Util.Tests.Assert_Equals (T, "harry", EL.Objects.To_String (Name), "Invalid attribute");
Name := Ctx.Get_Attribute ("voldemort");
T.Assert (EL.Objects.Is_Null (Name), "Oops... is there any horcrux left?");
end Test_Get_Attribute;
-- ------------------------------
-- Test getting a bean object from the faces context.
-- ------------------------------
procedure Test_Get_Bean (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Ctx : Faces_Context;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
begin
T.Setup (Ctx);
Bean := Ctx.Get_Bean ("dumbledore");
T.Assert (Bean = null, "Dumbledore should not be a bean");
Bean := Ctx.Get_Bean ("hogwarts");
T.Assert (Bean /= null, "hogwarts should be a bean");
end Test_Get_Bean;
-- ------------------------------
-- Test getting a bean object from the faces context and doing a conversion.
-- ------------------------------
procedure Test_Get_Bean_Helper (T : in out Test) is
use type ASF.Applications.Tests.Form_Bean_Access;
Ctx : aliased Faces_Context;
Bean : ASF.Applications.Tests.Form_Bean_Access;
begin
T.Setup (Ctx);
Bean := Get_Form_Bean ("hogwarts");
T.Assert (Bean = null, "A bean was found while the faces context does not exist!");
ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, null);
Bean := Get_Form_Bean ("hogwarts");
T.Assert (Bean /= null, "hogwarts should be a bean");
Bean := Get_Form_Bean ("dumbledore");
T.Assert (Bean = null, "Dumbledore should not be a bean");
ASF.Contexts.Faces.Restore (null);
end Test_Get_Bean_Helper;
-- ------------------------------
-- Test the faces message queue.
-- ------------------------------
procedure Test_Add_Message (T : in out Test) is
Ctx : Faces_Context;
begin
Ctx.Add_Message (Client_Id => "", Message => "msg1");
Ctx.Add_Message (Client_Id => "", Message => "msg1");
Ctx.Add_Message (Client_Id => "", Message => "msg2");
Ctx.Add_Message (Client_Id => "", Message => "msg3");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO);
Ctx.Add_Message (Client_Id => "warn", Message => "msg3", Severity => WARN);
Ctx.Add_Message (Client_Id => "error", Message => "msg3", Severity => ERROR);
Ctx.Add_Message (Client_Id => "fatal", Message => "msg3", Severity => FATAL);
T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Add message failed");
end Test_Add_Message;
procedure Test_Max_Severity (T : in out Test) is
Ctx : Faces_Context;
begin
T.Assert (Ctx.Get_Maximum_Severity = NONE, "Invalid max severity with no message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO);
T.Assert (Ctx.Get_Maximum_Severity = INFO, "Invalid max severity with info message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => WARN);
T.Assert (Ctx.Get_Maximum_Severity = WARN, "Invalid max severity with warn message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => FATAL);
T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Invalid max severity with warn message");
end Test_Max_Severity;
procedure Test_Get_Messages (T : in out Test) is
Ctx : Faces_Context;
begin
-- Iterator on an empty message list.
declare
Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "");
begin
T.Assert (not Vectors.Has_Element (Iter), "Iterator should indicate no message");
end;
Ctx.Add_Message (Client_Id => "info", Message => "msg1", Severity => INFO);
declare
Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "info");
M : Message;
begin
T.Assert (Vectors.Has_Element (Iter), "Iterator should indicate a message");
M := Vectors.Element (Iter);
Assert_Equals (T, "msg1", Get_Summary (M), "Invalid message");
Assert_Equals (T, "msg1", Get_Detail (M), "Invalid details");
T.Assert (INFO = Get_Severity (M), "Invalid severity");
end;
end Test_Get_Messages;
-- ------------------------------
-- Test adding some exception in the faces context.
-- ------------------------------
procedure Test_Queue_Exception (T : in out Test) is
procedure Raise_Exception (Depth : in Natural;
Excep : in Natural);
procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Faces_Context'Class);
Ctx : Faces_Context;
Cnt : Natural := 0;
procedure Raise_Exception (Depth : in Natural;
Excep : in Natural) is
begin
if Depth > 0 then
Raise_Exception (Depth - 1, Excep);
end if;
case Excep is
when 1 =>
raise Constraint_Error with "except code 1";
when 2 =>
raise Ada.IO_Exceptions.Name_Error;
when others =>
raise Program_Error with "Testing program error";
end case;
end Raise_Exception;
procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Context, Event);
begin
Cnt := Cnt + 1;
Remove := False;
end Check_Exception;
begin
-- Create some exceptions and queue them.
for I in 1 .. 3 loop
begin
Raise_Exception (3, I);
exception
when E : others =>
Ctx.Queue_Exception (E);
end;
end loop;
Ctx.Iterate_Exception (Check_Exception'Access);
Util.Tests.Assert_Equals (T, 3, Cnt, "3 exception should have been queued");
end Test_Queue_Exception;
-- ------------------------------
-- Test the flash instance.
-- ------------------------------
procedure Test_Flash_Context (T : in out Test) is
use type ASF.Contexts.Faces.Flash_Context_Access;
Ctx : Faces_Context;
Flash : aliased ASF.Contexts.Flash.Flash_Context;
begin
Ctx.Set_Flash (Flash'Unchecked_Access);
T.Assert (Ctx.Get_Flash /= null, "Null flash context returned");
end Test_Flash_Context;
-- ------------------------------
-- Test the mockup faces context.
-- ------------------------------
procedure Test_Mockup_Faces_Context (T : in out Test) is
use type ASF.Requests.Request_Access;
use type ASF.Responses.Response_Access;
use type EL.Contexts.ELContext_Access;
begin
ASF.Applications.Tests.Initialize_Test_Application;
declare
Ctx : Mockup.Mockup_Faces_Context;
begin
Ctx.Set_Method ("GET");
Ctx.Set_Path_Info ("something.html");
T.Assert (Current /= null, "There is no current faces context (mockup failed)");
T.Assert (Current.Get_Request /= null, "There is no current request");
T.Assert (Current.Get_Response /= null, "There is no current response");
T.Assert (Current.Get_Application /= null, "There is no current application");
T.Assert (Current.Get_ELContext /= null, "There is no current ELcontext");
end;
T.Assert (Current = null, "There is a current faces context but it shoudl be null");
end Test_Mockup_Faces_Context;
end ASF.Contexts.Faces.Tests;
|
-----------------------------------------------------------------------
-- Faces Context Tests - Unit tests for ASF.Contexts.Faces
-- Copyright (C) 2010, 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 Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with EL.Variables.Default;
with ASF.Applications.Messages.Factory;
with ASF.Contexts.Flash;
with ASF.Contexts.Faces.Mockup;
package body ASF.Contexts.Faces.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Contexts.Faces");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Add_Message",
Test_Add_Message'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Max_Severity",
Test_Max_Severity'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Message",
Test_Get_Messages'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Queue_Exception",
Test_Queue_Exception'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Flash",
Test_Flash_Context'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Attribute",
Test_Get_Attribute'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Bean",
Test_Get_Bean'Access);
Caller.Add_Test (Suite, "Test ASF.Helpers.Beans.Get_Bean",
Test_Get_Bean_Helper'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Mockup",
Test_Mockup_Faces_Context'Access);
Caller.Add_Test (Suite, "Test ASF.Applications.Messages.Factory.Add_Message",
Test_Add_Localized_Message'Access);
end Add_Tests;
-- ------------------------------
-- Setup the faces context for the unit test.
-- ------------------------------
procedure Setup (T : in out Test;
Context : in out Faces_Context) is
begin
T.Form := new ASF.Applications.Tests.Form_Bean;
Context.Set_ELContext (T.ELContext.all'Access);
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("dumbledore"),
EL.Objects.To_Object (String '("albus")));
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("potter"),
EL.Objects.To_Object (String '("harry")));
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("hogwarts"),
EL.Objects.To_Object (T.Form.all'Access,
EL.Objects.STATIC));
end Setup;
-- ------------------------------
-- Cleanup the test instance.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (ASF.Applications.Tests.Form_Bean'Class,
ASF.Applications.Tests.Form_Bean_Access);
begin
ASF.Tests.EL_Test (T).Tear_Down;
Free (T.Form);
end Tear_Down;
-- ------------------------------
-- Test getting an attribute from the faces context.
-- ------------------------------
procedure Test_Get_Attribute (T : in out Test) is
Ctx : Faces_Context;
Name : EL.Objects.Object;
begin
T.Setup (Ctx);
Name := Ctx.Get_Attribute ("dumbledore");
T.Assert (not EL.Objects.Is_Null (Name), "Null attribute returned");
Util.Tests.Assert_Equals (T, "albus", EL.Objects.To_String (Name), "Invalid attribute");
Name := Ctx.Get_Attribute ("potter");
T.Assert (not EL.Objects.Is_Null (Name), "Null attribute returned");
Util.Tests.Assert_Equals (T, "harry", EL.Objects.To_String (Name), "Invalid attribute");
Name := Ctx.Get_Attribute ("voldemort");
T.Assert (EL.Objects.Is_Null (Name), "Oops... is there any horcrux left?");
end Test_Get_Attribute;
-- ------------------------------
-- Test getting a bean object from the faces context.
-- ------------------------------
procedure Test_Get_Bean (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Ctx : Faces_Context;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
begin
T.Setup (Ctx);
Bean := Ctx.Get_Bean ("dumbledore");
T.Assert (Bean = null, "Dumbledore should not be a bean");
Bean := Ctx.Get_Bean ("hogwarts");
T.Assert (Bean /= null, "hogwarts should be a bean");
end Test_Get_Bean;
-- ------------------------------
-- Test getting a bean object from the faces context and doing a conversion.
-- ------------------------------
procedure Test_Get_Bean_Helper (T : in out Test) is
use type ASF.Applications.Tests.Form_Bean_Access;
Ctx : aliased Faces_Context;
Bean : ASF.Applications.Tests.Form_Bean_Access;
begin
T.Setup (Ctx);
Bean := Get_Form_Bean ("hogwarts");
T.Assert (Bean = null, "A bean was found while the faces context does not exist!");
ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, null);
Bean := Get_Form_Bean ("hogwarts");
T.Assert (Bean /= null, "hogwarts should be a bean");
Bean := Get_Form_Bean ("dumbledore");
T.Assert (Bean = null, "Dumbledore should not be a bean");
ASF.Contexts.Faces.Restore (null);
end Test_Get_Bean_Helper;
-- ------------------------------
-- Test the faces message queue.
-- ------------------------------
procedure Test_Add_Message (T : in out Test) is
Ctx : Faces_Context;
begin
Ctx.Add_Message (Client_Id => "", Message => "msg1");
Ctx.Add_Message (Client_Id => "", Message => "msg1");
Ctx.Add_Message (Client_Id => "", Message => "msg2");
Ctx.Add_Message (Client_Id => "", Message => "msg3");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO);
Ctx.Add_Message (Client_Id => "warn", Message => "msg3", Severity => WARN);
Ctx.Add_Message (Client_Id => "error", Message => "msg3", Severity => ERROR);
Ctx.Add_Message (Client_Id => "fatal", Message => "msg3", Severity => FATAL);
T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Add message failed");
end Test_Add_Message;
-- ------------------------------
-- Test the application message factory for the creation of localized messages.
-- ------------------------------
procedure Test_Add_Localized_Message (T : in out Test) is
App : aliased Applications.Main.Application;
App_Factory : Applications.Main.Application_Factory;
Ctx : aliased Faces_Context;
Conf : Applications.Config;
begin
Conf.Load_Properties ("regtests/view.properties");
App.Initialize (Conf, App_Factory);
Set_Current (Ctx'Unchecked_Access, App'Unchecked_Access);
ASF.Applications.Messages.Factory.Add_Message (Ctx, "asf.validators.length.maximum",
"23");
-- ASF.Applications.Messages.Factory.Add_Message (Ctx, "asf.exceptions.unexpected.extended",
-- "Fake-exception", "Fake-message");
T.Assert (Ctx.Get_Maximum_Severity = ERROR, "Add message failed");
end Test_Add_Localized_Message;
procedure Test_Max_Severity (T : in out Test) is
Ctx : Faces_Context;
begin
T.Assert (Ctx.Get_Maximum_Severity = NONE, "Invalid max severity with no message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO);
T.Assert (Ctx.Get_Maximum_Severity = INFO, "Invalid max severity with info message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => WARN);
T.Assert (Ctx.Get_Maximum_Severity = WARN, "Invalid max severity with warn message");
Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => FATAL);
T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Invalid max severity with warn message");
end Test_Max_Severity;
procedure Test_Get_Messages (T : in out Test) is
Ctx : Faces_Context;
begin
-- Iterator on an empty message list.
declare
Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "");
begin
T.Assert (not Vectors.Has_Element (Iter), "Iterator should indicate no message");
end;
Ctx.Add_Message (Client_Id => "info", Message => "msg1", Severity => INFO);
declare
Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "info");
M : Message;
begin
T.Assert (Vectors.Has_Element (Iter), "Iterator should indicate a message");
M := Vectors.Element (Iter);
Assert_Equals (T, "msg1", Get_Summary (M), "Invalid message");
Assert_Equals (T, "msg1", Get_Detail (M), "Invalid details");
T.Assert (INFO = Get_Severity (M), "Invalid severity");
end;
end Test_Get_Messages;
-- ------------------------------
-- Test adding some exception in the faces context.
-- ------------------------------
procedure Test_Queue_Exception (T : in out Test) is
procedure Raise_Exception (Depth : in Natural;
Excep : in Natural);
procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Faces_Context'Class);
Ctx : Faces_Context;
Cnt : Natural := 0;
procedure Raise_Exception (Depth : in Natural;
Excep : in Natural) is
begin
if Depth > 0 then
Raise_Exception (Depth - 1, Excep);
end if;
case Excep is
when 1 =>
raise Constraint_Error with "except code 1";
when 2 =>
raise Ada.IO_Exceptions.Name_Error;
when others =>
raise Program_Error with "Testing program error";
end case;
end Raise_Exception;
procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Context, Event);
begin
Cnt := Cnt + 1;
Remove := False;
end Check_Exception;
begin
-- Create some exceptions and queue them.
for I in 1 .. 3 loop
begin
Raise_Exception (3, I);
exception
when E : others =>
Ctx.Queue_Exception (E);
end;
end loop;
Ctx.Iterate_Exception (Check_Exception'Access);
Util.Tests.Assert_Equals (T, 3, Cnt, "3 exception should have been queued");
end Test_Queue_Exception;
-- ------------------------------
-- Test the flash instance.
-- ------------------------------
procedure Test_Flash_Context (T : in out Test) is
use type ASF.Contexts.Faces.Flash_Context_Access;
Ctx : Faces_Context;
Flash : aliased ASF.Contexts.Flash.Flash_Context;
begin
Ctx.Set_Flash (Flash'Unchecked_Access);
T.Assert (Ctx.Get_Flash /= null, "Null flash context returned");
end Test_Flash_Context;
-- ------------------------------
-- Test the mockup faces context.
-- ------------------------------
procedure Test_Mockup_Faces_Context (T : in out Test) is
use type ASF.Requests.Request_Access;
use type ASF.Responses.Response_Access;
use type EL.Contexts.ELContext_Access;
begin
ASF.Applications.Tests.Initialize_Test_Application;
declare
Ctx : Mockup.Mockup_Faces_Context;
begin
Ctx.Set_Method ("GET");
Ctx.Set_Path_Info ("something.html");
T.Assert (Current /= null, "There is no current faces context (mockup failed)");
T.Assert (Current.Get_Request /= null, "There is no current request");
T.Assert (Current.Get_Response /= null, "There is no current response");
T.Assert (Current.Get_Application /= null, "There is no current application");
T.Assert (Current.Get_ELContext /= null, "There is no current ELcontext");
end;
T.Assert (Current = null, "There is a current faces context but it shoudl be null");
end Test_Mockup_Faces_Context;
end ASF.Contexts.Faces.Tests;
|
Add test for localization messages
|
Add test for localization messages
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
afe7a770c1995118628e40cb3eaa931e13f5a723
|
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.
-----------------------------------------------------------------------
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;
end Babel.Files.Signatures;
|
-----------------------------------------------------------------------
-- 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;
|
Implement the Save_Checksum procedure
|
Implement the Save_Checksum procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
d9e4666fe29cd8579ded39bcd6082f0075fb9d81
|
tools/druss-commands-wifi.adb
|
tools/druss-commands-wifi.adb
|
-----------------------------------------------------------------------
-- druss-commands-wifi -- Wifi related commands
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Bbox.API;
package body Druss.Commands.Wifi is
use Ada.Strings.Unbounded;
use Ada.Text_IO;
-- ------------------------------
-- Enable or disable with wifi radio.
-- ------------------------------
procedure Set_Enable (Command : in Command_Type;
Args : in Argument_List'Class;
Value : in String;
Context : in out Context_Type) is
procedure Radio (Gateway : in out Druss.Gateways.Gateway_Type;
State : in String) is
Box : Bbox.API.Client_Type;
begin
Box.Set_Server (To_String (Gateway.Ip));
if Ada.Strings.Unbounded.Length (Gateway.Passwd) > 0 then
Box.Login (To_String (Gateway.Passwd));
end if;
Box.Put ("wireless", (if State = "on" then "radio.enable=1" else "radio.enable=0"));
end Radio;
begin
Druss.Commands.Gateway_Command (Command, Args, 1, Radio'Access, Context);
end Set_Enable;
-- ------------------------------
-- 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
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
procedure Wifi_Status (Gateway : in out Druss.Gateways.Gateway_Type) is
begin
Gateway.Refresh;
Console.Start_Row;
Console.Print_Field (F_IP_ADDR, Gateway.Ip);
Print_On_Off (Console, F_BOOL, Gateway.Wifi.Get ("wireless.radio.24.enable", " "));
Console.Print_Field (F_CHANNEL, Gateway.Wifi.Get ("wireless.radio.24.current_channel", " "));
Console.Print_Field (F_SSID, Gateway.Wifi.Get ("wireless.ssid.24.id", " "));
Console.Print_Field (F_PROTOCOL, Gateway.Wifi.Get ("wireless.ssid.24.security.protocol", " "));
Console.Print_Field (F_ENCRYPTION, Gateway.Wifi.Get ("wireless.ssid.24.security.encryption", " "));
Console.Print_Field (F_DEVICES, Gateway.Hosts.Get ("hosts.list.length", ""));
Console.End_Row;
if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then
return;
end if;
Console.Start_Row;
Console.Print_Field (F_IP_ADDR, To_String (Gateway.Ip));
Print_On_Off (Console, F_BOOL, Gateway.Wifi.Get ("wireless.radio.5.enable", " "));
Console.Print_Field (F_CHANNEL, Gateway.Wifi.Get ("wireless.radio.5.current_channel", " "));
Console.Print_Field (F_SSID, Gateway.Wifi.Get ("wireless.ssid.5.id", " "));
Console.Print_Field (F_PROTOCOL, Gateway.Wifi.Get ("wireless.ssid.5.security.protocol", " "));
Console.Print_Field (F_ENCRYPTION, Gateway.Wifi.Get ("wireless.ssid.5.security.encryption", " "));
Console.End_Row;
end Wifi_Status;
begin
Console.Start_Title;
Console.Print_Title (F_IP_ADDR, "Bbox IP", 15);
Console.Print_Title (F_BOOL, "Enable", 8);
Console.Print_Title (F_CHANNEL, "Channel", 8);
Console.Print_Title (F_SSID, "SSID", 20);
Console.Print_Title (F_PROTOCOL, "Protocol", 12);
Console.Print_Title (F_ENCRYPTION, "Encryption", 12);
Console.Print_Title (F_DEVICES, "Devices", 12);
Console.End_Title;
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Wifi_Status'Access);
end Do_Status;
-- ------------------------------
-- Execute a command to control or get status about the Wifi.
-- ------------------------------
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
begin
if Args.Get_Count = 0 then
Command.Do_Status (Args, Context);
elsif Args.Get_Argument (1) = "on" then
Command.Set_Enable (Args, "on", Context);
elsif Args.Get_Argument (1) = "off" then
Command.Set_Enable (Args, "on", Context);
elsif Args.Get_Argument (1) = "status" then
Command.Do_Status (Args, Context);
else
Put_Line ("Invalid sub-command: " & Args.Get_Argument (1));
Druss.Commands.Driver.Usage (Args);
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is
begin
Put_Line ("wifi: Control and get status about the Bbox Wifi");
Put_Line ("Usage: wifi {<action>} [<parameters>]");
New_Line;
Put_Line (" wifi on [IP]... Turn ON the wifi on the Bbox.");
Put_Line (" wifi off [IP]... Turn OFF the wifi on the Bbox.");
Put_Line (" wifi show Show information about the wifi on the Bbox.");
Put_Line (" wifi devices Show the wifi devices which are connected.");
end Help;
end Druss.Commands.Wifi;
|
-----------------------------------------------------------------------
-- druss-commands-wifi -- Wifi related commands
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Bbox.API;
package body Druss.Commands.Wifi is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Enable or disable with wifi radio.
-- ------------------------------
procedure Do_Enable (Command : in Command_Type;
Args : in Argument_List'Class;
Context : in out Context_Type) is
procedure Radio (Gateway : in out Druss.Gateways.Gateway_Type;
State : in String);
procedure Radio (Gateway : in out Druss.Gateways.Gateway_Type;
State : in String) is
Box : Bbox.API.Client_Type;
begin
Box.Set_Server (To_String (Gateway.Ip));
if Ada.Strings.Unbounded.Length (Gateway.Passwd) > 0 then
Box.Login (To_String (Gateway.Passwd));
end if;
Box.Put ("wireless", (if State = "on" then "radio.enable=1" else "radio.enable=0"));
end Radio;
begin
Druss.Commands.Gateway_Command (Command, Args, 1, Radio'Access, Context);
end Do_Enable;
-- ------------------------------
-- 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 Wifi_Status (Gateway : in out Druss.Gateways.Gateway_Type);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
procedure Wifi_Status (Gateway : in out Druss.Gateways.Gateway_Type) is
begin
Gateway.Refresh;
Console.Start_Row;
Console.Print_Field (F_IP_ADDR, Gateway.Ip);
Print_On_Off (Console, F_BOOL, Gateway.Wifi.Get ("wireless.radio.24.enable", " "));
Console.Print_Field (F_CHANNEL, Gateway.Wifi.Get ("wireless.radio.24.current_channel", " "));
Console.Print_Field (F_SSID, Gateway.Wifi.Get ("wireless.ssid.24.id", " "));
Console.Print_Field (F_PROTOCOL, Gateway.Wifi.Get ("wireless.ssid.24.security.protocol", " "));
Console.Print_Field (F_ENCRYPTION, Gateway.Wifi.Get ("wireless.ssid.24.security.encryption", " "));
Console.Print_Field (F_DEVICES, Gateway.Hosts.Get ("hosts.list.length", ""));
Console.End_Row;
if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then
return;
end if;
Console.Start_Row;
Console.Print_Field (F_IP_ADDR, To_String (Gateway.Ip));
Print_On_Off (Console, F_BOOL, Gateway.Wifi.Get ("wireless.radio.5.enable", " "));
Console.Print_Field (F_CHANNEL, Gateway.Wifi.Get ("wireless.radio.5.current_channel", " "));
Console.Print_Field (F_SSID, Gateway.Wifi.Get ("wireless.ssid.5.id", " "));
Console.Print_Field (F_PROTOCOL, Gateway.Wifi.Get ("wireless.ssid.5.security.protocol", " "));
Console.Print_Field (F_ENCRYPTION, Gateway.Wifi.Get ("wireless.ssid.5.security.encryption", " "));
Console.End_Row;
end Wifi_Status;
begin
Console.Start_Title;
Console.Print_Title (F_IP_ADDR, "Bbox IP", 15);
Console.Print_Title (F_BOOL, "Enable", 8);
Console.Print_Title (F_CHANNEL, "Channel", 8);
Console.Print_Title (F_SSID, "SSID", 20);
Console.Print_Title (F_PROTOCOL, "Protocol", 12);
Console.Print_Title (F_ENCRYPTION, "Encryption", 12);
Console.Print_Title (F_DEVICES, "Devices", 12);
Console.End_Title;
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Wifi_Status'Access);
end Do_Status;
-- ------------------------------
-- Execute a command to control or get status about the Wifi.
-- ------------------------------
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
if Args.Get_Count = 0 then
Command.Do_Status (Args, Context);
elsif Args.Get_Argument (1) in "on" | "off" then
Command.Do_Enable (Args, Context);
elsif Args.Get_Argument (1) = "status" then
Command.Do_Status (Args, Context);
else
Context.Console.Notice (N_USAGE, "Invalid sub-command: " & Args.Get_Argument (1));
Druss.Commands.Driver.Usage (Args);
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP, "wifi: Control and get status about the Bbox Wifi");
Console.Notice (N_HELP, "Usage: wifi {<action>} [<parameters>]");
Console.Notice (N_HELP, "");
Console.Notice (N_HELP, " wifi on [IP]... Turn ON the wifi on the Bbox.");
Console.Notice (N_HELP, " wifi off [IP]... Turn OFF the wifi on the Bbox.");
Console.Notice (N_HELP, " wifi show Show information about the wifi on the Bbox.");
Console.Notice (N_HELP, " wifi devices Show the wifi devices which are connected.");
end Help;
end Druss.Commands.Wifi;
|
Rename Set_Enable and Do_Enable and fix compilation warnings
|
Rename Set_Enable and Do_Enable and fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
4c0dcd9665a78d76748565a0b87c493eb39ec320
|
src/os-linux/util-systems-os.ads
|
src/os-linux/util-systems-os.ads
|
-----------------------------------------------------------------------
-- util-system-os -- Unix system operations
-- Copyright (C) 2011, 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Processes;
with Util.Systems.Constants;
with Util.Systems.Types;
-- The <b>Util.Systems.Os</b> package defines various types and operations which are specific
-- to the OS (Unix).
package Util.Systems.Os is
-- The directory separator.
Directory_Separator : constant Character := '/';
subtype Ptr is Interfaces.C.Strings.chars_ptr;
subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array;
type Ptr_Ptr_Array is access all Ptr_Array;
type File_Type is new Integer;
-- Standard file streams Posix, X/Open standard values.
STDIN_FILENO : constant File_Type := 0;
STDOUT_FILENO : constant File_Type := 1;
STDERR_FILENO : constant File_Type := 2;
-- File is not opened
NO_FILE : constant File_Type := -1;
-- The following values should be externalized. They are valid for GNU/Linux.
F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL;
FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC;
-- These values are specific to Linux.
O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY;
O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY;
O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR;
O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT;
O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL;
O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC;
O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND;
type Size_T is mod 2 ** Standard'Address_Size;
type Ssize_T is range -(2 ** (Standard'Address_Size - 1))
.. +(2 ** (Standard'Address_Size - 1)) - 1;
function Close (Fd : in File_Type) return Integer;
pragma Import (C, Close, "close");
function Read (Fd : in File_Type;
Buf : in System.Address;
Size : in Size_T) return Ssize_T;
pragma Import (C, Read, "read");
function Write (Fd : in File_Type;
Buf : in System.Address;
Size : in Size_T) return Ssize_T;
pragma Import (C, Write, "write");
-- System exit without any process cleaning.
-- (destructors, finalizers, atexit are not called)
procedure Sys_Exit (Code : in Integer);
pragma Import (C, Sys_Exit, "_exit");
-- Fork a new process
function Sys_Fork return Util.Processes.Process_Identifier;
pragma Import (C, Sys_Fork, "fork");
-- Fork a new process (vfork implementation)
function Sys_VFork return Util.Processes.Process_Identifier;
pragma Import (C, Sys_VFork, "fork");
-- Execute a process with the given arguments.
function Sys_Execvp (File : in Ptr;
Args : in Ptr_Array) return Integer;
pragma Import (C, Sys_Execvp, "execvp");
-- Wait for the process <b>Pid</b> to finish and return
function Sys_Waitpid (Pid : in Integer;
Status : in System.Address;
Options : in Integer) return Integer;
pragma Import (C, Sys_Waitpid, "waitpid");
-- Create a bi-directional pipe
function Sys_Pipe (Fds : in System.Address) return Integer;
pragma Import (C, Sys_Pipe, "pipe");
-- Make <b>fd2</b> the copy of <b>fd1</b>
function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer;
pragma Import (C, Sys_Dup2, "dup2");
-- Close a file
function Sys_Close (Fd : in File_Type) return Integer;
pragma Import (C, Sys_Close, "close");
-- Open a file
function Sys_Open (Path : in Ptr;
Flags : in Interfaces.C.int;
Mode : in Interfaces.C.int) return File_Type;
pragma Import (C, Sys_Open, "open");
-- Change the file settings
function Sys_Fcntl (Fd : in File_Type;
Cmd : in Interfaces.C.int;
Flags : in Interfaces.C.int) return Integer;
pragma Import (C, Sys_Fcntl, "fcntl");
function Sys_Kill (Pid : in Integer;
Signal : in Integer) return Integer;
pragma Import (C, Sys_Kill, "kill");
function Sys_Stat (Path : in Ptr;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME);
function Sys_Fstat (Fs : in File_Type;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME);
end Util.Systems.Os;
|
-----------------------------------------------------------------------
-- util-system-os -- Unix system operations
-- Copyright (C) 2011, 2012, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Processes;
with Util.Systems.Constants;
with Util.Systems.Types;
-- The <b>Util.Systems.Os</b> package defines various types and operations which are specific
-- to the OS (Unix).
package Util.Systems.Os is
-- The directory separator.
Directory_Separator : constant Character := '/';
-- The path separator.
Path_Separator : constant Character := ':';
subtype Ptr is Interfaces.C.Strings.chars_ptr;
subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array;
type Ptr_Ptr_Array is access all Ptr_Array;
type File_Type is new Integer;
-- Standard file streams Posix, X/Open standard values.
STDIN_FILENO : constant File_Type := 0;
STDOUT_FILENO : constant File_Type := 1;
STDERR_FILENO : constant File_Type := 2;
-- File is not opened
NO_FILE : constant File_Type := -1;
-- The following values should be externalized. They are valid for GNU/Linux.
F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL;
FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC;
-- These values are specific to Linux.
O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY;
O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY;
O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR;
O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT;
O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL;
O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC;
O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND;
type Size_T is mod 2 ** Standard'Address_Size;
type Ssize_T is range -(2 ** (Standard'Address_Size - 1))
.. +(2 ** (Standard'Address_Size - 1)) - 1;
function Close (Fd : in File_Type) return Integer;
pragma Import (C, Close, "close");
function Read (Fd : in File_Type;
Buf : in System.Address;
Size : in Size_T) return Ssize_T;
pragma Import (C, Read, "read");
function Write (Fd : in File_Type;
Buf : in System.Address;
Size : in Size_T) return Ssize_T;
pragma Import (C, Write, "write");
-- System exit without any process cleaning.
-- (destructors, finalizers, atexit are not called)
procedure Sys_Exit (Code : in Integer);
pragma Import (C, Sys_Exit, "_exit");
-- Fork a new process
function Sys_Fork return Util.Processes.Process_Identifier;
pragma Import (C, Sys_Fork, "fork");
-- Fork a new process (vfork implementation)
function Sys_VFork return Util.Processes.Process_Identifier;
pragma Import (C, Sys_VFork, "fork");
-- Execute a process with the given arguments.
function Sys_Execvp (File : in Ptr;
Args : in Ptr_Array) return Integer;
pragma Import (C, Sys_Execvp, "execvp");
-- Wait for the process <b>Pid</b> to finish and return
function Sys_Waitpid (Pid : in Integer;
Status : in System.Address;
Options : in Integer) return Integer;
pragma Import (C, Sys_Waitpid, "waitpid");
-- Create a bi-directional pipe
function Sys_Pipe (Fds : in System.Address) return Integer;
pragma Import (C, Sys_Pipe, "pipe");
-- Make <b>fd2</b> the copy of <b>fd1</b>
function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer;
pragma Import (C, Sys_Dup2, "dup2");
-- Close a file
function Sys_Close (Fd : in File_Type) return Integer;
pragma Import (C, Sys_Close, "close");
-- Open a file
function Sys_Open (Path : in Ptr;
Flags : in Interfaces.C.int;
Mode : in Interfaces.C.int) return File_Type;
pragma Import (C, Sys_Open, "open");
-- Change the file settings
function Sys_Fcntl (Fd : in File_Type;
Cmd : in Interfaces.C.int;
Flags : in Interfaces.C.int) return Integer;
pragma Import (C, Sys_Fcntl, "fcntl");
function Sys_Kill (Pid : in Integer;
Signal : in Integer) return Integer;
pragma Import (C, Sys_Kill, "kill");
function Sys_Stat (Path : in Ptr;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME);
function Sys_Fstat (Fs : in File_Type;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME);
end Util.Systems.Os;
|
Declare Path_Separator constant
|
Declare Path_Separator constant
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
70bab2f2b1c25bd9fb6c8f3083c7f43cb5d49926
|
src/util-serialize-io-json.ads
|
src/util-serialize-io-json.ads
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- 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.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Util.Streams.Texts;
with Util.Stacks;
package Util.Serialize.IO.JSON is
-- ------------------------------
-- JSON Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a JSON output stream.
-- The stream object takes care of the JSON escape rules.
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private;
-- Set the target output stream.
procedure Initialize (Stream : in out Output_Stream;
Output : in Util.Streams.Texts.Print_Stream_Access);
-- Flush the buffer (if any) to the sink.
overriding
procedure Flush (Stream : in out Output_Stream);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Write a raw character on the stream.
procedure Write (Stream : in out Output_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Output_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Output_Stream;
Item : in String);
-- Start a JSON document. This operation writes the initial JSON marker ('{').
overriding
procedure Start_Document (Stream : in out Output_Stream);
-- Finish a JSON document by writing the final JSON marker ('}').
overriding
procedure End_Document (Stream : in out Output_Stream);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Start a new JSON object. If the name is not empty, write it as a string
-- followed by the ':' (colon). The JSON object starts with '{' (curly brace).
-- Example: "list": {
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current JSON object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a JSON name/value pair. The value is written according to its type
-- Example: "name": null
-- "name": false
-- "name": 12
-- "name": "value"
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Starts a JSON array.
-- Example: "list": [
overriding
procedure Start_Array (Stream : in out Output_Stream;
Name : in String);
-- Terminates a JSON array.
overriding
procedure End_Array (Stream : in out Output_Stream;
Name : in String);
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
private
type Node_Info is record
Is_Array : Boolean := False;
Has_Fields : Boolean := False;
end record;
type Node_Info_Access is access all Node_Info;
package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info,
Element_Type_Access => Node_Info_Access);
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record
Stack : Node_Info_Stack.Stack;
Stream : Util.Streams.Texts.Print_Stream_Access;
end record;
procedure Write_Field_Name (Stream : in out Output_Stream;
Name : in String);
type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET,
T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE,
T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL);
type Parser is new Util.Serialize.IO.Parser with record
Token : Ada.Strings.Unbounded.Unbounded_String;
Pending_Token : Token_Type := T_EOF;
Line_Number : Natural := 1;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
end record;
end Util.Serialize.IO.JSON;
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- 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.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Util.Streams.Texts;
with Util.Stacks;
package Util.Serialize.IO.JSON is
-- ------------------------------
-- JSON Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a JSON output stream.
-- The stream object takes care of the JSON escape rules.
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private;
-- Set the target output stream.
procedure Initialize (Stream : in out Output_Stream;
Output : in Util.Streams.Texts.Print_Stream_Access);
-- Flush the buffer (if any) to the sink.
overriding
procedure Flush (Stream : in out Output_Stream);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Write a raw character on the stream.
procedure Write (Stream : in out Output_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Output_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Output_Stream;
Item : in String);
-- Start a JSON document. This operation writes the initial JSON marker ('{').
overriding
procedure Start_Document (Stream : in out Output_Stream);
-- Finish a JSON document by writing the final JSON marker ('}').
overriding
procedure End_Document (Stream : in out Output_Stream);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Start a new JSON object. If the name is not empty, write it as a string
-- followed by the ':' (colon). The JSON object starts with '{' (curly brace).
-- Example: "list": {
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current JSON object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a JSON name/value pair. The value is written according to its type
-- Example: "name": null
-- "name": false
-- "name": 12
-- "name": "value"
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Starts a JSON array.
-- Example: "list": [
overriding
procedure Start_Array (Stream : in out Output_Stream;
Name : in String);
-- Terminates a JSON array.
overriding
procedure End_Array (Stream : in out Output_Stream;
Name : in String);
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
private
type Node_Info is record
Is_Array : Boolean := False;
Has_Fields : Boolean := False;
end record;
type Node_Info_Access is access all Node_Info;
package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info,
Element_Type_Access => Node_Info_Access);
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record
Stack : Node_Info_Stack.Stack;
Stream : Util.Streams.Texts.Print_Stream_Access;
end record;
procedure Write_Field_Name (Stream : in out Output_Stream;
Name : in String);
type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET,
T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE,
T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL);
type Parser is new Util.Serialize.IO.Parser with record
Token : Ada.Strings.Unbounded.Unbounded_String;
Pending_Token : Token_Type := T_EOF;
Line_Number : Natural := 1;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
end record;
end Util.Serialize.IO.JSON;
|
Add a Sink parameter to the Parse procedure
|
Add a Sink parameter to the Parse procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9872f1dff41509fde7e45a4116980fb167b4a431
|
mat/src/mat-expressions.ads
|
mat/src/mat-expressions.ads
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events.Targets;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE,
INSIDE_DIRECT_FILE,
INSIDE_FUNCTION,
INSIDE_DIRECT_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Create an event ID range expression node.
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME, N_EVENT,
N_CONDITION, N_THREAD);
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 N_EVENT =>
Min_Event : MAT.Events.Targets.Event_Id_Type;
Max_Event : MAT.Events.Targets.Event_Id_Type;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events.Targets;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE,
INSIDE_DIRECT_FILE,
INSIDE_FUNCTION,
INSIDE_DIRECT_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Create an event ID range expression node.
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME, N_EVENT,
N_CONDITION, N_THREAD);
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 N_EVENT =>
Min_Event : MAT.Events.Targets.Event_Id_Type;
Max_Event : MAT.Events.Targets.Event_Id_Type;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
d369cc8196663d3f33205177d18bacbd516722e2
|
regtests/ado-datasets-tests.ads
|
regtests/ado-datasets-tests.ads
|
-----------------------------------------------------------------------
-- ado-datasets-tests -- Test executing queries and using 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.Tests;
package ADO.Datasets.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_List (T : in out Test);
procedure Test_Count (T : in out Test);
procedure Test_Count_Query (T : in out Test);
end ADO.Datasets.Tests;
|
-----------------------------------------------------------------------
-- ado-datasets-tests -- Test executing queries and using datasets
-- Copyright (C) 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.Tests;
package ADO.Datasets.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_List (T : in out Test);
-- Test dataset lists with null columns.
procedure Test_List_Nullable (T : in out Test);
procedure Test_Count (T : in out Test);
procedure Test_Count_Query (T : in out Test);
end ADO.Datasets.Tests;
|
Declare the Test_List_Nullable procedure
|
Declare the Test_List_Nullable procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
4d6c80640f1b3c9cce932fb49c2c2127daadffe4
|
regtests/util-locales-tests.adb
|
regtests/util-locales-tests.adb
|
-----------------------------------------------------------------------
-- locales.tests -- Unit tests for locales
-- 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.Test_Caller;
package body Util.Locales.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Locales.Get_Locale",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Language",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Country",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Variant",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Hash",
Test_Hash_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.=",
Test_Compare_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Locales",
Test_Get_Locales'Access);
end Add_Tests;
procedure Test_Get_Locale (T : in out Test) is
Loc : Locale;
begin
Loc := Get_Locale ("en");
Assert_Equals (T, "en", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant");
Loc := Get_Locale ("ja", "JP", "JP");
Assert_Equals (T, "ja", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "JP", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "JP", Get_Variant (Loc), "Invalid variant");
Loc := Get_Locale ("no", "NO", "NY");
Assert_Equals (T, "no", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "NO", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "NY", Get_Variant (Loc), "Invalid variant");
end Test_Get_Locale;
procedure Test_Hash_Locale (T : in out Test) is
use type Ada.Containers.Hash_Type;
begin
T.Assert (Hash (FRANCE) /= Hash (FRENCH), "Hash should be different");
T.Assert (Hash (FRANCE) /= Hash (ENGLISH), "Hash should be different");
T.Assert (Hash (FRENCH) /= Hash (ENGLISH), "Hash should be different");
end Test_Hash_Locale;
procedure Test_Compare_Locale (T : in out Test) is
begin
T.Assert (FRANCE /= FRENCH, "Equality");
T.Assert (FRANCE = FRANCE, "Equality");
T.Assert (FRANCE = Get_Locale ("fr", "FR"), "Equality");
T.Assert (FRANCE /= ENGLISH, "Equality");
T.Assert (FRENCH /= ENGLISH, "Equaliy");
end Test_Compare_Locale;
procedure Test_Get_Locales (T : in out Test) is
begin
for I in Locales'Range loop
declare
Language : constant String := Get_Language (Locales (I));
Country : constant String := Get_Country (Locales (I));
Variant : constant String := Get_Variant (Locales (I));
Loc : constant Locale := Get_Locale (Language, Country, Variant);
Name : constant String := To_String (Loc);
begin
T.Assert (Loc = Locales (I), "Invalid locale at " & Positive'Image (I)
& " " & Loc.all);
if Variant'Length > 0 then
T.Assert (Name, Language & "_" & Country & "_" & Variant, "Invalid To_String");
elsif Country'Length > 0 then
T.Assert (Name, Language & "_" & Country, "Invalid To_String");
else
T.Assert (Name, Language, "Invalid To_String");
end if;
end;
end loop;
end Test_Get_Locales;
end Util.Locales.Tests;
|
-----------------------------------------------------------------------
-- locales.tests -- Unit tests for locales
-- 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.Test_Caller;
package body Util.Locales.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Locales.Get_Locale",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Language",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Country",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Get_Variant",
Test_Get_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Hash",
Test_Hash_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.=",
Test_Compare_Locale'Access);
Caller.Add_Test (Suite, "Test Util.Locales.Locales",
Test_Get_Locales'Access);
end Add_Tests;
procedure Test_Get_Locale (T : in out Test) is
Loc : Locale;
begin
Loc := Get_Locale ("en");
Assert_Equals (T, "en", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant");
Loc := Get_Locale ("ja", "JP", "JP");
Assert_Equals (T, "ja", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "JP", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "JP", Get_Variant (Loc), "Invalid variant");
Loc := Get_Locale ("no", "NO", "NY");
Assert_Equals (T, "no", Get_Language (Loc), "Invalid language");
Assert_Equals (T, "NO", Get_Country (Loc), "Invalid country");
Assert_Equals (T, "NY", Get_Variant (Loc), "Invalid variant");
end Test_Get_Locale;
procedure Test_Hash_Locale (T : in out Test) is
use type Ada.Containers.Hash_Type;
begin
T.Assert (Hash (FRANCE) /= Hash (FRENCH), "Hash should be different");
T.Assert (Hash (FRANCE) /= Hash (ENGLISH), "Hash should be different");
T.Assert (Hash (FRENCH) /= Hash (ENGLISH), "Hash should be different");
end Test_Hash_Locale;
procedure Test_Compare_Locale (T : in out Test) is
begin
T.Assert (FRANCE /= FRENCH, "Equality");
T.Assert (FRANCE = FRANCE, "Equality");
T.Assert (FRANCE = Get_Locale ("fr", "FR"), "Equality");
T.Assert (FRANCE /= ENGLISH, "Equality");
T.Assert (FRENCH /= ENGLISH, "Equaliy");
end Test_Compare_Locale;
procedure Test_Get_Locales (T : in out Test) is
begin
for I in Locales'Range loop
declare
Language : constant String := Get_Language (Locales (I));
Country : constant String := Get_Country (Locales (I));
Variant : constant String := Get_Variant (Locales (I));
Loc : constant Locale := Get_Locale (Language, Country, Variant);
Name : constant String := To_String (Loc);
begin
T.Assert (Loc = Locales (I), "Invalid locale at " & Positive'Image (I)
& " " & Loc.all);
if Variant'Length > 0 then
Assert (T, Name, Language & "_" & Country & "_" & Variant, "Invalid To_String");
elsif Country'Length > 0 then
Assert (T, Name, Language & "_" & Country, "Invalid To_String");
else
Assert (T, Name, Language, "Invalid To_String");
end if;
end;
end loop;
end Test_Get_Locales;
end Util.Locales.Tests;
|
Fix compilation issue with GNAT 2011
|
Fix compilation issue with GNAT 2011
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f20684fdbfa11d5433656607fdf093bda90ed461
|
regtests/wiki-writers-tests.adb
|
regtests/wiki-writers-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- 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.Text_IO;
with Ada.Directories;
with Ada.Characters.Conversions;
with Util.Files;
with Util.Measures;
with Wiki.Utils;
package body Wiki.Writers.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
function To_Wide (Item : in String) return Wide_Wide_String
renames Ada.Characters.Conversions.To_Wide_Wide_String;
Result_File : constant String := To_String (T.Result);
Content : Unbounded_String;
begin
Util.Files.Read_File (Path => To_String (T.File),
Into => Content,
Max_Size => 10000);
declare
Time : Util.Measures.Stamp;
begin
if T.Is_Html then
Content := To_Unbounded_String
(Utils.To_Html (To_Wide (To_String (Content)), T.Format));
else
Content := To_Unbounded_String
(Utils.To_Text (To_Wide (To_String (Content)), T.Format));
end if;
Util.Measures.Report (Time, "Render " & To_String (T.Name));
end;
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Render");
end Test_Render;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : in Test) return Util.Tests.Message_String is
begin
if T.Is_Html then
return Util.Tests.Format ("Test HTML " & To_String (T.Name));
else
return Util.Tests.Format ("Test TEXT " & To_String (T.Name));
end if;
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Render;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
function Create_Test (Name : in String; Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Dir : constant String := "regtests/files/wiki";
Expect_Dir : constant String := "regtests/expect";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String; Is_Html : in Boolean) return Test_Case_Access is
Ext : constant String := Ada.Directories.Extension (Name);
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path & "/" & Name);
if Is_Html then
Tst.Expect := To_Unbounded_String (Expect_Path & "/wiki-html/" & Name);
Tst.Result := To_Unbounded_String (Result_Path & "/wiki-html/" & Name);
else
Tst.Expect := To_Unbounded_String (Expect_Path & "/wiki-txt/" & Name);
Tst.Result := To_Unbounded_String (Result_Path & "/wiki-txt/" & Name);
end if;
if Ext = "wiki" then
Tst.Format := Wiki.Parsers.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Tst.Format := Wiki.Parsers.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Tst.Format := Wiki.Parsers.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Tst.Format := Wiki.Parsers.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Tst.Format := Wiki.Parsers.SYNTAX_MEDIA_WIKI;
else
Tst.Format := Wiki.Parsers.SYNTAX_MIX;
end if;
return Tst;
end Create_Test;
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
Tst := Create_Test (Simple, True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Tests;
end Wiki.Writers.Tests;
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- Copyright (C) 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Ada.Characters.Conversions;
with Util.Files;
with Util.Measures;
with Wiki.Render.Wiki;
with Wiki.Filters.Html;
with Wiki.Writers.Builders;
with Wiki.Utils;
package body Wiki.Writers.Tests is
use Ada.Strings.Unbounded;
use type Wiki.Parsers.Wiki_Syntax_Type;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
function To_Wide (Item : in String) return Wide_Wide_String
renames Ada.Characters.Conversions.To_Wide_Wide_String;
Result_File : constant String := To_String (T.Result);
Content : Unbounded_String;
begin
Util.Files.Read_File (Path => To_String (T.File),
Into => Content,
Max_Size => 10000);
declare
Time : Util.Measures.Stamp;
begin
if T.Source = Wiki.Parsers.SYNTAX_HTML then
declare
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type;
Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access, T.Format);
Html_Filter.Set_Document (Renderer'Unchecked_Access);
Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide (To_String (Content)),
Wiki.Parsers.SYNTAX_HTML);
Content := To_Unbounded_String (Writer.To_String);
end;
elsif T.Is_Html then
Content := To_Unbounded_String
(Utils.To_Html (To_Wide (To_String (Content)), T.Format));
else
Content := To_Unbounded_String
(Utils.To_Text (To_Wide (To_String (Content)), T.Format));
end if;
Util.Measures.Report (Time, "Render " & To_String (T.Name));
end;
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Render");
end Test_Render;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : in Test) return Util.Tests.Message_String is
begin
if T.Source = Wiki.Parsers.SYNTAX_HTML then
return Util.Tests.Format ("Test IMPORT " & To_String (T.Name));
elsif T.Is_Html then
return Util.Tests.Format ("Test HTML " & To_String (T.Name));
else
return Util.Tests.Format ("Test TEXT " & To_String (T.Name));
end if;
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Render;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Parsers.Wiki_Syntax_Type;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Expect_Dir : constant String := "regtests/expect";
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Parsers.Wiki_Syntax_Type;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access is
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path);
Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name);
Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name);
Tst.Format := Format;
Tst.Source := Format;
return Tst;
end Create_Test;
procedure Add_Wiki_Tests is
Dir : constant String := "regtests/files/wiki";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Ext : constant String := Ada.Directories.Extension (Simple);
Tst : Test_Case_Access;
Format : Wiki.Parsers.Wiki_Syntax_Type;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.Parsers.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.Parsers.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.Parsers.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.Parsers.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.Parsers.SYNTAX_MEDIA_WIKI;
else
Format := Wiki.Parsers.SYNTAX_MIX;
end if;
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Wiki_Tests;
procedure Add_Import_Tests is
Dir : constant String := "regtests/files/html";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
for Syntax in Wiki.Parsers.Wiki_Syntax_Type'Range loop
case Syntax is
when Wiki.Parsers.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.Parsers.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when others =>
Tst := null;
end case;
if Tst /= null then
Tst.Source := Wiki.Parsers.SYNTAX_HTML;
Suite.Add_Test (Tst.all'Access);
end if;
end loop;
end if;
end;
end loop;
end Add_Import_Tests;
begin
Add_Wiki_Tests;
Add_Import_Tests;
end Add_Tests;
end Wiki.Writers.Tests;
|
Add HTML import tests to verify the Wiki renderer
|
Add HTML import tests to verify the Wiki renderer
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
f36ecd6179261e5a458d651719bb55014708d8cd
|
regtests/security-policies-tests.adb
|
regtests/security-policies-tests.adb
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
with Security.Permissions.Tests;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
use Security.Permissions.Tests;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role ("admin");
T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was granted but user has no role");
User.Roles (Admin) := True;
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was not granted and user has admin role");
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
end;
declare
use Security.Permissions.Tests;
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/list.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin_Perm := R.Find_Role (Role);
declare
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URI=" & URI);
-- Set the role.
User.Roles (Admin_Perm) := True;
T.Assert (U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URI=" & URI);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
with Security.Permissions.Tests;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
use Security.Permissions.Tests;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role ("admin");
T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was granted but user has no role");
User.Roles (Admin) := True;
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was not granted and user has admin role");
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
end;
declare
use Security.Permissions.Tests;
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/list.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role (Role);
declare
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URI=" & URI);
-- Set the role.
User.Roles (Admin) := True;
T.Assert (U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URI=" & URI);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
Rename the role Admin_Perm into Admin
|
Rename the role Admin_Perm into Admin
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
0cd886d6ab60a4cf05f8409dbdc0582c927bf952
|
src/security-controllers-roles.adb
|
src/security-controllers-roles.adb
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Mappers.Record_Mapper;
package body Security.Controllers.Roles is
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
-- ------------------------------
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is
use type Security.Permissions.Principal_Access;
P : constant Security.Permissions.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
for I in Handler.Roles'Range loop
if P.Has_Role (Handler.Roles (I)) then
return True;
end if;
end loop;
end if;
return False;
end Has_Permission;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Permissions.Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Manager;
Config_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Controllers.Roles;
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Mappers.Record_Mapper;
package body Security.Controllers.Roles is
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
-- ------------------------------
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is
use type Security.Principal_Access;
P : constant Security.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
for I in Handler.Roles'Range loop
-- if P.Has_Role (Handler.Roles (I)) then
return True;
-- end if;
end loop;
end if;
return False;
end Has_Permission;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Permissions.Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Manager;
Config_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Controllers.Roles;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
d17889d422d9eba189e293ccb9fb1430382c834b
|
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;
-- The <b>ADO.Drivers</b> package represents the database driver that will create
-- database connections and provide the database specific implementation.
package ADO.Drivers is
use Ada.Strings.Unbounded;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- Raised for all errors reported by the database
DB_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;
end ADO.Drivers;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
-- == Introduction ==
-- 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");
--
-- === Connection string ===
-- The database connection string is an URI that specifies the database driver to use as well
-- as the information for the database driver to connect to the database.
-- The driver connection is a string of the form:
--
-- driver://[host][:port]/[database][?property1][=value1]...
--
-- The database connection string is passed to the session factory that maintains connections
-- to the database (see ADO.Sessions.Factory).
--
package ADO.Drivers is
use Ada.Strings.Unbounded;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- Raised for all errors reported by the database
DB_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;
end ADO.Drivers;
|
Add some documentation on database drivers
|
Add some documentation on database drivers
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
31e3c175e7a01dfbc1e27e58ba24d90301e3ed65
|
src/babel-files.ads
|
src/babel-files.ads
|
-----------------------------------------------------------------------
-- bkp-files -- File and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Encoders.SHA1;
with ADO;
package Babel.Files is
NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER;
subtype File_Identifier is ADO.Identifier;
subtype Directory_Identifier is ADO.Identifier;
subtype File_Size is Long_Long_Integer;
type File_Mode is mod 2**16;
type Uid_Type is mod 2**16;
type Gid_Type is mod 2**16;
type File_Type is private;
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
type Directory_Type is private;
type Directory_Type_Array is array (Positive range <>) of Directory_Type;
type Directory_Type_Array_Access is access all Directory_Type_Array;
NO_DIRECTORY : constant Directory_Type;
NO_FILE : constant File_Type;
type Status_Type is mod 2**16;
-- The file was modified.
FILE_MODIFIED : constant Status_Type := 16#0001#;
-- There was some error while processing this file.
FILE_ERROR : constant Status_Type := 16#8000#;
-- The SHA1 signature for the file is known and valid.
FILE_HAS_SHA1 : constant Status_Type := 16#0002#;
-- Allocate a File_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type;
-- Allocate a Directory_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type;
type File (Len : Positive) is record
Id : File_Identifier := NO_IDENTIFIER;
Size : File_Size := 0;
Dir : Directory_Type := NO_DIRECTORY;
Mode : File_Mode := 8#644#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Status : Status_Type := 0;
Date : Ada.Calendar.Time;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Name : aliased String (1 .. Len);
end record;
-- Return true if the file was modified and need a backup.
function Is_Modified (Element : in File_Type) return Boolean;
-- Set the file as modified.
procedure Set_Modified (Element : in File_Type);
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array);
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
procedure Set_Size (Element : in File_Type;
Size : in File_Size);
-- Return the path for the file.
function Get_Path (Element : in File_Type) return String;
-- Return the path for the directory.
function Get_Path (Element : in Directory_Type) return String;
-- Return the SHA1 signature computed for the file.
function Get_SHA1 (Element : in File_Type) return String;
type File_Container is limited interface;
-- Add the file with the given name in the container.
procedure Add_File (Into : in out File_Container;
Element : in File_Type) is abstract;
-- Add the directory with the given name in the container.
procedure Add_Directory (Into : in out File_Container;
Element : in Directory_Type) is abstract;
-- Create a new file instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return File_Type is abstract;
-- Create a new directory instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
function Find (From : in File_Container;
Name : in String) return File_Type is abstract;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
function Find (From : in File_Container;
Name : in String) return Directory_Type is abstract;
type Default_Container is new File_Container with private;
-- Add the file with the given name in the container.
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type);
-- Add the directory with the given name in the container.
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type);
-- Create a new file instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type;
-- Create a new directory instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type;
-- Set the directory object associated with the container.
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type);
private
type File_Type is access all File;
type Directory (Len : Positive) is record
Id : Directory_Identifier := NO_IDENTIFIER;
Parent : Directory_Type;
Mode : File_Mode := 8#755#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Files : File_Type_Array_Access;
Children : Directory_Type_Array_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Name : aliased String (1 .. Len);
end record;
type Directory_Type is access all Directory;
package File_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => File_Type,
"=" => "=");
package Directory_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Directory_Type,
"=" => "=");
subtype Directory_Vector is Directory_Vectors.Vector;
type Default_Container is new Babel.Files.File_Container with record
Current : Directory_Type;
Files : File_Vectors.Vector;
Dirs : Directory_Vectors.Vector;
end record;
NO_DIRECTORY : constant Directory_Type := null;
NO_FILE : constant File_Type := null;
end Babel.Files;
|
-----------------------------------------------------------------------
-- bkp-files -- File and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Encoders.SHA1;
with ADO;
package Babel.Files is
NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER;
subtype File_Identifier is ADO.Identifier;
subtype Directory_Identifier is ADO.Identifier;
subtype File_Size is Long_Long_Integer;
type File_Mode is mod 2**16;
type Uid_Type is mod 2**16;
type Gid_Type is mod 2**16;
type File_Type is private;
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
type Directory_Type is private;
type Directory_Type_Array is array (Positive range <>) of Directory_Type;
type Directory_Type_Array_Access is access all Directory_Type_Array;
NO_DIRECTORY : constant Directory_Type;
NO_FILE : constant File_Type;
type Status_Type is mod 2**16;
-- The file was modified.
FILE_MODIFIED : constant Status_Type := 16#0001#;
-- There was some error while processing this file.
FILE_ERROR : constant Status_Type := 16#8000#;
-- The SHA1 signature for the file is known and valid.
FILE_HAS_SHA1 : constant Status_Type := 16#0002#;
-- Allocate a File_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type;
-- Allocate a Directory_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type;
type File (Len : Positive) is record
Id : File_Identifier := NO_IDENTIFIER;
Size : File_Size := 0;
Dir : Directory_Type := NO_DIRECTORY;
Mode : File_Mode := 8#644#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Status : Status_Type := 0;
Date : Ada.Calendar.Time;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Name : aliased String (1 .. Len);
end record;
-- Return true if the file was modified and need a backup.
function Is_Modified (Element : in File_Type) return Boolean;
-- Set the file as modified.
procedure Set_Modified (Element : in File_Type);
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array);
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
procedure Set_Size (Element : in File_Type;
Size : in File_Size);
-- Return the path for the file.
function Get_Path (Element : in File_Type) return String;
-- Return the path for the directory.
function Get_Path (Element : in Directory_Type) return String;
-- Return the SHA1 signature computed for the file.
function Get_SHA1 (Element : in File_Type) return String;
type File_Container is limited interface;
-- Add the file with the given name in the container.
procedure Add_File (Into : in out File_Container;
Element : in File_Type) is abstract;
-- Add the directory with the given name in the container.
procedure Add_Directory (Into : in out File_Container;
Element : in Directory_Type) is abstract;
-- Create a new file instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return File_Type is abstract;
-- Create a new directory instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
function Find (From : in File_Container;
Name : in String) return File_Type is abstract;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
function Find (From : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Set the directory object associated with the container.
procedure Set_Directory (Into : in out File_Container;
Directory : in Directory_Type) is abstract;
type Default_Container is new File_Container with private;
-- Add the file with the given name in the container.
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type);
-- Add the directory with the given name in the container.
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type);
-- Create a new file instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type;
-- Create a new directory instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type;
-- Set the directory object associated with the container.
overriding
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type);
private
type File_Type is access all File;
type Directory (Len : Positive) is record
Id : Directory_Identifier := NO_IDENTIFIER;
Parent : Directory_Type;
Mode : File_Mode := 8#755#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Files : File_Type_Array_Access;
Children : Directory_Type_Array_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Name : aliased String (1 .. Len);
end record;
type Directory_Type is access all Directory;
package File_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => File_Type,
"=" => "=");
package Directory_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Directory_Type,
"=" => "=");
subtype Directory_Vector is Directory_Vectors.Vector;
type Default_Container is new Babel.Files.File_Container with record
Current : Directory_Type;
Files : File_Vectors.Vector;
Dirs : Directory_Vectors.Vector;
end record;
NO_DIRECTORY : constant Directory_Type := null;
NO_FILE : constant File_Type := null;
end Babel.Files;
|
Add the Set_Directory on the File_Container interface
|
Add the Set_Directory on the File_Container interface
|
Ada
|
apache-2.0
|
stcarrez/babel
|
5a135c7dd28308a2825f0de99729e8a700b2c07b
|
src/asf-servlets-faces-mappers.adb
|
src/asf-servlets-faces-mappers.adb
|
-----------------------------------------------------------------------
-- asf-servlets-faces-mappers -- Read faces specific configuration files
-- 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 ASF.Routes.Servlets.Faces;
package body ASF.Servlets.Faces.Mappers is
use type ASF.Routes.Route_Type_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access is
Disp : constant Request_Dispatcher := Container.Get_Request_Dispatcher (View);
Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route;
begin
if Route = null then
raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View;
end if;
if not (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class) then
raise Util.Serialize.Mappers.Field_Error with "View " & View & " not mapped to a servlet";
end if;
return ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet;
end Find_Servlet;
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the URL_MAPPING, URL_PATTERN, VIEW_ID field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Field is
when URL_PATTERN =>
N.URL_Pattern := Value;
when VIEW_ID =>
N.View_Id := Value;
when URL_MAPPING =>
declare
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
View : constant String := To_String (N.View_Id);
Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
To : ASF.Routes.Servlets.Faces.Faces_Route_Type_Access;
begin
if Route.Is_Null then
To := new ASF.Routes.Servlets.Faces.Faces_Route_Type;
To.View := To_Unbounded_String (View);
To.Servlet := Servlet;
Route := ASF.Routes.Route_Type_Refs.Create (To.all'Access);
end if;
end Insert;
begin
N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern),
ELContext => N.Context.all,
Process => Insert'Access);
end;
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("faces-config", SMapper'Access);
Reader.Add_Mapping ("module", SMapper'Access);
Reader.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("url-mapping", URL_MAPPING);
SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN);
SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID);
end ASF.Servlets.Faces.Mappers;
|
-----------------------------------------------------------------------
-- asf-servlets-faces-mappers -- Read faces specific configuration files
-- Copyright (C) 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 ASF.Routes.Servlets.Faces;
package body ASF.Servlets.Faces.Mappers is
use type ASF.Routes.Route_Type_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access is
Disp : constant Request_Dispatcher := Container.Get_Request_Dispatcher (View);
Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route;
begin
if Route = null then
raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View;
end if;
if not (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class) then
raise Util.Serialize.Mappers.Field_Error with "View " & View & " not mapped to a servlet";
end if;
return ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet;
end Find_Servlet;
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the URL_MAPPING, URL_PATTERN, VIEW_ID field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Field is
when URL_PATTERN =>
N.URL_Pattern := Value;
when VIEW_ID =>
N.View_Id := Value;
when URL_MAPPING =>
declare
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
View : constant String := To_String (N.View_Id);
Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
To : ASF.Routes.Servlets.Faces.Faces_Route_Type_Access;
begin
if Route.Is_Null then
To := new ASF.Routes.Servlets.Faces.Faces_Route_Type;
To.View := To_Unbounded_String (View);
To.Servlet := Servlet;
Route := ASF.Routes.Route_Type_Refs.Create (To.all'Access);
end if;
end Insert;
begin
N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern),
ELContext => N.Context.all,
Process => Insert'Access);
end;
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", SMapper'Access);
Mapper.Add_Mapping ("module", SMapper'Access);
Mapper.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("url-mapping", URL_MAPPING);
SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN);
SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID);
end ASF.Servlets.Faces.Mappers;
|
Update the Reader_Config to use the new parser/mapper interface
|
Update the Reader_Config to use the new parser/mapper interface
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
439a1ce5dc4bc017a64e527e05d33f61c9a42f95
|
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 := "15";
copyright_years : constant String := "2015-2018";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.28";
default_pgsql : constant String := "10";
default_php : constant String := "7.2";
default_python3 : constant String := "3.7";
default_ruby : constant String := "2.5";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc8";
compiler_version : constant String := "8.2.0";
previous_compiler : constant String := "7.3.0";
binutils_version : constant String := "2.31.1";
previous_binutils : constant String := "2.30";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
raven_var : constant String := "/var/ravenports";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "1";
raven_version_minor : constant String := "16";
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 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
raven_var : constant String := "/var/ravenports";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
Bump copyright years and version
|
Bump copyright years and version
The version bump is in anticipation of major updates.
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
95b8adc01003dc565d296eaf11dd04ae94e2559c
|
src/util-beans-objects-maps.adb
|
src/util-beans-objects-maps.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Maps -- Object maps
-- 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.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Maps is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Map_Bean;
Name : in String) return Object is
Pos : constant Cursor := From.Find (Name);
begin
if Has_Element (Pos) then
return Element (Pos);
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
procedure Set_Value (From : in out Map_Bean;
Name : in String;
Value : in Object) is
begin
From.Include (Name, Value);
end Set_Value;
-- ------------------------------
-- Create an object that contains a <tt>Map_Bean</tt> instance.
-- ------------------------------
function Create return Object is
M : constant access Map_Bean'Class := new Map_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
end Util.Beans.Objects.Maps;
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Maps -- Object maps
-- 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.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Maps is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Map_Bean;
Name : in String) return Object is
Pos : constant Cursor := From.Find (Name);
begin
if Has_Element (Pos) then
return Element (Pos);
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
procedure Set_Value (From : in out Map_Bean;
Name : in String;
Value : in Object) is
begin
From.Include (Name, Value);
end Set_Value;
-- ------------------------------
-- Iterate over the members of the map.
-- ------------------------------
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object)) is
procedure Process_One (Pos : in Maps.Cursor);
procedure Process_One (Pos : in Maps.Cursor) is
begin
Process (Maps.Key (Pos), Maps.Element (Pos));
end Process_One;
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From);
begin
if Bean /= null and then Bean.all in Util.Beans.Objects.Maps.Map_Bean'Class then
Map_Bean'Class (Bean.all).Iterate (Process_One'Access);
end if;
end Iterate;
-- ------------------------------
-- Create an object that contains a <tt>Map_Bean</tt> instance.
-- ------------------------------
function Create return Object is
M : constant access Map_Bean'Class := new Map_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
end Util.Beans.Objects.Maps;
|
Implement the Iterate procedure to call a Process procedure for each element of the object map
|
Implement the Iterate procedure to call a Process procedure for each element of the object map
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
87421374397e313e70bb80cdb4d60465e862c5fe
|
awa/src/awa-events-services.adb
|
awa/src/awa-events-services.adb
|
-----------------------------------------------------------------------
-- awa-events-services -- AWA Event Manager
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with ADO.SQL;
with ADO.Sessions;
with AWA.Events.Dispatchers.Tasks;
with AWA.Events.Dispatchers.Actions;
package body AWA.Events.Services is
use type Util.Strings.Name_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Events.Services");
-- ------------------------------
-- Send the event to the modules that subscribed to it.
-- The event is sent on each event queue. Event queues will dispatch the event
-- by invoking immediately or later on the <b>Dispatch</b> operation. The synchronous
-- or asynchronous reception of the event depends on the event queue.
-- ------------------------------
procedure Send (Manager : in Event_Manager;
Event : in Module_Event'Class) is
procedure Send_Queue (Queue : in Queue_Dispatcher);
procedure Send_Queue (Queue : in Queue_Dispatcher) is
begin
if Queue.Queue.Is_Null then
Queue.Dispatcher.Dispatch (Event);
else
Queue.Queue.Enqueue (Event);
end if;
end Send_Queue;
Name : constant Util.Strings.Name_Access := Get_Event_Type_Name (Event.Kind);
begin
if Name = null then
Log.Error ("Cannot send event type {0}", Event_Index'Image (Event.Kind));
raise Not_Found;
end if;
-- Find the event queues associated with the event. Post the event on each queue.
-- Some queue can dispatch the event immediately while some others may dispatched it
-- asynchronously.
declare
Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First;
begin
if not Queue_Dispatcher_Lists.Has_Element (Pos) then
Log.Debug ("Sending event {0} but there is no listener", Name.all);
else
Log.Debug ("Sending event {0}", Name.all);
loop
Queue_Dispatcher_Lists.Query_Element (Pos, Send_Queue'Access);
Queue_Dispatcher_Lists.Next (Pos);
exit when not Queue_Dispatcher_Lists.Has_Element (Pos);
end loop;
end if;
end;
end Send;
-- ------------------------------
-- Set the event message type which correspond to the <tt>Kind</tt> event index.
-- ------------------------------
procedure Set_Message_Type (Manager : in Event_Manager;
Event : in out AWA.Events.Models.Message_Ref;
Kind : in Event_Index) is
begin
if not Event_Arrays.Is_Valid (Kind) then
Log.Error ("Cannot send event type {0}", Event_Index'Image (Kind));
raise Not_Found;
end if;
Event.Set_Status (AWA.Events.Models.QUEUED);
Event.Set_Message_Type (Manager.Actions (Kind).Event);
end Set_Message_Type;
-- ------------------------------
-- Set the event queue associated with the event message. The event queue identified by
-- <tt>Name</tt> is searched to find the <tt>Queue_Ref</tt> instance.
-- ------------------------------
procedure Set_Event_Queue (Manager : in Event_Manager;
Event : in out AWA.Events.Models.Message_Ref;
Name : in String) is
Queue : constant AWA.Events.Queues.Queue_Ref := Manager.Find_Queue (Name);
begin
Event.Set_Queue (Queue.Get_Queue);
end Set_Event_Queue;
-- ------------------------------
-- Dispatch the event identified by <b>Event</b> and associated with the event
-- queue <b>Queue</b>. The event actions which are associated with the event are
-- executed synchronously.
-- ------------------------------
procedure Dispatch (Manager : in Event_Manager;
Queue : in AWA.Events.Queues.Queue_Ref;
Event : in Module_Event'Class) is
procedure Find_Queue (List : in Queue_Dispatcher);
Found : Boolean := False;
procedure Find_Queue (List : in Queue_Dispatcher) is
begin
if List.Queue = Queue then
List.Dispatcher.Dispatch (Event);
Found := True;
end if;
end Find_Queue;
Name : constant Util.Strings.Name_Access := Get_Event_Type_Name (Event.Kind);
begin
if Name = null then
Log.Error ("Cannot dispatch event type {0}", Event_Index'Image (Event.Kind));
raise Not_Found;
end if;
declare
Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First;
begin
if not Queue_Dispatcher_Lists.Has_Element (Pos) then
Log.Debug ("Dispatching event {0} but there is no listener", Name.all);
else
Log.Debug ("Dispatching event {0}", Name.all);
loop
Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access);
exit when Found;
Queue_Dispatcher_Lists.Next (Pos);
if not Queue_Dispatcher_Lists.Has_Element (Pos) then
Log.Debug ("Dispatched event {0} but there was no listener", Name.all);
exit;
end if;
end loop;
end if;
end;
end Dispatch;
-- ------------------------------
-- Find the event queue identified by the given name.
-- ------------------------------
function Find_Queue (Manager : in Event_Manager;
Name : in String) return AWA.Events.Queues.Queue_Ref is
Pos : constant Queues.Maps.Cursor := Manager.Queues.Find (Name);
begin
if Queues.Maps.Has_Element (Pos) then
return Queues.Maps.Element (Pos);
else
Log.Error ("Event queue {0} not found", Name);
return AWA.Events.Queues.Null_Queue;
end if;
end Find_Queue;
-- ------------------------------
-- Add the event queue in the registry.
-- ------------------------------
procedure Add_Queue (Manager : in out Event_Manager;
Queue : in AWA.Events.Queues.Queue_Ref) is
Name : constant String := Queue.Get_Name;
begin
if Manager.Queues.Contains (Name) then
Log.Error ("Event queue {0} already defined");
else
Log.Info ("Adding event queue {0}", Name);
end if;
Manager.Queues.Include (Key => Name,
New_Item => Queue);
end Add_Queue;
-- ------------------------------
-- Add an action invoked when the event identified by <b>Event</b> is sent.
-- The event is posted on the queue identified by <b>Queue</b>.
-- When the event queue dispatches the event, the Ada bean identified by the method action
-- represented by <b>Action</b> is created and initialized by evaluating and setting the
-- parameters defined in <b>Params</b>. The action method is then invoked.
-- ------------------------------
procedure Add_Action (Manager : in out Event_Manager;
Event : in String;
Queue : in AWA.Events.Queues.Queue_Ref;
Action : in EL.Expressions.Method_Expression;
Params : in EL.Beans.Param_Vectors.Vector) is
procedure Find_Queue (List : in Queue_Dispatcher);
procedure Add_Action (List : in out Queue_Dispatcher);
procedure Add_Action (List : in out Queue_Dispatcher) is
use type AWA.Events.Dispatchers.Dispatcher_Access;
begin
if List.Dispatcher = null then
List.Dispatcher := AWA.Events.Dispatchers.Actions.Create_Dispatcher
(Application => Manager.Application.all'Access);
end if;
List.Dispatcher.Add_Action (Action, Params);
end Add_Action;
Found : Boolean := False;
procedure Find_Queue (List : in Queue_Dispatcher) is
begin
Found := List.Queue = Queue;
end Find_Queue;
Index : constant Event_Index := Find_Event_Index (Event);
Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Index).Queues.First;
begin
Log.Info ("Adding action {0} to event {1}", Action.Get_Expression, Event);
-- Find the queue.
while Queue_Dispatcher_Lists.Has_Element (Pos) loop
Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access);
exit when Found;
Queue_Dispatcher_Lists.Next (Pos);
end loop;
-- Create it if it does not exist.
if not Found then
declare
New_Queue : Queue_Dispatcher;
begin
New_Queue.Queue := Queue;
Manager.Actions (Index).Queues.Append (New_Queue);
Pos := Manager.Actions (Index).Queues.Last;
end;
end if;
-- And append the new action to the event queue.
Manager.Actions (Index).Queues.Update_Element (Pos, Add_Action'Access);
end Add_Action;
-- ------------------------------
-- Add a dispatcher to process the event queues matching the <b>Match</b> string.
-- The dispatcher can create up to <b>Count</b> tasks running at the priority <b>Priority</b>.
-- ------------------------------
procedure Add_Dispatcher (Manager : in out Event_Manager;
Match : in String;
Count : in Positive;
Priority : in Positive) is
use type AWA.Events.Dispatchers.Dispatcher_Access;
begin
Log.Info ("Adding event dispatcher with {0} tasks prio {1} and dispatching queues '{2}'",
Positive'Image (Count), Positive'Image (Priority), Match);
for I in Manager.Dispatchers'Range loop
if Manager.Dispatchers (I) = null then
Manager.Dispatchers (I) :=
AWA.Events.Dispatchers.Tasks.Create_Dispatcher (Manager'Unchecked_Access,
Match, Count, Priority);
return;
end if;
end loop;
Log.Error ("Implementation limit is reached. Too many dispatcher.");
end Add_Dispatcher;
-- ------------------------------
-- Initialize the event manager.
-- ------------------------------
procedure Initialize (Manager : in out Event_Manager;
App : in Application_Access) is
procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref);
Msg_Types : AWA.Events.Models.Message_Type_Vector;
Query : ADO.SQL.Query;
procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref) is
Name : constant String := Msg.Get_Name;
begin
declare
Index : constant Event_Index := Find_Event_Index (Name);
begin
Manager.Actions (Index).Event := Msg;
end;
exception
when others =>
Log.Warn ("Event {0} is no longer used", Name);
end Set_Events;
DB : ADO.Sessions.Master_Session := App.Get_Master_Session;
begin
Log.Info ("Initializing {0} events", Event_Index'Image (Event_Arrays.Get_Last));
Manager.Application := App;
DB.Begin_Transaction;
Manager.Actions := new Event_Queues_Array (1 .. Event_Arrays.Get_Last);
AWA.Events.Models.List (Object => Msg_Types,
Session => DB,
Query => Query);
declare
Pos : AWA.Events.Models.Message_Type_Vectors.Cursor := Msg_Types.First;
begin
while AWA.Events.Models.Message_Type_Vectors.Has_Element (Pos) loop
AWA.Events.Models.Message_Type_Vectors.Query_Element (Pos, Set_Events'Access);
AWA.Events.Models.Message_Type_Vectors.Next (Pos);
end loop;
end;
for I in Manager.Actions'Range loop
if Manager.Actions (I).Event.Is_Null then
declare
Name : constant Util.Strings.Name_Access := Get_Event_Type_Name (I);
begin
Log.Info ("Creating event type {0} in database", Name.all);
Manager.Actions (I).Event.Set_Name (Name.all);
Manager.Actions (I).Event.Save (DB);
end;
end if;
end loop;
DB.Commit;
end Initialize;
-- ------------------------------
-- Start the event manager. The dispatchers are configured to dispatch the event queues
-- and tasks are started to process asynchronous events.
-- ------------------------------
procedure Start (Manager : in out Event_Manager) is
use type AWA.Events.Dispatchers.Dispatcher_Access;
-- Dispatch the event queues to the dispatcher according to the dispatcher configuration.
procedure Associate_Dispatcher (Key : in String;
Queue : in out AWA.Events.Queues.Queue_Ref);
-- ------------------------------
-- Dispatch the event queues to the dispatcher according to the dispatcher configuration.
-- ------------------------------
procedure Associate_Dispatcher (Key : in String;
Queue : in out AWA.Events.Queues.Queue_Ref) is
pragma Unreferenced (Key);
Added : Boolean := False;
begin
for I in reverse Manager.Dispatchers'Range loop
if Manager.Dispatchers (I) /= null then
Manager.Dispatchers (I).Add_Queue (Queue, Added);
exit when Added;
end if;
end loop;
end Associate_Dispatcher;
Iter : AWA.Events.Queues.Maps.Cursor := Manager.Queues.First;
begin
Log.Info ("Starting the event manager");
while AWA.Events.Queues.Maps.Has_Element (Iter) loop
Manager.Queues.Update_Element (Iter, Associate_Dispatcher'Access);
AWA.Events.Queues.Maps.Next (Iter);
end loop;
-- Start the dispatchers.
for I in Manager.Dispatchers'Range loop
exit when Manager.Dispatchers (I) = null;
Manager.Dispatchers (I).Start;
end loop;
end Start;
-- ------------------------------
-- Get the application associated with the event manager.
-- ------------------------------
function Get_Application (Manager : in Event_Manager) return Application_Access is
begin
return Manager.Application;
end Get_Application;
-- ------------------------------
-- Finalize the queue dispatcher releasing the dispatcher memory.
-- ------------------------------
procedure Finalize (Object : in out Queue_Dispatcher) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class,
Name => AWA.Events.Dispatchers.Dispatcher_Access);
begin
Free (Object.Dispatcher);
end Finalize;
-- ------------------------------
-- Finalize the event queues and the dispatchers.
-- ------------------------------
procedure Finalize (Object : in out Event_Queues) is
begin
loop
declare
Pos : constant Queue_Dispatcher_Lists.Cursor := Object.Queues.First;
begin
exit when not Queue_Dispatcher_Lists.Has_Element (Pos);
Object.Queues.Update_Element (Position => Pos,
Process => Finalize'Access);
Object.Queues.Delete_First;
end;
end loop;
end Finalize;
-- ------------------------------
-- Finalize the event manager by releasing the allocated storage.
-- ------------------------------
overriding
procedure Finalize (Manager : in out Event_Manager) is
use type AWA.Events.Dispatchers.Dispatcher_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Event_Queues_Array,
Name => Event_Queues_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class,
Name => AWA.Events.Dispatchers.Dispatcher_Access);
begin
-- Stop the dispatcher first.
for I in Manager.Dispatchers'Range loop
exit when Manager.Dispatchers (I) = null;
Free (Manager.Dispatchers (I));
end loop;
if Manager.Actions /= null then
for I in Manager.Actions'Range loop
Finalize (Manager.Actions (I));
end loop;
Free (Manager.Actions);
end if;
end Finalize;
end AWA.Events.Services;
|
-----------------------------------------------------------------------
-- awa-events-services -- AWA Event Manager
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with ADO.SQL;
with ADO.Sessions;
with AWA.Events.Dispatchers.Tasks;
with AWA.Events.Dispatchers.Actions;
package body AWA.Events.Services is
use type Util.Strings.Name_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Events.Services");
-- ------------------------------
-- Send the event to the modules that subscribed to it.
-- The event is sent on each event queue. Event queues will dispatch the event
-- by invoking immediately or later on the <b>Dispatch</b> operation. The synchronous
-- or asynchronous reception of the event depends on the event queue.
-- ------------------------------
procedure Send (Manager : in Event_Manager;
Event : in Module_Event'Class) is
procedure Send_Queue (Queue : in Queue_Dispatcher);
procedure Send_Queue (Queue : in Queue_Dispatcher) is
begin
if Queue.Queue.Is_Null then
Queue.Dispatcher.Dispatch (Event);
else
Queue.Queue.Enqueue (Event);
end if;
end Send_Queue;
Name : constant Name_Access := Get_Event_Type_Name (Event.Kind);
begin
if Name = null then
Log.Error ("Cannot send event type {0}", Event_Index'Image (Event.Kind));
raise Not_Found;
end if;
-- Find the event queues associated with the event. Post the event on each queue.
-- Some queue can dispatch the event immediately while some others may dispatched it
-- asynchronously.
declare
Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First;
begin
if not Queue_Dispatcher_Lists.Has_Element (Pos) then
Log.Debug ("Sending event {0} but there is no listener", Name.all);
else
Log.Debug ("Sending event {0}", Name.all);
loop
Queue_Dispatcher_Lists.Query_Element (Pos, Send_Queue'Access);
Queue_Dispatcher_Lists.Next (Pos);
exit when not Queue_Dispatcher_Lists.Has_Element (Pos);
end loop;
end if;
end;
end Send;
-- ------------------------------
-- Set the event message type which correspond to the <tt>Kind</tt> event index.
-- ------------------------------
procedure Set_Message_Type (Manager : in Event_Manager;
Event : in out AWA.Events.Models.Message_Ref;
Kind : in Event_Index) is
begin
if not Event_Arrays.Is_Valid (Kind) then
Log.Error ("Cannot send event type {0}", Event_Index'Image (Kind));
raise Not_Found;
end if;
Event.Set_Status (AWA.Events.Models.QUEUED);
Event.Set_Message_Type (Manager.Actions (Kind).Event);
end Set_Message_Type;
-- ------------------------------
-- Set the event queue associated with the event message. The event queue identified by
-- <tt>Name</tt> is searched to find the <tt>Queue_Ref</tt> instance.
-- ------------------------------
procedure Set_Event_Queue (Manager : in Event_Manager;
Event : in out AWA.Events.Models.Message_Ref;
Name : in String) is
Queue : constant AWA.Events.Queues.Queue_Ref := Manager.Find_Queue (Name);
begin
Event.Set_Queue (Queue.Get_Queue);
end Set_Event_Queue;
-- ------------------------------
-- Dispatch the event identified by <b>Event</b> and associated with the event
-- queue <b>Queue</b>. The event actions which are associated with the event are
-- executed synchronously.
-- ------------------------------
procedure Dispatch (Manager : in Event_Manager;
Queue : in AWA.Events.Queues.Queue_Ref;
Event : in Module_Event'Class) is
procedure Find_Queue (List : in Queue_Dispatcher);
Found : Boolean := False;
procedure Find_Queue (List : in Queue_Dispatcher) is
begin
if List.Queue = Queue then
List.Dispatcher.Dispatch (Event);
Found := True;
end if;
end Find_Queue;
Name : constant Name_Access := Get_Event_Type_Name (Event.Kind);
begin
if Name = null then
Log.Error ("Cannot dispatch event type {0}", Event_Index'Image (Event.Kind));
raise Not_Found;
end if;
declare
Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First;
begin
if not Queue_Dispatcher_Lists.Has_Element (Pos) then
Log.Debug ("Dispatching event {0} but there is no listener", Name.all);
else
Log.Debug ("Dispatching event {0}", Name.all);
loop
Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access);
exit when Found;
Queue_Dispatcher_Lists.Next (Pos);
if not Queue_Dispatcher_Lists.Has_Element (Pos) then
Log.Debug ("Dispatched event {0} but there was no listener", Name.all);
exit;
end if;
end loop;
end if;
end;
end Dispatch;
-- ------------------------------
-- Find the event queue identified by the given name.
-- ------------------------------
function Find_Queue (Manager : in Event_Manager;
Name : in String) return AWA.Events.Queues.Queue_Ref is
Pos : constant Queues.Maps.Cursor := Manager.Queues.Find (Name);
begin
if Queues.Maps.Has_Element (Pos) then
return Queues.Maps.Element (Pos);
else
Log.Error ("Event queue {0} not found", Name);
return AWA.Events.Queues.Null_Queue;
end if;
end Find_Queue;
-- ------------------------------
-- Add the event queue in the registry.
-- ------------------------------
procedure Add_Queue (Manager : in out Event_Manager;
Queue : in AWA.Events.Queues.Queue_Ref) is
Name : constant String := Queue.Get_Name;
begin
if Manager.Queues.Contains (Name) then
Log.Error ("Event queue {0} already defined");
else
Log.Info ("Adding event queue {0}", Name);
end if;
Manager.Queues.Include (Key => Name,
New_Item => Queue);
end Add_Queue;
-- ------------------------------
-- Add an action invoked when the event identified by <b>Event</b> is sent.
-- The event is posted on the queue identified by <b>Queue</b>.
-- When the event queue dispatches the event, the Ada bean identified by the method action
-- represented by <b>Action</b> is created and initialized by evaluating and setting the
-- parameters defined in <b>Params</b>. The action method is then invoked.
-- ------------------------------
procedure Add_Action (Manager : in out Event_Manager;
Event : in String;
Queue : in AWA.Events.Queues.Queue_Ref;
Action : in EL.Expressions.Method_Expression;
Params : in EL.Beans.Param_Vectors.Vector) is
procedure Find_Queue (List : in Queue_Dispatcher);
procedure Add_Action (List : in out Queue_Dispatcher);
procedure Add_Action (List : in out Queue_Dispatcher) is
use type AWA.Events.Dispatchers.Dispatcher_Access;
begin
if List.Dispatcher = null then
List.Dispatcher := AWA.Events.Dispatchers.Actions.Create_Dispatcher
(Application => Manager.Application.all'Access);
end if;
List.Dispatcher.Add_Action (Action, Params);
end Add_Action;
Found : Boolean := False;
procedure Find_Queue (List : in Queue_Dispatcher) is
begin
Found := List.Queue = Queue;
end Find_Queue;
Index : constant Event_Index := Find_Event_Index (Event);
Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Index).Queues.First;
begin
Log.Info ("Adding action {0} to event {1}", Action.Get_Expression, Event);
-- Find the queue.
while Queue_Dispatcher_Lists.Has_Element (Pos) loop
Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access);
exit when Found;
Queue_Dispatcher_Lists.Next (Pos);
end loop;
-- Create it if it does not exist.
if not Found then
declare
New_Queue : Queue_Dispatcher;
begin
New_Queue.Queue := Queue;
Manager.Actions (Index).Queues.Append (New_Queue);
Pos := Manager.Actions (Index).Queues.Last;
end;
end if;
-- And append the new action to the event queue.
Manager.Actions (Index).Queues.Update_Element (Pos, Add_Action'Access);
end Add_Action;
-- ------------------------------
-- Add a dispatcher to process the event queues matching the <b>Match</b> string.
-- The dispatcher can create up to <b>Count</b> tasks running at the priority <b>Priority</b>.
-- ------------------------------
procedure Add_Dispatcher (Manager : in out Event_Manager;
Match : in String;
Count : in Positive;
Priority : in Positive) is
use type AWA.Events.Dispatchers.Dispatcher_Access;
begin
Log.Info ("Adding event dispatcher with {0} tasks prio {1} and dispatching queues '{2}'",
Positive'Image (Count), Positive'Image (Priority), Match);
for I in Manager.Dispatchers'Range loop
if Manager.Dispatchers (I) = null then
Manager.Dispatchers (I) :=
AWA.Events.Dispatchers.Tasks.Create_Dispatcher (Manager'Unchecked_Access,
Match, Count, Priority);
return;
end if;
end loop;
Log.Error ("Implementation limit is reached. Too many dispatcher.");
end Add_Dispatcher;
-- ------------------------------
-- Initialize the event manager.
-- ------------------------------
procedure Initialize (Manager : in out Event_Manager;
App : in Application_Access) is
procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref);
Msg_Types : AWA.Events.Models.Message_Type_Vector;
Query : ADO.SQL.Query;
procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref) is
Name : constant String := Msg.Get_Name;
begin
declare
Index : constant Event_Index := Find_Event_Index (Name);
begin
Manager.Actions (Index).Event := Msg;
end;
exception
when others =>
Log.Warn ("Event {0} is no longer used", Name);
end Set_Events;
DB : ADO.Sessions.Master_Session := App.Get_Master_Session;
begin
Log.Info ("Initializing {0} events", Event_Index'Image (Event_Arrays.Get_Last));
Manager.Application := App;
DB.Begin_Transaction;
Manager.Actions := new Event_Queues_Array (1 .. Event_Arrays.Get_Last);
AWA.Events.Models.List (Object => Msg_Types,
Session => DB,
Query => Query);
declare
Pos : AWA.Events.Models.Message_Type_Vectors.Cursor := Msg_Types.First;
begin
while AWA.Events.Models.Message_Type_Vectors.Has_Element (Pos) loop
AWA.Events.Models.Message_Type_Vectors.Query_Element (Pos, Set_Events'Access);
AWA.Events.Models.Message_Type_Vectors.Next (Pos);
end loop;
end;
for I in Manager.Actions'Range loop
if Manager.Actions (I).Event.Is_Null then
declare
Name : constant Name_Access := Get_Event_Type_Name (I);
begin
Log.Info ("Creating event type {0} in database", Name.all);
Manager.Actions (I).Event.Set_Name (Name.all);
Manager.Actions (I).Event.Save (DB);
end;
end if;
end loop;
DB.Commit;
end Initialize;
-- ------------------------------
-- Start the event manager. The dispatchers are configured to dispatch the event queues
-- and tasks are started to process asynchronous events.
-- ------------------------------
procedure Start (Manager : in out Event_Manager) is
use type AWA.Events.Dispatchers.Dispatcher_Access;
-- Dispatch the event queues to the dispatcher according to the dispatcher configuration.
procedure Associate_Dispatcher (Key : in String;
Queue : in out AWA.Events.Queues.Queue_Ref);
-- ------------------------------
-- Dispatch the event queues to the dispatcher according to the dispatcher configuration.
-- ------------------------------
procedure Associate_Dispatcher (Key : in String;
Queue : in out AWA.Events.Queues.Queue_Ref) is
pragma Unreferenced (Key);
Added : Boolean := False;
begin
for I in reverse Manager.Dispatchers'Range loop
if Manager.Dispatchers (I) /= null then
Manager.Dispatchers (I).Add_Queue (Queue, Added);
exit when Added;
end if;
end loop;
end Associate_Dispatcher;
Iter : AWA.Events.Queues.Maps.Cursor := Manager.Queues.First;
begin
Log.Info ("Starting the event manager");
while AWA.Events.Queues.Maps.Has_Element (Iter) loop
Manager.Queues.Update_Element (Iter, Associate_Dispatcher'Access);
AWA.Events.Queues.Maps.Next (Iter);
end loop;
-- Start the dispatchers.
for I in Manager.Dispatchers'Range loop
exit when Manager.Dispatchers (I) = null;
Manager.Dispatchers (I).Start;
end loop;
end Start;
-- ------------------------------
-- Get the application associated with the event manager.
-- ------------------------------
function Get_Application (Manager : in Event_Manager) return Application_Access is
begin
return Manager.Application;
end Get_Application;
-- ------------------------------
-- Finalize the queue dispatcher releasing the dispatcher memory.
-- ------------------------------
procedure Finalize (Object : in out Queue_Dispatcher) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class,
Name => AWA.Events.Dispatchers.Dispatcher_Access);
begin
Free (Object.Dispatcher);
end Finalize;
-- ------------------------------
-- Finalize the event queues and the dispatchers.
-- ------------------------------
procedure Finalize (Object : in out Event_Queues) is
begin
loop
declare
Pos : constant Queue_Dispatcher_Lists.Cursor := Object.Queues.First;
begin
exit when not Queue_Dispatcher_Lists.Has_Element (Pos);
Object.Queues.Update_Element (Position => Pos,
Process => Finalize'Access);
Object.Queues.Delete_First;
end;
end loop;
end Finalize;
-- ------------------------------
-- Finalize the event manager by releasing the allocated storage.
-- ------------------------------
overriding
procedure Finalize (Manager : in out Event_Manager) is
use type AWA.Events.Dispatchers.Dispatcher_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Event_Queues_Array,
Name => Event_Queues_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class,
Name => AWA.Events.Dispatchers.Dispatcher_Access);
begin
-- Stop the dispatcher first.
for I in Manager.Dispatchers'Range loop
exit when Manager.Dispatchers (I) = null;
Free (Manager.Dispatchers (I));
end loop;
if Manager.Actions /= null then
for I in Manager.Actions'Range loop
Finalize (Manager.Actions (I));
end loop;
Free (Manager.Actions);
end if;
end Finalize;
end AWA.Events.Services;
|
Use the event Name_Access type
|
Use the event Name_Access type
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
2c3149d0b4da4989d8b1be1c7bc616fb0b4193cc
|
awa/src/awa-helpers-selectors.adb
|
awa/src/awa-helpers-selectors.adb
|
-----------------------------------------------------------------------
-- awa-helpers -- Helpers for AWA applications
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries.Loaders;
with AWA.Services.Contexts;
package body AWA.Helpers.Selectors is
-- ------------------------------
-- Create a selector list from the definition of a discrete type such as an enum.
-- The select item has the enum value as value and the label is created by
-- localizing the string <b>Prefix</b>_<i>enum name</i>.
-- ------------------------------
function Create_From_Enum (Bundle : in Util.Properties.Bundles.Manager'Class)
return ASF.Models.Selects.Select_Item_List is
Result : ASF.Models.Selects.Select_Item_List;
begin
for I in T'Range loop
declare
Value : constant String := T'Image (I);
Name : constant String := Prefix & "_" & Value;
Label : constant String := Bundle.Get (Name, Name);
begin
Result.Append (ASF.Models.Selects.Create_Select_Item (Label, Value));
end;
end loop;
return Result;
end Create_From_Enum;
-- ------------------------------
-- Append the selector list from the SQL query. The query will be executed.
-- It should return rows with at least two columns. The first column is the
-- selector value and the second column is the selector label.
-- ------------------------------
procedure Append_From_Query (Into : in out ASF.Models.Selects.Select_Item_List;
Query : in out ADO.Statements.Query_Statement'Class) is
begin
Query.Execute;
while Query.Has_Elements loop
declare
Id : constant String := Query.Get_String (1);
Label : constant String := Query.Get_String (2);
begin
Into.Append (ASF.Models.Selects.Create_Select_Item (Id, Label));
end;
Query.Next;
end loop;
end Append_From_Query;
-- ------------------------------
-- Create the selector list from the SQL query. The query will be executed.
-- It should return rows with at least two columns. The first column is the
-- selector value and the second column is the selector label.
-- ------------------------------
function Create_From_Query (Session : in ADO.Sessions.Session'Class;
Query : in ADO.Queries.Context'Class)
return ASF.Models.Selects.Select_Item_List is
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Result : ASF.Models.Selects.Select_Item_List;
begin
Append_From_Query (Result, Stmt);
return Result;
end Create_From_Query;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Select_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "list" then
return ASF.Models.Selects.To_Object (From.List);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
procedure Set_Value (From : in out Select_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use type AWA.Services.Contexts.Service_Context_Access;
use type ADO.Queries.Query_Definition_Access;
begin
if Name = "query" then
declare
Query_Name : constant String := Util.Beans.Objects.To_String (Value);
Ctx : constant AWA.Services.Contexts.Service_Context_Access
:= AWA.Services.Contexts.Current;
Query_Def : constant ADO.Queries.Query_Definition_Access
:= ADO.Queries.Loaders.Find_Query (Query_Name);
Query : ADO.Queries.Context;
begin
if Ctx = null or Query_Def = null then
return;
end if;
Query.Set_Query (Query_Def);
From.List := Create_From_Query (Session => AWA.Services.Contexts.Get_Session (Ctx),
Query => Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the select list bean instance.
-- ------------------------------
function Create_Select_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Select_List_Bean_Access := new Select_List_Bean;
begin
return Result.all'Access;
end Create_Select_List_Bean;
end AWA.Helpers.Selectors;
|
-----------------------------------------------------------------------
-- awa-helpers -- Helpers for AWA applications
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries.Loaders;
with ADO.Schemas;
with Util.Strings;
with Util.Log.Loggers;
with AWA.Services.Contexts;
package body AWA.Helpers.Selectors is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Helpers.Selectors");
-- ------------------------------
-- Create a selector list from the definition of a discrete type such as an enum.
-- The select item has the enum value as value and the label is created by
-- localizing the string <b>Prefix</b>_<i>enum name</i>.
-- ------------------------------
function Create_From_Enum (Bundle : in Util.Properties.Bundles.Manager'Class)
return ASF.Models.Selects.Select_Item_List is
Result : ASF.Models.Selects.Select_Item_List;
begin
for I in T'Range loop
declare
Value : constant String := T'Image (I);
Name : constant String := Prefix & "_" & Value;
Label : constant String := Bundle.Get (Name, Name);
begin
Result.Append (ASF.Models.Selects.Create_Select_Item (Label, Value));
end;
end loop;
return Result;
end Create_From_Enum;
-- ------------------------------
-- Append the selector list from the SQL query. The query will be executed.
-- It should return rows with at least two columns. The first column is the
-- selector value and the second column is the selector label.
-- ------------------------------
procedure Append_From_Query (Into : in out ASF.Models.Selects.Select_Item_List;
Query : in out ADO.Statements.Query_Statement'Class) is
use ADO.Schemas;
Id_Type : ADO.Schemas.Column_Type := T_UNKNOWN;
Label_Type : ADO.Schemas.Column_Type := T_UNKNOWN;
function Get_Column (Id : in Natural;
Of_Type : in ADO.Schemas.Column_Type) return String is
begin
case Of_Type is
when T_CHAR | T_VARCHAR =>
return Query.Get_String (Id);
when T_INTEGER | T_TINYINT | T_SMALLINT | T_ENUM =>
return Util.Strings.Image (Query.Get_Integer (Id));
when T_LONG_INTEGER =>
return Util.Strings.Image (Long_Long_Integer (Query.Get_Int64 (Id)));
when others =>
return "";
end case;
end Get_Column;
begin
Query.Execute;
while Query.Has_Elements loop
if Id_Type = T_UNKNOWN then
Id_Type := Query.Get_Column_Type (0);
Label_Type := Query.Get_Column_Type (1);
end if;
declare
Id : constant String := Get_Column (0, Id_Type);
Label : constant String := Get_Column (1, Label_Type);
begin
Into.Append (ASF.Models.Selects.Create_Select_Item (Label => Label, Value => Id));
end;
Query.Next;
end loop;
end Append_From_Query;
-- ------------------------------
-- Create the selector list from the SQL query. The query will be executed.
-- It should return rows with at least two columns. The first column is the
-- selector value and the second column is the selector label.
-- ------------------------------
function Create_From_Query (Session : in ADO.Sessions.Session'Class;
Query : in ADO.Queries.Context'Class)
return ASF.Models.Selects.Select_Item_List is
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Result : ASF.Models.Selects.Select_Item_List;
begin
Append_From_Query (Result, Stmt);
return Result;
end Create_From_Query;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Select_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "list" then
return ASF.Models.Selects.To_Object (From.List);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
procedure Set_Value (From : in out Select_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use type AWA.Services.Contexts.Service_Context_Access;
use type ADO.Queries.Query_Definition_Access;
begin
if Name = "query" then
declare
Query_Name : constant String := Util.Beans.Objects.To_String (Value);
Ctx : constant AWA.Services.Contexts.Service_Context_Access
:= AWA.Services.Contexts.Current;
Query_Def : constant ADO.Queries.Query_Definition_Access
:= ADO.Queries.Loaders.Find_Query (Query_Name);
Query : ADO.Queries.Context;
begin
if Ctx = null or Query_Def = null then
return;
end if;
Query.Set_Query (Query_Def);
From.List := Create_From_Query (Session => AWA.Services.Contexts.Get_Session (Ctx),
Query => Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the select list bean instance.
-- ------------------------------
function Create_Select_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Select_List_Bean_Access := new Select_List_Bean;
begin
return Result.all'Access;
end Create_Select_List_Bean;
end AWA.Helpers.Selectors;
|
Use the column type to decide which column fetch operation must be used
|
Use the column type to decide which column fetch operation must be used
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3d5120b316dc2d2f32cf73b597cd4ff4a48226ae
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- 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 AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Wikis.Parsers.Tests;
with AWA.Wikis.Writers.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Wikis.Writers.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Application.Start;
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 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 AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Wikis.Parsers.Tests;
with AWA.Wikis.Writers.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Wikis.Writers.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Application.Start;
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
Add the comments module unit tests
|
Add the comments module unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a4edeeee734bbc33e57ac67e65d49d2f87c67cd8
|
mat/src/memory/mat-memory-readers.ads
|
mat/src/memory/mat-memory-readers.ads
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with MAT.Events;
-- with MAT.Ipc;
with Util.Events;
with MAT.Readers;
with MAT.Memory.Targets;
-- with MAT.Memory.Clients;
-- with MAT.Ipc.Clients;
-- with MAT.Events; use MAT.Events;
package MAT.Memory.Readers is
type Memory_Servant is new MAT.Readers.Reader_Base with record
Data : MAT.Memory.Targets.Client_Memory;
-- Slots : Client_Memory_Ref;
-- Impl : Client_Memory_Ref;
end record;
-- The memory servant is a proxy for the generic communication
-- channel to process incomming events (such as memory allocations).
overriding
procedure Dispatch (For_Servant : in out Memory_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message);
procedure Bind (For_Servant : in out Memory_Servant);
-- Bind the servant with the object adapter to register the
-- events it recognizes.
end MAT.Memory.Readers;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with MAT.Events;
-- with MAT.Ipc;
with Util.Events;
with MAT.Readers;
with MAT.Memory.Targets;
-- with MAT.Memory.Clients;
-- with MAT.Ipc.Clients;
-- with MAT.Events; use MAT.Events;
package MAT.Memory.Readers is
type Memory_Servant is new MAT.Readers.Reader_Base with record
Data : MAT.Memory.Targets.Client_Memory;
-- Slots : Client_Memory_Ref;
-- Impl : Client_Memory_Ref;
end record;
type Memory_Reader_Access is access all Memory_Servant'Class;
-- The memory servant is a proxy for the generic communication
-- channel to process incomming events (such as memory allocations).
overriding
procedure Dispatch (For_Servant : in out Memory_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message);
-- Register the reader to extract and analyze memory events.
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Memory_Reader_Access);
end MAT.Memory.Readers;
|
Remove the Bind procedure and define a Register procedure
|
Remove the Bind procedure and define a Register procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
672e405a51bda710a71dc1d4cb7d86f96540f32f
|
mat/src/memory/mat-memory-targets.adb
|
mat/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Probes;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access
:= new MAT.Memory.Probes.Memory_Probe_Type;
begin
-- Memory.Manager := Memory_Probe.all'Access;
Memory_Probe.Data := Memory'Unrestricted_Access;
MAT.Memory.Probes.Register (Manager, Memory_Probe);
end Initialize;
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info) is
begin
Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-"
& MAT.Types.Hex_Image (Region.End_Addr) & "] - {0}", Region.Path);
Memory.Memory.Add_Region (Region);
end Add_Region;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map) is
begin
Memory.Memory.Thread_Information (Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
Memory.Memory.Frame_Information (Level, Frames);
end Frame_Information;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat) is
begin
Memory.Memory.Stat_Information (Result);
end Stat_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Filter, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Region : in Region_Info) is
begin
Regions.Insert (Region.Start_Addr, Region);
end Add_Region;
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end if;
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation);
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
pragma Unreferenced (Key);
begin
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
Pos : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end if;
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
MAT.Memory.Tools.Size_Information (Used_Slots, Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Threads : in out Memory_Info_Map) is
begin
MAT.Memory.Tools.Thread_Information (Used_Slots, Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into);
end Find;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Result : out Memory_Stat) is
begin
Result := Stats;
end Stat_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Probes;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access
:= new MAT.Memory.Probes.Memory_Probe_Type;
begin
-- Memory.Manager := Memory_Probe.all'Access;
Memory_Probe.Data := Memory'Unrestricted_Access;
MAT.Memory.Probes.Register (Manager, Memory_Probe);
end Initialize;
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info) is
begin
Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-"
& MAT.Types.Hex_Image (Region.End_Addr) & "] - {0}", Region.Path);
Memory.Memory.Add_Region (Region);
end Add_Region;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map) is
begin
Memory.Memory.Thread_Information (Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
Memory.Memory.Frame_Information (Level, Frames);
end Frame_Information;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat) is
begin
Memory.Memory.Stat_Information (Result);
end Stat_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Filter, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Region : in Region_Info) is
begin
Regions.Insert (Region.Start_Addr, Region);
end Add_Region;
-- ------------------------------
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map) is
Iter : Region_Info_Cursor;
begin
Iter := Regions.Floor (From);
while Region_Info_Maps.Has_Element (Iter) loop
declare
Start : constant MAT.Types.Target_Addr := Region_Info_Maps.Key (Iter);
Region : Region_Info;
begin
exit when Start > To;
Region := Region_Info_Maps.Element (Iter);
if Region.End_Addr >= From then
if not Into.Contains (Start) then
Into.Insert (Start, Region);
end if;
end if;
Region_Info_Maps.Next (Iter);
end;
end loop;
end Find;
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end if;
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation);
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
pragma Unreferenced (Key);
begin
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
Pos : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end if;
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
MAT.Memory.Tools.Size_Information (Used_Slots, Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Threads : in out Memory_Info_Map) is
begin
MAT.Memory.Tools.Thread_Information (Used_Slots, Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into);
end Find;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Result : out Memory_Stat) is
begin
Result := Stats;
end Stat_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
Implement the Find protected procedure to find the memory region that intersect a given segment
|
Implement the Find protected procedure to find the memory region that intersect a given segment
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ed0a5bcb470acad2b6cca41659146530a731c47d
|
awa/plugins/awa-storages/src/awa-storages-modules.adb
|
awa/plugins/awa-storages/src/awa-storages-modules.adb
|
-----------------------------------------------------------------------
-- awa-storages-module -- Storage management module
-- Copyright (C) 2012, 2016, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Applications;
with AWA.Storages.Beans.Factories;
package body AWA.Storages.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Module");
package Register is new AWA.Modules.Beans (Module => Storage_Module,
Module_Access => Storage_Module_Access);
-- ------------------------------
-- Initialize the storage module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Storage_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the storage module");
-- Setup the resource bundles.
App.Register ("storageMsg", "storages");
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Upload_Bean",
Handler => AWA.Storages.Beans.Create_Upload_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Folder_Bean",
Handler => AWA.Storages.Beans.Factories.Create_Folder_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Folder_List_Bean",
Handler => AWA.Storages.Beans.Create_Folder_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Storage_List_Bean",
Handler => AWA.Storages.Beans.Create_Storage_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Storage_Bean",
Handler => AWA.Storages.Beans.Create_Storage_Bean'Access);
App.Add_Servlet ("storage", Plugin.Storage_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Storage_Module;
Props : in ASF.Applications.Config) is
begin
-- Create the storage manager when everything is initialized.
Plugin.Manager := Plugin.Create_Storage_Manager;
end Configure;
-- ------------------------------
-- Get the storage manager.
-- ------------------------------
function Get_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access is
begin
return Plugin.Manager;
end Get_Storage_Manager;
-- ------------------------------
-- Create a storage manager. This operation can be overriden to provide another
-- storage service implementation.
-- ------------------------------
function Create_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access is
Result : constant Services.Storage_Service_Access := new Services.Storage_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_Storage_Manager;
-- ------------------------------
-- Get the storage module instance associated with the current application.
-- ------------------------------
function Get_Storage_Module return Storage_Module_Access is
function Get is new AWA.Modules.Get (Storage_Module, Storage_Module_Access, NAME);
begin
return Get;
end Get_Storage_Module;
-- ------------------------------
-- Get the storage manager instance associated with the current application.
-- ------------------------------
function Get_Storage_Manager return Services.Storage_Service_Access is
Module : constant Storage_Module_Access := Get_Storage_Module;
begin
if Module = null then
Log.Error ("There is no active Storage_Module");
return null;
else
return Module.Get_Storage_Manager;
end if;
end Get_Storage_Manager;
end AWA.Storages.Modules;
|
-----------------------------------------------------------------------
-- awa-storages-module -- Storage management module
-- Copyright (C) 2012, 2016, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Applications;
with AWA.Storages.Beans;
package body AWA.Storages.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Module");
package Register is new AWA.Modules.Beans (Module => Storage_Module,
Module_Access => Storage_Module_Access);
-- ------------------------------
-- Initialize the storage module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Storage_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the storage module");
-- Setup the resource bundles.
App.Register ("storageMsg", "storages");
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Upload_Bean",
Handler => AWA.Storages.Beans.Create_Upload_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Folder_Bean",
Handler => AWA.Storages.Beans.Create_Folder_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Folder_List_Bean",
Handler => AWA.Storages.Beans.Create_Folder_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Storage_List_Bean",
Handler => AWA.Storages.Beans.Create_Storage_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Storage_Bean",
Handler => AWA.Storages.Beans.Create_Storage_Bean'Access);
App.Add_Servlet ("storage", Plugin.Storage_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Storage_Module;
Props : in ASF.Applications.Config) is
begin
-- Create the storage manager when everything is initialized.
Plugin.Manager := Plugin.Create_Storage_Manager;
end Configure;
-- ------------------------------
-- Get the storage manager.
-- ------------------------------
function Get_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access is
begin
return Plugin.Manager;
end Get_Storage_Manager;
-- ------------------------------
-- Create a storage manager. This operation can be overriden to provide another
-- storage service implementation.
-- ------------------------------
function Create_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access is
Result : constant Services.Storage_Service_Access := new Services.Storage_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_Storage_Manager;
-- ------------------------------
-- Get the storage module instance associated with the current application.
-- ------------------------------
function Get_Storage_Module return Storage_Module_Access is
function Get is new AWA.Modules.Get (Storage_Module, Storage_Module_Access, NAME);
begin
return Get;
end Get_Storage_Module;
-- ------------------------------
-- Get the storage manager instance associated with the current application.
-- ------------------------------
function Get_Storage_Manager return Services.Storage_Service_Access is
Module : constant Storage_Module_Access := Get_Storage_Module;
begin
if Module = null then
Log.Error ("There is no active Storage_Module");
return null;
else
return Module.Get_Storage_Manager;
end if;
end Get_Storage_Manager;
end AWA.Storages.Modules;
|
Update to avoid using the Beans.Factories package
|
Update to avoid using the Beans.Factories package
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6b1d91209293bc822dec28351710b785db614d24
|
regtests/asf-applications-views-tests.adb
|
regtests/asf-applications-views-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for ASF.Applications.Views
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with ASF.Applications.Main;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with Ada.Directories;
with Util.Tests;
with Util.Files;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use AUnit;
use Ada.Strings.Unbounded;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
use ASF;
use ASF.Contexts.Faces;
App : Applications.Main.Application;
-- H : Applications.Views.View_Handler;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
App_Factory : Applications.Main.Application_Factory;
begin
Conf.Load_Properties ("regtests/view.properties");
App.Initialize (Conf, App_Factory);
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Rep : ASF.Responses.Mockup.Response;
Content : Unbounded_String;
begin
Req.Set_Method ("GET");
Req.Set_Path_Info (View_Name);
App.Dispatch (Page => View_Name,
Request => Req,
Response => Rep);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Rep.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
end Test_Load_Facelet;
-- Test case name
overriding
function Name (T : Test) return Message_String is
begin
return Format ("Test " & To_String (T.Name));
end Name;
-- Perform the test.
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "regtests/result/views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) = Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String (File_Path);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for ASF.Applications.Views
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with ASF.Applications.Main;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with Ada.Directories;
with Util.Tests;
with Util.Files;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use AUnit;
use Ada.Strings.Unbounded;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
use ASF;
use ASF.Contexts.Faces;
App : Applications.Main.Application;
-- H : Applications.Views.View_Handler;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
App_Factory : Applications.Main.Application_Factory;
begin
Conf.Load_Properties ("regtests/view.properties");
App.Initialize (Conf, App_Factory);
App.Set_Global ("function", "Test_Load_Facelet");
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Rep : ASF.Responses.Mockup.Response;
Content : Unbounded_String;
begin
Req.Set_Method ("GET");
Req.Set_Path_Info (View_Name);
App.Dispatch (Page => View_Name,
Request => Req,
Response => Rep);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Rep.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
end Test_Load_Facelet;
-- Test case name
overriding
function Name (T : Test) return Message_String is
begin
return Format ("Test " & To_String (T.Name));
end Name;
-- Perform the test.
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "regtests/result/views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) = Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String (File_Path);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
Declare a variable that can be used in tests
|
Declare a variable that can be used in tests
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
c6b431d27d8be68e74a88d777dfe6a5c7f8ce34f
|
src/util-serialize-io-csv.adb
|
src/util-serialize-io-csv.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.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 Integer) is
begin
if Stream.Column > 1 then
Stream.Write (",");
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 (",");
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 (",");
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;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
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
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;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
begin
Stream.Write_Cell (Value);
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
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, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
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 Integer) is
begin
if Stream.Column > 1 then
Stream.Write (",");
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 (",");
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 (",");
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;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
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
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;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
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
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;
|
Implement the Write_Entity operation with a date/time
|
Implement the Write_Entity operation with a date/time
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
13b1ce96ecbd4a4356ddb114d14770d36d3995f2
|
awa/src/awa-permissions-controllers.ads
|
awa/src/awa-permissions-controllers.ads
|
-----------------------------------------------------------------------
-- awa-permissions-controllers -- Permission controllers
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
with Security.Controllers;
package AWA.Permissions.Controllers is
-- ------------------------------
-- Security Controller
-- ------------------------------
-- The <b>Entity_Controller</b> implements an entity based permission check.
-- The controller is configured through an XML description. It uses an SQL statement
-- to verify that a permission is granted.
--
-- The SQL query can use the following query parameters:
--
-- <dl>
-- <dt>entity_type</dt>
-- <dd>The entity type identifier defined by the entity permission</dd>
-- <dt>entity_id</dt>
-- <dd>The entity identifier which is associated with an <b>ACL</b> entry to check</dd>
-- <dt>user_id</dt>
-- <dd>The user identifier</dd>
-- </dl>
type Entity_Controller (Len : Positive) is
limited new Security.Controllers.Controller with record
SQL : String (1 .. Len);
Entity : ADO.Entity_Type;
end record;
type Entity_Controller_Access is access all Entity_Controller'Class;
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access a database entity. The security context contains some
-- information about the entity to check and the permission controller will use an
-- SQL statement to verify the permission.
overriding
function Has_Permission (Handler : in Entity_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
end AWA.Permissions.Controllers;
|
-----------------------------------------------------------------------
-- awa-permissions-controllers -- Permission controllers
-- 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.Contexts;
with Security.Controllers;
package AWA.Permissions.Controllers is
-- ------------------------------
-- Security Controller
-- ------------------------------
-- The <b>Entity_Controller</b> implements an entity based permission check.
-- The controller is configured through an XML description. It uses an SQL statement
-- to verify that a permission is granted.
--
-- The SQL query can use the following query parameters:
--
-- <dl>
-- <dt>entity_type</dt>
-- <dd>The entity type identifier defined by the entity permission</dd>
-- <dt>entity_id</dt>
-- <dd>The entity identifier which is associated with an <b>ACL</b> entry to check</dd>
-- <dt>user_id</dt>
-- <dd>The user identifier</dd>
-- </dl>
type Entity_Controller (Len : Positive) is
limited new Security.Controllers.Controller with record
Entities : Entity_Type_Array;
SQL : String (1 .. Len);
end record;
type Entity_Controller_Access is access all Entity_Controller'Class;
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access a database entity. The security context contains some
-- information about the entity to check and the permission controller will use an
-- SQL statement to verify the permission.
overriding
function Has_Permission (Handler : in Entity_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
end AWA.Permissions.Controllers;
|
Store several entity types in the entity permission definition
|
Store several entity types in the entity permission definition
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e8167616205a91b0aded120690c5963948e8e40e
|
mat/regtests/mat-memory-tests.adb
|
mat/regtests/mat-memory-tests.adb
|
-----------------------------------------------------------------------
-- mat-memory-tests -- Unit tests for MAT 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 Util.Test_Caller;
with MAT.Memory.Targets;
package body MAT.Memory.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Memory");
-- Builtin and well known definition of test frames.
Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) :=
(1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc",
Test_Probe_Malloc'Access);
end Add_Tests;
-- ------------------------------
-- Basic consistency checks when creating the test tree
-- ------------------------------
procedure Test_Probe_Malloc (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
begin
S.Size := 4;
M.Create_Frame (Frame_1_0, S.Frame);
-- Create memory slots:
-- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104]
for I in 1 .. 10 loop
M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S);
end loop;
-- Search for a memory region that does not overlap a memory slot.
M.Find (15, 19, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [15 .. 19]");
M.Find (1, 9, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [1 .. 9]");
M.Find (105, 1000, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [105 .. 1000]");
-- Search with an overlap.
M.Find (1, 1000, R);
Util.Tests.Assert_Equals (T, 10, Integer (R.Length),
"Find must return 10 slots in range [1 .. 1000]");
R.Clear;
M.Find (1, 19, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [1 .. 19]");
R.Clear;
M.Find (13, 19, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [13 .. 19]");
R.Clear;
M.Find (100, 1000, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [100 .. 1000]");
R.Clear;
M.Find (101, 1000, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [101 .. 1000]");
end Test_Probe_Malloc;
end MAT.Memory.Tests;
|
-----------------------------------------------------------------------
-- mat-memory-tests -- Unit tests for MAT 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 Util.Test_Caller;
with MAT.Memory.Targets;
package body MAT.Memory.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Memory");
-- Builtin and well known definition of test frames.
Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) :=
(1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc",
Test_Probe_Malloc'Access);
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free",
Test_Probe_Free'Access);
end Add_Tests;
-- ------------------------------
-- Basic consistency checks when creating the test tree
-- ------------------------------
procedure Test_Probe_Malloc (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
begin
S.Size := 4;
M.Create_Frame (Frame_1_0, S.Frame);
-- Create memory slots:
-- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104]
for I in 1 .. 10 loop
M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S);
end loop;
-- Search for a memory region that does not overlap a memory slot.
M.Find (15, 19, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [15 .. 19]");
M.Find (1, 9, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [1 .. 9]");
M.Find (105, 1000, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [105 .. 1000]");
-- Search with an overlap.
M.Find (1, 1000, R);
Util.Tests.Assert_Equals (T, 10, Integer (R.Length),
"Find must return 10 slots in range [1 .. 1000]");
R.Clear;
M.Find (1, 19, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [1 .. 19]");
R.Clear;
M.Find (13, 19, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [13 .. 19]");
R.Clear;
M.Find (100, 1000, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [100 .. 1000]");
R.Clear;
M.Find (101, 1000, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [101 .. 1000]");
end Test_Probe_Malloc;
-- ------------------------------
-- Test Probe_Free with update of memory slots.
-- ------------------------------
procedure Test_Probe_Free (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
begin
S.Size := 4;
M.Create_Frame (Frame_1_0, S.Frame);
-- Malloc followed by a free.
M.Probe_Malloc (10, S);
M.Probe_Free (10, S);
M.Find (1, 1000, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slot after a free");
end Test_Probe_Free;
end MAT.Memory.Tests;
|
Implement new test for Probe_Free
|
Implement new test for Probe_Free
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f416d4edd91104b5ec7c81583728eca8b370ac77
|
src/security-policies.ads
|
src/security-policies.ads
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with Security.Permissions;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Security Policies ==
-- The Security Policy defines and implements the set of security rules that specify
-- how to protect the system or resources. The <tt>Policy_Manager</tt> maintains
-- the security policies. These policies are registered when an application starts,
-- before reading the policy configuration files.
--
-- [http://ada-security.googlecode.com/svn/wiki/PolicyModel.png]
--
-- While the policy configuration files are processed, the policy instances that have been
-- registered will create a security controller and bind it to a given permission. After
-- successful initialization, the <tt>Policy_Manager</tt> contains a list of securiy
-- controllers which are associated with each permission defined by the application.
--
-- === Authenticated Permission ===
-- The `auth-permission` is a pre-defined permission that can be configured in the XML
-- configuration. Basically the permission is granted if the security context has a principal.
-- Otherwise the permission is denied. The permission is assigned a name and is declared
-- as follows:
--
-- <policy-rules>
-- <auth-permission>
-- <name>view-profile</name>
-- </auth-permission>
-- </policy-rules>
--
-- This example defines the `view-profile` permission.
--
-- === Grant Permission ===
-- The `grant-permission` is another pre-defined permission that gives the permission whatever
-- the security context. The permission is defined as follows:
--
-- <policy-rules>
-- <grant-permission>
-- <name>anonymous</name>
-- </grant-permission>
-- </policy-rules>
--
-- This example defines the `anonymous` permission.
--
-- @include security-policies-roles.ads
-- @include security-policies-urls.ads
--- @include security-controllers.ads
package Security.Policies is
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is
array (Permissions.Permission_Index range <>) of Controller_Access;
type Policy_Index is new Positive;
type Policy_Context is limited interface;
type Policy_Context_Access is access all Policy_Context'Class;
type Policy_Context_Array is
array (Policy_Index range <>) of Policy_Context_Access;
type Policy_Context_Array_Access is access Policy_Context_Array;
-- ------------------------------
-- Security policy
-- ------------------------------
type Policy is abstract new Ada.Finalization.Limited_Controlled with private;
type Policy_Access is access all Policy'Class;
-- Get the policy name.
function Get_Name (From : in Policy) return String is abstract;
-- Get the policy index.
function Get_Policy_Index (From : in Policy'Class) return Policy_Index;
pragma Inline (Get_Policy_Index);
-- Prepare the XML parser to read the policy configuration.
procedure Prepare_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Into : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access);
Invalid_Name : exception;
Policy_Error : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- Checks whether the permission defined by the <b>Permission</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- 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;
-- Create the policy contexts to be associated with the security context.
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access;
-- 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);
-- 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);
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access;
type Policy is abstract new Ada.Finalization.Limited_Controlled with record
Manager : Policy_Manager_Access;
Index : Policy_Index;
end record;
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with record
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
-- The security policies.
Policies : Policy_Access_Array (1 .. Max_Policies);
end record;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 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 Ada.Finalization;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with Security.Permissions;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Security Policies ==
-- The Security Policy defines and implements the set of security rules that specify
-- how to protect the system or resources. The <tt>Policy_Manager</tt> maintains
-- the security policies. These policies are registered when an application starts,
-- before reading the policy configuration files.
--
-- [http://ada-security.googlecode.com/svn/wiki/PolicyModel.png]
--
-- While the policy configuration files are processed, the policy instances that have been
-- registered will create a security controller and bind it to a given permission. After
-- successful initialization, the <tt>Policy_Manager</tt> contains a list of securiy
-- controllers which are associated with each permission defined by the application.
--
-- === Authenticated Permission ===
-- The `auth-permission` is a pre-defined permission that can be configured in the XML
-- configuration. Basically the permission is granted if the security context has a principal.
-- Otherwise the permission is denied. The permission is assigned a name and is declared
-- as follows:
--
-- <policy-rules>
-- <auth-permission>
-- <name>view-profile</name>
-- </auth-permission>
-- </policy-rules>
--
-- This example defines the `view-profile` permission.
--
-- === Grant Permission ===
-- The `grant-permission` is another pre-defined permission that gives the permission whatever
-- the security context. The permission is defined as follows:
--
-- <policy-rules>
-- <grant-permission>
-- <name>anonymous</name>
-- </grant-permission>
-- </policy-rules>
--
-- This example defines the `anonymous` permission.
--
-- @include security-policies-roles.ads
-- @include security-policies-urls.ads
--- @include security-controllers.ads
package Security.Policies is
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is
array (Permissions.Permission_Index range <>) of Controller_Access;
type Policy_Index is new Positive;
type Policy_Context is limited interface;
type Policy_Context_Access is access all Policy_Context'Class;
type Policy_Context_Array is
array (Policy_Index range <>) of Policy_Context_Access;
type Policy_Context_Array_Access is access Policy_Context_Array;
-- ------------------------------
-- Security policy
-- ------------------------------
type Policy is abstract new Ada.Finalization.Limited_Controlled with private;
type Policy_Access is access all Policy'Class;
-- Get the policy name.
function Get_Name (From : in Policy) return String is abstract;
-- Get the policy index.
function Get_Policy_Index (From : in Policy'Class) return Policy_Index;
pragma Inline (Get_Policy_Index);
-- Prepare the XML parser to read the policy configuration.
procedure Prepare_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
procedure Finish_Config (Into : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access);
Invalid_Name : exception;
Policy_Error : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- Checks whether the permission defined by the <b>Permission</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- 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;
-- Create the policy contexts to be associated with the security context.
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access;
-- 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);
-- 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);
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access;
type Policy is abstract new Ada.Finalization.Limited_Controlled with record
Manager : Policy_Manager_Access;
Index : Policy_Index := Policy_Index'First;
end record;
type Policy_Manager (Max_Policies : Policy_Index) is
new Ada.Finalization.Limited_Controlled with record
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
-- The security policies.
Policies : Policy_Access_Array (1 .. Max_Policies);
end record;
end Security.Policies;
|
Add a default initializer for Index in Policy record
|
Add a default initializer for Index in Policy record
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
03c408fd7ff0afcc1372eaa1f39638a02289f600
|
mat/src/memory/mat-memory-readers.adb
|
mat/src/memory/mat-memory-readers.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Types;
with MAT.Readers.Marshaller;
with MAT.Memory;
package body MAT.Memory.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers");
MSG_MALLOC : constant MAT.Events.Internal_Reference := 0;
MSG_FREE : constant MAT.Events.Internal_Reference := 1;
MSG_REALLOC : constant MAT.Events.Internal_Reference := 2;
M_SIZE : constant MAT.Events.Internal_Reference := 1;
M_FRAME : constant MAT.Events.Internal_Reference := 2;
M_ADDR : constant MAT.Events.Internal_Reference := 3;
M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4;
M_THREAD : constant MAT.Events.Internal_Reference := 5;
M_UNKNOWN : constant MAT.Events.Internal_Reference := 6;
M_TIME : constant MAT.Events.Internal_Reference := 7;
-- Defines the possible data kinds which are recognized by
-- the memory unmarshaller. All others are ignored.
SIZE_NAME : aliased constant String := "size";
FRAME_NAME : aliased constant String := "frame";
ADDR_NAME : aliased constant String := "pointer";
OLD_NAME : aliased constant String := "old-pointer";
THREAD_NAME : aliased constant String := "thread";
TIME_NAME : aliased constant String := "time";
Memory_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => SIZE_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE),
2 => (Name => FRAME_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_FRAME),
3 => (Name => ADDR_NAME'Access, Size => 0,
Kind => MAT.Events.T_POINTER, Ref => M_ADDR),
4 => (Name => OLD_NAME'Access, Size => 0,
Kind => MAT.Events.T_POINTER, Ref => M_ADDR),
5 => (Name => THREAD_NAME'Access, Size => 0,
Kind => MAT.Events.T_THREAD, Ref => M_THREAD),
6 => (Name => TIME_NAME'Access, Size => 0,
Kind => MAT.Events.T_TIME, Ref => M_TIME));
procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message;
Slot : in out Allocation;
Addr : in out MAT.Types.Target_Addr;
Old_Addr : in out MAT.Types.Target_Addr;
Defs : in MAT.Events.Attribute_Table);
----------------------
-- Register the reader to extract and analyze memory events.
----------------------
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Memory_Reader_Access) is
begin
Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC,
Memory_Attributes'Access);
Into.Register_Reader (Reader.all'Access, "free", MSG_FREE,
Memory_Attributes'Access);
Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC,
Memory_Attributes'Access);
end Register;
----------------------
-- Unmarshall from the message the memory slot information.
-- The data is described by the Defs table.
----------------------
procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message;
Slot : in out Allocation;
Addr : in out MAT.Types.Target_Addr;
Old_Addr : in out MAT.Types.Target_Addr;
Defs : in MAT.Events.Attribute_Table) is
begin
for I in Defs'Range loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_SIZE =>
Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind);
when M_ADDR =>
Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when M_OLD_ADDR =>
Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when M_UNKNOWN =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
when others =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
end case;
end;
end loop;
end Unmarshall_Allocation;
overriding
procedure Dispatch (For_Servant : in out Memory_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
Slot : Allocation;
Addr : MAT.Types.Target_Addr := 0;
Old_Addr : MAT.Types.Target_Addr := 0;
begin
case Id is
when MSG_MALLOC =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
For_Servant.Data.Create_Frame (Pc => Frame.Frame (1 .. Frame.Cur_Depth),
Result => Slot.Frame);
For_Servant.Data.Probe_Malloc (Addr, Slot);
when MSG_FREE =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
For_Servant.Data.Probe_Free (Addr, Slot);
when MSG_REALLOC =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
For_Servant.Data.Create_Frame (Pc => Frame.Frame (1 .. Frame.Cur_Depth),
Result => Slot.Frame);
For_Servant.Data.Probe_Realloc (Addr, Old_Addr, Slot);
when others =>
raise Program_Error;
end case;
end Dispatch;
end MAT.Memory.Readers;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Types;
with MAT.Readers.Marshaller;
with MAT.Memory;
package body MAT.Memory.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers");
MSG_MALLOC : constant MAT.Events.Internal_Reference := 0;
MSG_FREE : constant MAT.Events.Internal_Reference := 1;
MSG_REALLOC : constant MAT.Events.Internal_Reference := 2;
M_SIZE : constant MAT.Events.Internal_Reference := 1;
M_FRAME : constant MAT.Events.Internal_Reference := 2;
M_ADDR : constant MAT.Events.Internal_Reference := 3;
M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4;
M_THREAD : constant MAT.Events.Internal_Reference := 5;
M_UNKNOWN : constant MAT.Events.Internal_Reference := 6;
M_TIME : constant MAT.Events.Internal_Reference := 7;
-- Defines the possible data kinds which are recognized by
-- the memory unmarshaller. All others are ignored.
SIZE_NAME : aliased constant String := "size";
FRAME_NAME : aliased constant String := "frame";
ADDR_NAME : aliased constant String := "pointer";
OLD_NAME : aliased constant String := "old-pointer";
THREAD_NAME : aliased constant String := "thread";
TIME_NAME : aliased constant String := "time";
Memory_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => SIZE_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE),
2 => (Name => FRAME_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_FRAME),
3 => (Name => ADDR_NAME'Access, Size => 0,
Kind => MAT.Events.T_POINTER, Ref => M_ADDR),
4 => (Name => OLD_NAME'Access, Size => 0,
Kind => MAT.Events.T_POINTER, Ref => M_OLD_ADDR),
5 => (Name => THREAD_NAME'Access, Size => 0,
Kind => MAT.Events.T_THREAD, Ref => M_THREAD),
6 => (Name => TIME_NAME'Access, Size => 0,
Kind => MAT.Events.T_TIME, Ref => M_TIME));
procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message;
Slot : in out Allocation;
Addr : in out MAT.Types.Target_Addr;
Old_Addr : in out MAT.Types.Target_Addr;
Defs : in MAT.Events.Attribute_Table);
----------------------
-- Register the reader to extract and analyze memory events.
----------------------
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Memory_Reader_Access) is
begin
Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC,
Memory_Attributes'Access);
Into.Register_Reader (Reader.all'Access, "free", MSG_FREE,
Memory_Attributes'Access);
Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC,
Memory_Attributes'Access);
end Register;
----------------------
-- Unmarshall from the message the memory slot information.
-- The data is described by the Defs table.
----------------------
procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message;
Slot : in out Allocation;
Addr : in out MAT.Types.Target_Addr;
Old_Addr : in out MAT.Types.Target_Addr;
Defs : in MAT.Events.Attribute_Table) is
begin
for I in Defs'Range loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_SIZE =>
Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind);
when M_ADDR =>
Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when M_OLD_ADDR =>
Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when M_UNKNOWN =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
when others =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
end case;
end;
end loop;
end Unmarshall_Allocation;
overriding
procedure Dispatch (For_Servant : in out Memory_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
Slot : Allocation;
Addr : MAT.Types.Target_Addr := 0;
Old_Addr : MAT.Types.Target_Addr := 0;
begin
case Id is
when MSG_MALLOC =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
For_Servant.Data.Create_Frame (Pc => Frame.Frame (1 .. Frame.Cur_Depth),
Result => Slot.Frame);
For_Servant.Data.Probe_Malloc (Addr, Slot);
when MSG_FREE =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
For_Servant.Data.Probe_Free (Addr, Slot);
when MSG_REALLOC =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
For_Servant.Data.Create_Frame (Pc => Frame.Frame (1 .. Frame.Cur_Depth),
Result => Slot.Frame);
For_Servant.Data.Probe_Realloc (Addr, Old_Addr, Slot);
when others =>
raise Program_Error;
end case;
end Dispatch;
end MAT.Memory.Readers;
|
Fix the realloc attributes definition
|
Fix the realloc attributes definition
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
648bcfb9021b799b09673fd4580298980224ff99
|
mat/src/memory/mat-memory-targets.adb
|
mat/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info) is
begin
Memory.Memory.Add_Region (Region);
end Add_Region;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map) is
begin
Memory.Memory.Thread_Information (Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
Memory.Memory.Frame_Information (Level, Frames);
end Frame_Information;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat) is
begin
Memory.Memory.Stat_Information (Result);
end Stat_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Filter, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Region : in Region_Info) is
begin
Regions.Insert (Region.Start_Addr, Region);
end Add_Region;
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation);
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
pragma Unreferenced (Key);
begin
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
Pos : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end if;
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
MAT.Memory.Tools.Size_Information (Used_Slots, Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Threads : in out Memory_Info_Map) is
begin
MAT.Memory.Tools.Thread_Information (Used_Slots, Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into);
end Find;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Result : out Memory_Stat) is
begin
Result := Stats;
end Stat_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info) is
begin
Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-"
& MAT.Types.Hex_Image (Region.End_Addr) & "]");
Memory.Memory.Add_Region (Region);
end Add_Region;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map) is
begin
Memory.Memory.Thread_Information (Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
Memory.Memory.Frame_Information (Level, Frames);
end Frame_Information;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat) is
begin
Memory.Memory.Stat_Information (Result);
end Stat_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Filter, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Region : in Region_Info) is
begin
Regions.Insert (Region.Start_Addr, Region);
end Add_Region;
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation);
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
pragma Unreferenced (Key);
begin
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
Pos : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end if;
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
MAT.Memory.Tools.Size_Information (Used_Slots, Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Threads : in out Memory_Info_Map) is
begin
MAT.Memory.Tools.Thread_Information (Used_Slots, Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into);
end Find;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Result : out Memory_Stat) is
begin
Result := Stats;
end Stat_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
Add a log for debugging
|
Add a log for debugging
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
d250df3df7d547e254e36190c9711fa3a5c41863
|
matp/src/events/mat-events-timelines.adb
|
matp/src/events/mat-events-timelines.adb
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Frames;
package body MAT.Events.Timelines is
use MAT.Events.Targets;
ITERATE_COUNT : constant MAT.Events.Targets.Event_Id_Type := 10_000;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events;
Into : in out Timeline_Info_Vector) is
use type MAT.Types.Target_Time;
procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type);
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Prev_Event : MAT.Events.Targets.Probe_Event_Type;
Info : Timeline_Info;
First_Id : MAT.Events.Targets.Event_Id_Type;
procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type) is
Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time;
begin
if Dt > 500_000 then
Into.Append (Info);
Info.Malloc_Count := 0;
Info.Realloc_Count := 0;
Info.Free_Count := 0;
Info.Start_Id := Event.Id;
Info.Start_Time := Event.Time;
end if;
Info.End_Id := Event.Id;
Info.End_Time := Event.Time;
if Event.Event = 2 then
Info.Malloc_Count := Info.Malloc_Count + 1;
elsif Event.Event = 3 then
Info.Realloc_Count := Info.Realloc_Count + 1;
elsif Event.Event = 4 then
Info.Free_Count := Info.Free_Count + 1;
end if;
end Collect;
begin
Target.Get_Limits (First_Event, Last_Event);
Prev_Event := First_Event;
Info.Start_Id := First_Event.Id;
Info.Start_Time := First_Event.Time;
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Extract;
-- ------------------------------
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
-- ------------------------------
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Targets.Probe_Event_Type;
Max : in Positive;
List : in out MAT.Events.Targets.Target_Event_Vector) is
procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type);
procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type);
First_Id : MAT.Events.Targets.Event_Id_Type;
Last_Id : MAT.Events.Targets.Event_Id_Type;
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Addr : MAT.Types.Target_Addr := Event.Addr;
Done : exception;
procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
if Event.Index = MAT.Events.Targets.MSG_FREE and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Old_Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Addr;
end if;
end Collect_Free;
procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
if Event.Index = MAT.Events.Targets.MSG_MALLOC and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Old_Addr;
end if;
end Collect_Alloc;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := Event.Id;
if Event.Index = MAT.Events.Targets.MSG_FREE then
-- Search backward for MSG_MALLOC and MSG_REALLOC.
First_Id := First_Id - 1;
while First_Id > First_Event.Id loop
if First_Id > ITERATE_COUNT then
Last_Id := First_Id - ITERATE_COUNT;
else
Last_Id := First_Event.Id;
end if;
Target.Iterate (Start => First_Id,
Finish => Last_Id,
Process => Collect_Alloc'Access);
First_Id := Last_Id;
end loop;
else
-- Search forward for MSG_REALLOC and MSG_FREE
First_Id := First_Id + 1;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect_Free'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end if;
exception
when Done =>
null;
end Find_Related;
-- ------------------------------
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
-- ------------------------------
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Targets.Size_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event);
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
end Update_Size;
begin
-- Look for malloc or realloc events which are selected by the filter.
if (Event.Index /= MAT.Events.Targets.MSG_MALLOC
and Event.Index /= MAT.Events.Targets.MSG_REALLOC)
or else not Filter.Is_Selected (Event)
then
return;
end if;
declare
Pos : constant MAT.Events.Targets.Size_Event_Info_Cursor := Sizes.Find (Event.Size);
begin
if MAT.Events.Targets.Size_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Sizes.Update_Element (Pos, Update_Size'Access);
else
declare
Info : Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Count := 1;
Sizes.Insert (Event.Size, Info);
end;
end if;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Sizes;
-- ------------------------------
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
-- ------------------------------
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Natural;
Frames : in out MAT.Events.Targets.Frame_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event);
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
end Update_Size;
begin
-- Look for events which are selected by the filter.
if not Filter.Is_Selected (Event) then
return;
end if;
declare
Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame);
begin
for I in Backtrace'Range loop
exit when I > Depth;
declare
Pos : constant MAT.Events.Targets.Frame_Event_Info_Cursor
:= Frames.Find (Backtrace (I));
begin
if MAT.Events.Targets.Frame_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Frames.Update_Element (Pos, Update_Size'Access);
else
declare
Info : Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Frame_Addr := Backtrace (I);
Info.Count := 1;
Frames.Insert (Backtrace (I), Info);
end;
end if;
end;
end loop;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Frames;
end MAT.Events.Timelines;
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Frames;
package body MAT.Events.Timelines is
use MAT.Events.Targets;
ITERATE_COUNT : constant MAT.Events.Targets.Event_Id_Type := 10_000;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class;
Into : in out Timeline_Info_Vector) is
use type MAT.Types.Target_Time;
procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type);
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Prev_Event : MAT.Events.Targets.Probe_Event_Type;
Info : Timeline_Info;
First_Id : MAT.Events.Targets.Event_Id_Type;
procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type) is
Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time;
begin
if Dt > 500_000 then
Into.Append (Info);
Info.Malloc_Count := 0;
Info.Realloc_Count := 0;
Info.Free_Count := 0;
Info.First_Event := Event;
Prev_Event := Event;
end if;
Info.Last_Event := Event;
if Event.Event = 2 then
Info.Malloc_Count := Info.Malloc_Count + 1;
elsif Event.Event = 3 then
Info.Realloc_Count := Info.Realloc_Count + 1;
elsif Event.Event = 4 then
Info.Free_Count := Info.Free_Count + 1;
end if;
end Collect;
begin
Target.Get_Limits (First_Event, Last_Event);
Prev_Event := First_Event;
Info.First_Event := First_Event;
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Extract;
-- ------------------------------
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
-- ------------------------------
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Targets.Probe_Event_Type;
Max : in Positive;
List : in out MAT.Events.Targets.Target_Event_Vector) is
procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type);
procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type);
First_Id : MAT.Events.Targets.Event_Id_Type;
Last_Id : MAT.Events.Targets.Event_Id_Type;
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Addr : MAT.Types.Target_Addr := Event.Addr;
Done : exception;
procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
if Event.Index = MAT.Events.Targets.MSG_FREE and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Old_Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Addr;
end if;
end Collect_Free;
procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
if Event.Index = MAT.Events.Targets.MSG_MALLOC and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Old_Addr;
end if;
end Collect_Alloc;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := Event.Id;
if Event.Index = MAT.Events.Targets.MSG_FREE then
-- Search backward for MSG_MALLOC and MSG_REALLOC.
First_Id := First_Id - 1;
while First_Id > First_Event.Id loop
if First_Id > ITERATE_COUNT then
Last_Id := First_Id - ITERATE_COUNT;
else
Last_Id := First_Event.Id;
end if;
Target.Iterate (Start => First_Id,
Finish => Last_Id,
Process => Collect_Alloc'Access);
First_Id := Last_Id;
end loop;
else
-- Search forward for MSG_REALLOC and MSG_FREE
First_Id := First_Id + 1;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect_Free'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end if;
exception
when Done =>
null;
end Find_Related;
-- ------------------------------
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
-- ------------------------------
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Targets.Size_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event);
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
end Update_Size;
begin
-- Look for malloc or realloc events which are selected by the filter.
if (Event.Index /= MAT.Events.Targets.MSG_MALLOC
and Event.Index /= MAT.Events.Targets.MSG_REALLOC)
or else not Filter.Is_Selected (Event)
then
return;
end if;
declare
Pos : constant MAT.Events.Targets.Size_Event_Info_Cursor := Sizes.Find (Event.Size);
begin
if MAT.Events.Targets.Size_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Sizes.Update_Element (Pos, Update_Size'Access);
else
declare
Info : Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Count := 1;
Sizes.Insert (Event.Size, Info);
end;
end if;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Sizes;
-- ------------------------------
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
-- ------------------------------
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Natural;
Frames : in out MAT.Events.Targets.Frame_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event);
procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Targets.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
end Update_Size;
begin
-- Look for events which are selected by the filter.
if not Filter.Is_Selected (Event) then
return;
end if;
declare
Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame);
begin
for I in Backtrace'Range loop
exit when I > Depth;
declare
Pos : constant MAT.Events.Targets.Frame_Event_Info_Cursor
:= Frames.Find (Backtrace (I));
begin
if MAT.Events.Targets.Frame_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Frames.Update_Element (Pos, Update_Size'Access);
else
declare
Info : Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Frame_Addr := Backtrace (I);
Info.Count := 1;
Frames.Insert (Backtrace (I), Info);
end;
end if;
end;
end loop;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Frames;
end MAT.Events.Timelines;
|
Fix the Extract procedure to identify the timeline groups
|
Fix the Extract procedure to identify the timeline groups
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
3d3f5914c29cc46a92f1f665d95e2f5c47420c56
|
matp/src/events/mat-events-timelines.ads
|
matp/src/events/mat-events-timelines.ads
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Vectors;
with MAT.Expressions;
with MAT.Events.Tools;
with MAT.Events.Targets;
package MAT.Events.Timelines is
-- Describe a section of the timeline. The section has a starting and ending
-- event that marks the boundary of the section within the collected events.
-- The timeline section gives the duration and some statistics about memory
-- allocation made in the section.
type Timeline_Info is record
First_Event : MAT.Events.Target_Event_Type;
Last_Event : MAT.Events.Target_Event_Type;
Duration : MAT.Types.Target_Time := 0;
Malloc_Count : Natural := 0;
Realloc_Count : Natural := 0;
Free_Count : Natural := 0;
Alloc_Size : MAT.Types.Target_Size := 0;
Free_Size : MAT.Types.Target_Size := 0;
end record;
package Timeline_Info_Vectors is
new Ada.Containers.Vectors (Positive, Timeline_Info);
subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector;
subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class;
Into : in out Timeline_Info_Vector);
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Target_Event_Type;
Max : in Positive;
List : in out MAT.Events.Tools.Target_Event_Vector);
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Tools.Size_Event_Info_Map);
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Positive;
Exact : in Boolean;
Frames : in out MAT.Events.Tools.Frame_Event_Info_Map);
end MAT.Events.Timelines;
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Vectors;
with MAT.Expressions;
with MAT.Events.Tools;
with MAT.Events.Targets;
package MAT.Events.Timelines is
-- Describe a section of the timeline. The section has a starting and ending
-- event that marks the boundary of the section within the collected events.
-- The timeline section gives the duration and some statistics about memory
-- allocation made in the section.
type Timeline_Info is record
First_Event : MAT.Events.Target_Event_Type;
Last_Event : MAT.Events.Target_Event_Type;
Duration : MAT.Types.Target_Time := 0;
Malloc_Count : Natural := 0;
Realloc_Count : Natural := 0;
Free_Count : Natural := 0;
Alloc_Size : MAT.Types.Target_Size := 0;
Free_Size : MAT.Types.Target_Size := 0;
end record;
package Timeline_Info_Vectors is
new Ada.Containers.Vectors (Positive, Timeline_Info);
subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector;
subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class;
Level : in Positive;
Into : in out Timeline_Info_Vector);
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Target_Event_Type;
Max : in Positive;
List : in out MAT.Events.Tools.Target_Event_Vector);
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Tools.Size_Event_Info_Map);
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Positive;
Exact : in Boolean;
Frames : in out MAT.Events.Tools.Frame_Event_Info_Map);
end MAT.Events.Timelines;
|
Add a Level parameter to the timeline calculation to define the time in seconds for the timeline analysis
|
Add a Level parameter to the timeline calculation to define the time
in seconds for the timeline analysis
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
4767d0e077a999d9614765db72f377ce4b21b172
|
src/http/util-http-clients-mockups.adb
|
src/http/util-http-clients-mockups.adb
|
-----------------------------------------------------------------------
-- util-http-clients-mockups -- HTTP Clients
-- 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 Util.Files;
with Util.Http.Mockups;
package body Util.Http.Clients.Mockups is
use Ada.Strings.Unbounded;
Manager : aliased File_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
-- ------------------------------
-- Set the path of the file that contains the response for the next
-- <b>Do_Get</b> and <b>Do_Post</b> calls.
-- ------------------------------
procedure Set_File (Path : in String) is
begin
Manager.File := To_Unbounded_String (Path);
end Set_File;
procedure Create (Manager : in File_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new Util.Http.Mockups.Mockup_Request;
end Create;
overriding
procedure Do_Get (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Http, URI);
Rep : constant Util.Http.Mockups.Mockup_Response_Access
:= new Util.Http.Mockups.Mockup_Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Delegate := Rep.all'Access;
Util.Files.Read_File (Path => To_String (Manager.File),
Into => Content,
Max_Size => 100000);
Rep.Set_Body (To_String (Content));
Rep.Set_Status (SC_OK);
end Do_Get;
overriding
procedure Do_Post (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Post;
overriding
procedure Do_Put (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Put;
-- ------------------------------
-- Set the timeout for the connection.
-- ------------------------------
overriding
procedure Set_Timeout (Manager : in File_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
pragma Unreferenced (Manager, Http, Timeout);
begin
null;
end Set_Timeout;
end Util.Http.Clients.Mockups;
|
-----------------------------------------------------------------------
-- util-http-clients-mockups -- HTTP Clients
-- 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 Util.Files;
with Util.Http.Mockups;
package body Util.Http.Clients.Mockups is
use Ada.Strings.Unbounded;
Manager : aliased File_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
-- ------------------------------
-- Set the path of the file that contains the response for the next
-- <b>Do_Get</b> and <b>Do_Post</b> calls.
-- ------------------------------
procedure Set_File (Path : in String) is
begin
Manager.File := To_Unbounded_String (Path);
end Set_File;
procedure Create (Manager : in File_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new Util.Http.Mockups.Mockup_Request;
end Create;
overriding
procedure Do_Get (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Http, URI);
Rep : constant Util.Http.Mockups.Mockup_Response_Access
:= new Util.Http.Mockups.Mockup_Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Delegate := Rep.all'Access;
Util.Files.Read_File (Path => To_String (Manager.File),
Into => Content,
Max_Size => 100000);
Rep.Set_Body (To_String (Content));
Rep.Set_Status (SC_OK);
end Do_Get;
overriding
procedure Do_Post (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Post;
overriding
procedure Do_Put (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Put;
overriding
procedure Do_Delete (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Delete;
-- ------------------------------
-- Set the timeout for the connection.
-- ------------------------------
overriding
procedure Set_Timeout (Manager : in File_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
pragma Unreferenced (Manager, Http, Timeout);
begin
null;
end Set_Timeout;
end Util.Http.Clients.Mockups;
|
Implement the Do_Delete procedure for the mockup
|
Implement the Do_Delete procedure for the mockup
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
058f46b6b74634a9f2beb63e8af426062cf57d70
|
awa/regtests/awa-jobs-modules-tests.adb
|
awa/regtests/awa-jobs-modules-tests.adb
|
-----------------------------------------------------------------------
-- jobs-tests -- Unit tests for AWA jobs
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with AWA.Jobs.Modules;
with AWA.Jobs.Services.Tests;
package body AWA.Jobs.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Jobs.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register",
Test_Register'Access);
end Add_Tests;
-- ------------------------------
-- Test the job factory.
-- ------------------------------
procedure Test_Register (T : in out Test) is
M : AWA.Jobs.Modules.Job_Module;
begin
M.Register (Definition => Services.Tests.Test_Definition.Factory'Access);
Util.Tests.Assert_Equals (T, 1, Integer (M.Factory.Length), "Invalid factory length");
M.Register (Definition => Services.Tests.Work_1_Definition.Factory'Access);
Util.Tests.Assert_Equals (T, 2, Integer (M.Factory.Length), "Invalid factory length");
M.Register (Definition => Services.Tests.Work_2_Definition.Factory'Access);
Util.Tests.Assert_Equals (T, 3, Integer (M.Factory.Length), "Invalid factory length");
end Test_Register;
end AWA.Jobs.Modules.Tests;
|
-----------------------------------------------------------------------
-- jobs-tests -- Unit tests for AWA jobs
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with AWA.Jobs.Modules;
with AWA.Jobs.Services.Tests;
package body AWA.Jobs.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Jobs.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register",
Test_Register'Access);
end Add_Tests;
-- ------------------------------
-- Test the job factory.
-- ------------------------------
procedure Test_Register (T : in out Test) is
M : AWA.Jobs.Modules.Job_Module;
begin
M.Register (Definition => Services.Tests.Test_Definition.Factory);
Util.Tests.Assert_Equals (T, 1, Integer (M.Factory.Length), "Invalid factory length");
M.Register (Definition => Services.Tests.Work_1_Definition.Factory);
Util.Tests.Assert_Equals (T, 2, Integer (M.Factory.Length), "Invalid factory length");
M.Register (Definition => Services.Tests.Work_2_Definition.Factory);
Util.Tests.Assert_Equals (T, 3, Integer (M.Factory.Length), "Invalid factory length");
end Test_Register;
end AWA.Jobs.Modules.Tests;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
77f9d198306ad49aba6175e47442cc006cf89ba6
|
src/el-expressions.adb
|
src/el-expressions.adb
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Language
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Expressions.Nodes;
with EL.Expressions.Parser;
package body EL.Expressions is
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : Expression;
Context : ELContext'Class) return Object is
begin
if Expr.Node = null then
return EL.Objects.Null_Object;
end if;
return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context);
end Get_Value;
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : ValueExpression;
Context : ELContext'Class) return Object is
pragma Unreferenced (Context);
begin
if Expr.Bean = null then
return EL.Objects.Null_Object;
end if;
return To_Object (Expr.Bean);
end Get_Value;
procedure Set_Value (Expr : in ValueExpression;
Context : in ELContext'Class;
Value : in Object) is
begin
null;
end Set_Value;
function Is_Readonly (Expr : in ValueExpression) return Boolean is
begin
if Expr.Bean = null then
return True;
end if;
return not (Expr.Bean.all in EL.Beans.Bean'Class);
end Is_Readonly;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
Result : Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
if Node /= null then
Result.Node := Node.all'Access;
end if;
return Result;
end Create_Expression;
function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class)
return ValueExpression is
Result : ValueExpression;
begin
Result.Bean := Bean;
return Result;
end Create_ValueExpression;
-- Parse an expression and return its representation ready for evaluation.
function Create_Expression (Expr : String;
Context : ELContext'Class)
return ValueExpression is
Result : ValueExpression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
Result.Node := Node.all'Access;
return Result;
end Create_Expression;
procedure Adjust (Object : in out Expression) is
begin
if Object.Node /= null then
Object.Node.Ref_Counter := Object.Node.Ref_Counter + 1;
end if;
end Adjust;
procedure Finalize (Object : in out Expression) is
Node : EL.Expressions.Nodes.ELNode_Access;
begin
if Object.Node /= null then
Node := Object.Node.all'Access;
Node.Ref_Counter := Node.Ref_Counter - 1;
if Node.Ref_Counter = 0 then
EL.Expressions.Nodes.Delete (Node);
Object.Node := null;
end if;
end if;
end Finalize;
end EL.Expressions;
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Language
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Expressions.Nodes;
with EL.Expressions.Parser;
package body EL.Expressions is
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : Expression;
Context : ELContext'Class) return Object is
begin
if Expr.Node = null then
return EL.Objects.Null_Object;
end if;
return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context);
end Get_Value;
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : ValueExpression;
Context : ELContext'Class) return Object is
pragma Unreferenced (Context);
begin
if Expr.Bean = null then
if Expr.Node = null then
return EL.Objects.Null_Object;
else
return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context);
end if;
end if;
return To_Object (Expr.Bean);
end Get_Value;
procedure Set_Value (Expr : in ValueExpression;
Context : in ELContext'Class;
Value : in Object) is
begin
null;
end Set_Value;
function Is_Readonly (Expr : in ValueExpression) return Boolean is
begin
if Expr.Bean = null then
return True;
end if;
return not (Expr.Bean.all in EL.Beans.Bean'Class);
end Is_Readonly;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
Result : Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
if Node /= null then
Result.Node := Node.all'Access;
end if;
return Result;
end Create_Expression;
function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class)
return ValueExpression is
Result : ValueExpression;
begin
Result.Bean := Bean;
return Result;
end Create_ValueExpression;
-- Parse an expression and return its representation ready for evaluation.
function Create_Expression (Expr : String;
Context : ELContext'Class)
return ValueExpression is
Result : ValueExpression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
Result.Node := Node.all'Access;
return Result;
end Create_Expression;
procedure Adjust (Object : in out Expression) is
begin
if Object.Node /= null then
Object.Node.Ref_Counter := Object.Node.Ref_Counter + 1;
end if;
end Adjust;
procedure Finalize (Object : in out Expression) is
Node : EL.Expressions.Nodes.ELNode_Access;
begin
if Object.Node /= null then
Node := Object.Node.all'Access;
Node.Ref_Counter := Node.Ref_Counter - 1;
if Node.Ref_Counter = 0 then
EL.Expressions.Nodes.Delete (Node);
Object.Node := null;
end if;
end if;
end Finalize;
end EL.Expressions;
|
Fix Get_Value for the Value_Expression
|
Fix Get_Value for the Value_Expression
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
6501b36f5ca2573a289dae33bc18d70196d6a363
|
src/nanomsg-socket.adb
|
src/nanomsg-socket.adb
|
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Ada.Streams;
with Interfaces.C.Strings;
with Interfaces.C.Pointers;
with Nanomsg.Errors;
with System;
package body Nanomsg.Socket is
package C renames Interfaces.C;
use type C.Int;
function Is_Null (Obj : in Socket_T) return Boolean is (Obj.Fd = -1);
procedure Init (Obj : out Socket_T;
Domain : in Nanomsg.Domains.Domain_T;
Protocol : in Nanomsg.Protocols.Protocol_T
) is
function C_Nn_Socket (Domain : in C.Int; Protocol : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_socket";
begin
Obj.Fd := Integer (C_Nn_Socket (Nanomsg.Domains.To_C (Domain),
Nanomsg.Protocols.To_C (Protocol)));
if Obj.Fd < 0 then
raise Socket_Exception with "Init: " & Nanomsg.Errors.Errno_Text;
end if;
end Init;
procedure Close (Obj : in out Socket_T) is
function C_Nn_Close (Socket : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_close";
begin
Obj.Delete_Endpoint;
if C_Nn_Close (C.Int (Obj.Fd)) /= 0 then
raise Socket_Exception with "Close: " & Nanomsg.Errors.Errno_Text;
end if;
Obj.Fd := -1;
end Close;
procedure Bind (Obj : in Socket_T;
Address : in String) is
function C_Bind (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_bind";
Endpoint : C.Int := -1;
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Endpoint := C_Bind(C.Int (Obj.Fd), C_Address);
C.Strings.Free (C_Address);
if Endpoint < -1 then
raise Socket_Exception with "Bind: " & Nanomsg.Errors.Errno_Text;
end if;
-- FIXME
-- Add endpoints container
end Bind;
procedure Connect (Obj : in Socket_T;
Address : in String) is
function C_Connect (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_connect";
Endpoint : C.Int := -1;
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Endpoint := C_Connect(C.Int (Obj.Fd), C_Address) ;
C.Strings.Free (C_Address);
if Endpoint < 0 then
raise Socket_Exception with "Connect: " & Nanomsg.Errors.Errno_Text;
end if;
end Connect;
function Get_Fd (Obj : in Socket_T) return Integer is (Obj.Fd);
procedure Receive (Obj : in out Socket_T;
Message : out Nanomsg.Messages.Message_T) is
Payload : System.Address;
use type System.Address;
Received : Integer;
use type C.Size_T;
Flags : constant C.Int := 0;
Nn_Msg : constant C.Size_T := C.Size_T'Last;
function Nn_Recv (Socket : C.Int;
Buf_Access : out System.Address;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_recv";
function Free_Msg (Buf_Access :System.Address) return C.Int
with Import, Convention => C, External_Name => "nn_freemsg";
begin
Received := Integer (Nn_Recv (C.Int (Obj.Fd), Payload, Nn_Msg, Flags));
if Received < 0 then
raise Socket_Exception with "Receive: " & Nanomsg.Errors.Errno_Text;
end if;
Message.Set_Length (Received);
declare
Data : Ada.Streams.Stream_Element_Array (1 .. Ada.Streams.Stream_Element_Offset (Received));
for Data'Address use Payload;
begin
Message.Set_Payload (Data);
end;
if Free_Msg (Payload) < 0 then
raise Socket_Exception with "Deallocation failed";
end if;
end Receive;
procedure Send (Obj : in Socket_T; Message : Nanomsg.Messages.Message_T) is
Flags : C.Int := 0;
function Nn_Send (Socket : C.Int;
Buf_Access : Ada.Streams.Stream_Element_Array;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_send";
Sent : Integer;
begin
Sent := Integer (Nn_Send (C.Int (Obj.Fd),
Message.Get_Payload.all,
C.Size_T (Message.Get_Length),
Flags));
if Sent < 0 then
raise Socket_Exception with "Send: " & Nanomsg.Errors.Errno_Text;
end if;
if Sent /= Message.Get_Length then
raise Socket_Exception with "Send/Receive count doesn't match";
end if;
end Send;
procedure Delete_Endpoint (Obj : in out Socket_T) is
function Nn_Shutdown (Socket : C.Int;
Endpoint : C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_shutodown";
begin
if Nn_Shutdown (Obj.Fd, Obj.Endpoint) < 0 then
raise Socket_Exception with "Shutdown Error";
end if;
Obj.Endpoint := -1;
end Delete_Endpoint;
end Nanomsg.Socket;
|
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Ada.Streams;
with Interfaces.C.Strings;
with Interfaces.C.Pointers;
with Nanomsg.Errors;
with System;
package body Nanomsg.Socket is
package C renames Interfaces.C;
use type C.Int;
function Is_Null (Obj : in Socket_T) return Boolean is (Obj.Fd = -1);
procedure Init (Obj : out Socket_T;
Domain : in Nanomsg.Domains.Domain_T;
Protocol : in Nanomsg.Protocols.Protocol_T
) is
function C_Nn_Socket (Domain : in C.Int; Protocol : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_socket";
begin
Obj.Fd := Integer (C_Nn_Socket (Nanomsg.Domains.To_C (Domain),
Nanomsg.Protocols.To_C (Protocol)));
if Obj.Fd < 0 then
raise Socket_Exception with "Init: " & Nanomsg.Errors.Errno_Text;
end if;
end Init;
procedure Close (Obj : in out Socket_T) is
function C_Nn_Close (Socket : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_close";
begin
Obj.Delete_Endpoint;
if C_Nn_Close (C.Int (Obj.Fd)) /= 0 then
raise Socket_Exception with "Close: " & Nanomsg.Errors.Errno_Text;
end if;
Obj.Fd := -1;
end Close;
procedure Bind (Obj : in Socket_T;
Address : in String) is
function C_Bind (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_bind";
Endpoint : C.Int := -1;
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Endpoint := C_Bind(C.Int (Obj.Fd), C_Address);
C.Strings.Free (C_Address);
if Endpoint < -1 then
raise Socket_Exception with "Bind: " & Nanomsg.Errors.Errno_Text;
end if;
-- FIXME
-- Add endpoints container
end Bind;
procedure Connect (Obj : in Socket_T;
Address : in String) is
function C_Connect (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_connect";
Endpoint : C.Int := -1;
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Endpoint := C_Connect(C.Int (Obj.Fd), C_Address) ;
C.Strings.Free (C_Address);
if Endpoint < 0 then
raise Socket_Exception with "Connect: " & Nanomsg.Errors.Errno_Text;
end if;
end Connect;
function Get_Fd (Obj : in Socket_T) return Integer is (Obj.Fd);
procedure Receive (Obj : in out Socket_T;
Message : out Nanomsg.Messages.Message_T) is
Payload : System.Address;
use type System.Address;
Received : Integer;
use type C.Size_T;
Flags : constant C.Int := 0;
Nn_Msg : constant C.Size_T := C.Size_T'Last;
function Nn_Recv (Socket : C.Int;
Buf_Access : out System.Address;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_recv";
function Free_Msg (Buf_Access :System.Address) return C.Int
with Import, Convention => C, External_Name => "nn_freemsg";
begin
Received := Integer (Nn_Recv (C.Int (Obj.Fd), Payload, Nn_Msg, Flags));
if Received < 0 then
raise Socket_Exception with "Receive: " & Nanomsg.Errors.Errno_Text;
end if;
Message.Set_Length (Received);
declare
Data : Ada.Streams.Stream_Element_Array (1 .. Ada.Streams.Stream_Element_Offset (Received));
for Data'Address use Payload;
begin
Message.Set_Payload (Data);
end;
if Free_Msg (Payload) < 0 then
raise Socket_Exception with "Deallocation failed";
end if;
end Receive;
procedure Send (Obj : in Socket_T; Message : Nanomsg.Messages.Message_T) is
Flags : C.Int := 0;
function Nn_Send (Socket : C.Int;
Buf_Access : Ada.Streams.Stream_Element_Array;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_send";
Sent : Integer;
begin
Sent := Integer (Nn_Send (C.Int (Obj.Fd),
Message.Get_Payload.all,
C.Size_T (Message.Get_Length),
Flags));
if Sent < 0 then
raise Socket_Exception with "Send: " & Nanomsg.Errors.Errno_Text;
end if;
if Sent /= Message.Get_Length then
raise Socket_Exception with "Send/Receive count doesn't match";
end if;
end Send;
procedure Delete_Endpoint (Obj : in out Socket_T) is
function Nn_Shutdown (Socket : C.Int;
Endpoint : C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_shutdown";
begin
if Nn_Shutdown (C.Int (Obj.Fd), C.Int (Obj.Endpoint)) < 0 then
raise Socket_Exception with "Shutdown Error";
end if;
Obj.Endpoint := -1;
end Delete_Endpoint;
end Nanomsg.Socket;
|
Fix typo in nn_shutdown
|
Fix typo in nn_shutdown
|
Ada
|
mit
|
landgraf/nanomsg-ada
|
0e65f325d527466f514412be2023e9e3bb5fa641
|
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;
directory_list : entry_crate.Map;
dossier_list : entry_crate.Map;
begin
LOG.log_phase_begin (log_handle, phase_name);
TIO.Put_Line (log_handle, "====> Checking for package manifest issues");
if not ingest_manifests (specification => specification,
log_handle => log_handle,
directory_list => directory_list,
dossier_list => dossier_list,
seq_id => seq_id,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if orphaned_directories_detected (log_handle => log_handle,
directory_list => directory_list,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if missing_directories_detected (log_handle, directory_list) then
passed_check := False;
end if;
if orphaned_files_detected (log_handle, dossier_list, namebase, rootdir) then
passed_check := False;
end if;
if missing_files_detected (log_handle, dossier_list) then
passed_check := False;
end if;
if passed_check then
TIO.Put_Line (log_handle, "====> No manifest issues found");
end if;
LOG.log_phase_end (log_handle);
return passed_check;
end exec_check_plist;
--------------------------------------------------------------------------------------------
-- ingest_manifests
--------------------------------------------------------------------------------------------
function ingest_manifests
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
dossier_list : in out entry_crate.Map;
seq_id : port_id;
namebase : String;
rootdir : String) return Boolean
is
procedure eat_plist (position : subpackage_crate.Cursor);
procedure insert_directory (directory : String; subpackage : HT.Text);
result : Boolean := True;
procedure insert_directory (directory : String; subpackage : HT.Text)
is
numsep : Natural := HT.count_char (directory, LAT.Solidus);
canvas : HT.Text := HT.SUS (directory);
begin
for x in 1 .. numsep + 1 loop
declare
paint : String := HT.USS (canvas);
my_new_rec : entry_record := (subpackage, False);
begin
if paint /= "" then
if not directory_list.Contains (canvas) then
directory_list.Insert (canvas, my_new_rec);
end if;
canvas := HT.SUS (HT.head (paint, "/"));
end if;
end;
end loop;
end insert_directory;
procedure eat_plist (position : subpackage_crate.Cursor)
is
subpackage : HT.Text := subpackage_crate.Element (position).subpackage;
manifest_file : String := "/construction/" & namebase & "/.manifest." &
HT.USS (subpackage) & ".mktmp";
contents : String := FOP.get_file_contents (rootdir & manifest_file);
identifier : constant String := HT.USS (subpackage) & " manifest: ";
markers : HT.Line_Markers;
begin
HT.initialize_markers (contents, markers);
loop
exit when not HT.next_line_present (contents, markers);
declare
line : constant String := HT.extract_line (contents, markers);
line_text : HT.Text := HT.SUS (line);
new_rec : entry_record := (subpackage, False);
begin
if HT.leads (line, "@comment ") then
null;
elsif 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 (directory_list.Element (dir_text).subpackage);
begin
if spkg /= "" then
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by the " & spkg & " manifest");
else
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by another manifest");
end if;
end;
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;
directory_list : in out entry_crate.Map;
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;
directory_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_dir : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"Directory " & plist_dir & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
directory_list.Iterate (check'Access);
return result;
end missing_directories_detected;
--------------------------------------------------------------------------------------------
-- missing_files_detected
--------------------------------------------------------------------------------------------
function missing_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_file : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"File " & plist_file & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
dossier_list.Iterate (check'Access);
return result;
end missing_files_detected;
--------------------------------------------------------------------------------------------
-- orphaned_files_detected
--------------------------------------------------------------------------------------------
function orphaned_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map;
namebase : String;
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;
directory_list : entry_crate.Map;
dossier_list : entry_crate.Map;
begin
LOG.log_phase_begin (log_handle, phase_name);
TIO.Put_Line (log_handle, "====> Checking for package manifest issues");
if not ingest_manifests (specification => specification,
log_handle => log_handle,
directory_list => directory_list,
dossier_list => dossier_list,
seq_id => seq_id,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if orphaned_directories_detected (log_handle => log_handle,
directory_list => directory_list,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if missing_directories_detected (log_handle, directory_list) then
passed_check := False;
end if;
if orphaned_files_detected (log_handle, dossier_list, namebase, rootdir) then
passed_check := False;
end if;
if missing_files_detected (log_handle, dossier_list) then
passed_check := False;
end if;
if passed_check then
TIO.Put_Line (log_handle, "====> No manifest issues found");
end if;
LOG.log_phase_end (log_handle);
return passed_check;
end exec_check_plist;
--------------------------------------------------------------------------------------------
-- ingest_manifests
--------------------------------------------------------------------------------------------
function ingest_manifests
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
dossier_list : in out entry_crate.Map;
seq_id : port_id;
namebase : String;
rootdir : String) return Boolean
is
procedure eat_plist (position : subpackage_crate.Cursor);
procedure insert_directory (directory : String; subpackage : HT.Text);
result : Boolean := True;
procedure insert_directory (directory : String; subpackage : HT.Text)
is
numsep : Natural := HT.count_char (directory, LAT.Solidus);
canvas : HT.Text := HT.SUS (directory);
begin
for x in 1 .. numsep + 1 loop
declare
paint : String := HT.USS (canvas);
my_new_rec : entry_record := (subpackage, False);
begin
if paint /= "" then
if not directory_list.Contains (canvas) then
directory_list.Insert (canvas, my_new_rec);
end if;
canvas := HT.SUS (HT.head (paint, "/"));
end if;
end;
end loop;
end insert_directory;
procedure eat_plist (position : subpackage_crate.Cursor)
is
subpackage : HT.Text := subpackage_crate.Element (position).subpackage;
manifest_file : String := "/construction/" & namebase & "/.manifest." &
HT.USS (subpackage) & ".mktmp";
contents : String := FOP.get_file_contents (rootdir & manifest_file);
identifier : constant String := HT.USS (subpackage) & " manifest: ";
markers : HT.Line_Markers;
begin
HT.initialize_markers (contents, markers);
loop
exit when not HT.next_line_present (contents, markers);
declare
line : constant String := HT.extract_line (contents, markers);
line_text : HT.Text := HT.SUS (line);
new_rec : entry_record := (subpackage, False);
begin
if HT.leads (line, "@comment ") then
null;
elsif HT.leads (line, "@terminfo") then
null;
elsif 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 (directory_list.Element (dir_text).subpackage);
begin
if spkg /= "" then
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by the " & spkg & " manifest");
else
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by another manifest");
end if;
end;
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;
directory_list : in out entry_crate.Map;
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;
directory_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_dir : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"Directory " & plist_dir & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
directory_list.Iterate (check'Access);
return result;
end missing_directories_detected;
--------------------------------------------------------------------------------------------
-- missing_files_detected
--------------------------------------------------------------------------------------------
function missing_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_file : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"File " & plist_file & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
dossier_list.Iterate (check'Access);
return result;
end missing_files_detected;
--------------------------------------------------------------------------------------------
-- orphaned_files_detected
--------------------------------------------------------------------------------------------
function orphaned_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map;
namebase : String;
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;
|
exclude @terminfo keyword from check-plist
|
exclude @terminfo keyword from check-plist
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
8246b1faff45536d0dc112887f69d8a2e1a0f331
|
src/util-properties-bundles.adb
|
src/util-properties-bundles.adb
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
package body Util.Properties.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String,
Util.Strings.String_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value);
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value);
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access);
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count + 1;
else
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end if;
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Natural := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Bundle.Impl.Count := Bundle.Impl.Count + 1;
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward);
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
Path : constant String := To_String (Factory.Path);
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Pattern : constant String := Name & "*.properties";
Ent : Directory_Entry_Type;
Names : Util.Strings.String_Set.Set;
Search : Search_Type;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Start_Search (Search, Directory => Path,
Pattern => Pattern, Filter => Filter);
Factory.Lock.Write;
begin
-- Scan the directory and load all the property files.
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Bundle : constant Bundle_Manager_Access := new Manager;
Bundle_Name : constant Name_Access
:= new String '(Simple (Simple'First .. Simple'Last - 11));
begin
Log.Debug ("Loading file {0}", File_Path);
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Found := True;
Names.Insert (Bundle_Name);
end;
end loop;
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in Value)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
-- ------------------------------
-- Returns the property value. Raises an exception if not found.
-- ------------------------------
function Get (Self : in Manager; Name : in Value)
return Value is
begin
return Self.Props.Get (Name);
exception
when NO_PROPERTY =>
declare
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
begin
return Element (Iter).all.Get (Name);
exception
when NO_PROPERTY =>
Iter := Next (Iter);
end;
end loop;
end;
raise;
end Get;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
procedure Insert (Self : in out Manager;
Name : in Value;
Item : in Value) is
pragma Unreferenced (Self);
pragma Unreferenced (Name);
pragma Unreferenced (Item);
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager;
Name : in Value;
Item : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager; Name : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access) is
pragma Unreferenced (Self);
Item : Manager_Object_Access := Manager (Obj.all)'Access;
begin
Free (Item);
end Delete;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is
Result : Name_Array (1 .. 2);
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
declare
N : constant Name_Array := Element (Iter).Get_Names (Prefix);
begin
return N;
end;
Iter := Next (Iter);
end loop;
return Result;
end Get_Names;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Util.Strings.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Util.Strings.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
package body Util.Properties.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String,
Util.Strings.String_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Object_Access is access all Manager;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value);
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value);
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access);
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
use type Util.Properties.Manager_Access;
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Manager,
Manager_Object_Access);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
use type Util.Properties.Interface_P.Manager_Access;
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count + 1;
else
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Object.Impl.Count := 1;
end if;
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
use type Util.Properties.Manager_Access;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Natural := Loc_Name'Last;
begin
Log.Info ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Bundle.Impl.Count := Bundle.Impl.Count + 1;
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward);
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
Path : constant String := To_String (Factory.Path);
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Pattern : constant String := Name & "*.properties";
Ent : Directory_Entry_Type;
Names : Util.Strings.String_Set.Set;
Search : Search_Type;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Start_Search (Search, Directory => Path,
Pattern => Pattern, Filter => Filter);
Factory.Lock.Write;
begin
-- Scan the directory and load all the property files.
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Bundle : constant Bundle_Manager_Access := new Manager;
Bundle_Name : constant Name_Access
:= new String '(Simple (Simple'First .. Simple'Last - 11));
begin
Log.Debug ("Loading file {0}", File_Path);
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Found := True;
Names.Insert (Bundle_Name);
end;
end loop;
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in Value)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
-- ------------------------------
-- Returns the property value. Raises an exception if not found.
-- ------------------------------
function Get (Self : in Manager; Name : in Value)
return Value is
begin
return Self.Props.Get (Name);
exception
when NO_PROPERTY =>
declare
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
begin
return Element (Iter).all.Get (Name);
exception
when NO_PROPERTY =>
Iter := Next (Iter);
end;
end loop;
end;
raise;
end Get;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
procedure Insert (Self : in out Manager;
Name : in Value;
Item : in Value) is
pragma Unreferenced (Self);
pragma Unreferenced (Name);
pragma Unreferenced (Item);
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager;
Name : in Value;
Item : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager; Name : in Value) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Delete (Self : in Manager;
Obj : in out Util.Properties.Interface_P.Manager_Access) is
pragma Unreferenced (Self);
Item : Manager_Object_Access := Manager (Obj.all)'Access;
begin
Free (Item);
end Delete;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is
Result : Name_Array (1 .. 2);
Iter : Cursor := Self.List.First;
begin
while Has_Element (Iter) loop
declare
M : constant Util.Properties.Manager_Access := Element (Iter);
N : constant Name_Array := M.Get_Names (Prefix);
begin
return N;
end;
Iter := Next (Iter);
end loop;
return Result;
end Get_Names;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Util.Strings.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Util.Strings.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
Fix compilation with gcc 4.4.1
|
Fix compilation with gcc 4.4.1
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
19dab4f498ae06fd2b5d7d72011bb84ba6fe69e3
|
regtests/util-properties-tests.adb
|
regtests/util-properties-tests.adb
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
use Util;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
end Add_Tests;
end Util.Properties.Tests;
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
use Util;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
end Add_Tests;
end Util.Properties.Tests;
|
Implement the Test_Load_Ini_Procedure and register the new test
|
Implement the Test_Load_Ini_Procedure and register the new test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f9b2e97b4e9f0119ab3b411726904c5ddd42d30a
|
src/natools-web-string_tables.adb
|
src/natools-web-string_tables.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Web.String_Tables is
------------------
-- Constructors --
------------------
not overriding function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return String_Table is
begin
return String_Table'(Ref => Create (Expression));
end Create;
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Table_References.Immutable_Reference
is
pragma Unreferenced (Expression);
begin
raise Program_Error with "Not implemented yet";
return Table_References.Null_Immutable_Reference;
end Create;
---------------
-- Renderers --
---------------
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in String_Table;
Expression : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Exchange);
pragma Unreferenced (Object);
pragma Unreferenced (Expression);
begin
raise Program_Error with "Not implemented yet";
end Render;
end Natools.Web.String_Tables;
|
------------------------------------------------------------------------------
-- Copyright (c) 2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Containers.Doubly_Linked_Lists;
package body Natools.Web.String_Tables is
package Row_Lists is new Ada.Containers.Doubly_Linked_Lists
(Containers.Atom_Array_Refs.Immutable_Reference,
Containers.Atom_Array_Refs."=");
------------------
-- Constructors --
------------------
not overriding function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return String_Table is
begin
return String_Table'(Ref => Create (Expression));
end Create;
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Table_References.Immutable_Reference
is
List : 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 (Containers.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;
if Row_Lists.Is_Empty (List) then
return Table_References.Null_Immutable_Reference;
end if;
Build_Table :
declare
Data : constant Table_References.Data_Access
:= new Table (1 .. S_Expressions.Count (Row_Lists.Length (List)));
Ref : constant Table_References.Immutable_Reference
:= Table_References.Create (Data);
Cursor : Row_Lists.Cursor := Row_Lists.First (List);
begin
for I in Data.all'Range loop
Data (I) := Row_Lists.Element (Cursor);
Row_Lists.Next (Cursor);
end loop;
pragma Assert (not Row_Lists.Has_Element (Cursor));
return Ref;
end Build_Table;
end Create;
---------------
-- Renderers --
---------------
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in String_Table;
Expression : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Exchange);
pragma Unreferenced (Object);
pragma Unreferenced (Expression);
begin
raise Program_Error with "Not implemented yet";
end Render;
end Natools.Web.String_Tables;
|
implement table construction from S-expression
|
string_tables: implement table construction from S-expression
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
e45b268f5a18b423078db17742a71f738b9891a9
|
awa/src/awa-applications.adb
|
awa/src/awa-applications.adb
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- 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 AWA.Modules;
package body AWA.Applications is
-- ------------------------------
-- Initialize the application
-- ------------------------------
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in ASF.Applications.Main.Application_Factory'Class) is
URI : constant String := Conf.Get ("database");
begin
ASF.Applications.Main.Application (App).Initialize (Conf, Factory);
App.Factory.Create (URI);
end Initialize;
-- ------------------------------
-- 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'Access, Name, URI);
Module.Initialize (App);
end Register;
-- ------------------------------
-- Get the database connection for reading
-- ------------------------------
function Get_Session (App : Application)
return ADO.Sessions.Session is
begin
return App.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.Factory.Get_Master_Session;
end Get_Master_Session;
end AWA.Applications;
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- 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 AWA.Modules;
package body AWA.Applications is
-- ------------------------------
-- Initialize the application
-- ------------------------------
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in ASF.Applications.Main.Application_Factory'Class) is
URI : constant String := Conf.Get ("database");
begin
ASF.Applications.Main.Application (App).Initialize (Conf, Factory);
App.Factory.Create (URI);
end Initialize;
-- ------------------------------
-- 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
Module.Initialize (App);
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.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.Factory.Get_Master_Session;
end Get_Master_Session;
end AWA.Applications;
|
Fix initialization of the AWA application
|
Fix initialization of the AWA application
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
529bd69c0f5bc8a725968df7ab1090370c97f4b5
|
awa/src/aws/awa-mail-clients-aws_smtp.adb
|
awa/src/aws/awa-mail-clients-aws_smtp.adb
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with AWS.SMTP.Client;
with Util.Log.Loggers;
package body AWA.Mail.Clients.AWS_SMTP is
use Ada.Strings.Unbounded;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP");
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients,
Name => Recipients_Access);
-- ------------------------------
-- Set the <tt>From</tt> part of the message.
-- ------------------------------
overriding
procedure Set_From (Message : in out AWS_Mail_Message;
Name : in String;
Address : in String) is
begin
Message.From := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Set_From;
-- ------------------------------
-- Add a recipient for the message.
-- ------------------------------
overriding
procedure Add_Recipient (Message : in out AWS_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is
begin
if Message.To = null then
Message.To := new AWS.SMTP.Recipients (1 .. 1);
else
declare
To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1);
begin
To (Message.To'Range) := Message.To.all;
Free (Message.To);
Message.To := To;
end;
end if;
Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Add_Recipient;
-- ------------------------------
-- Set the subject of the message.
-- ------------------------------
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String) is
begin
Message.Subject := To_Unbounded_String (Subject);
end Set_Subject;
-- ------------------------------
-- Set the body of the message.
-- ------------------------------
overriding
procedure Set_Body (Message : in out AWS_Mail_Message;
Content : in String) is
begin
Message.Content := To_Unbounded_String (Content);
end Set_Body;
-- ------------------------------
-- Send the email message.
-- ------------------------------
overriding
procedure Send (Message : in out AWS_Mail_Message) is
Result : AWS.SMTP.Status;
begin
if Message.To = null then
return;
end if;
if Message.Manager.Enable then
Log.Info ("Send email to {0}", "");
AWS.SMTP.Client.Send (Server => Message.Manager.Server,
From => Message.From,
To => Message.To.all,
Subject => To_String (Message.Subject),
Message => To_String (Message.Content),
Status => Result);
else
Log.Info ("Disable send email to {0}", "");
end if;
end Send;
-- ------------------------------
-- Deletes the mail message.
-- ------------------------------
overriding
procedure Finalize (Message : in out AWS_Mail_Message) is
begin
Log.Info ("Finalize mail message");
Free (Message.To);
end Finalize;
-- ------------------------------
-- Create a SMTP based mail manager and configure it according to the properties.
-- ------------------------------
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is
Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost");
Port : constant String := Props.Get (Name => "smtp.port", Default => "25");
Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1");
Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager;
begin
Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port);
Result.Self := Result;
Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true";
Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server,
Port => Positive'Value (Port));
return Result.all'Access;
end Create_Manager;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is
Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message;
begin
Result.Manager := Manager.Self;
return Result.all'Access;
end Create_Message;
end AWA.Mail.Clients.AWS_SMTP;
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with AWS.SMTP.Client;
with Util.Log.Loggers;
package body AWA.Mail.Clients.AWS_SMTP is
use Ada.Strings.Unbounded;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP");
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients,
Name => Recipients_Access);
-- ------------------------------
-- Set the <tt>From</tt> part of the message.
-- ------------------------------
overriding
procedure Set_From (Message : in out AWS_Mail_Message;
Name : in String;
Address : in String) is
begin
Message.From := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Set_From;
-- ------------------------------
-- Add a recipient for the message.
-- ------------------------------
overriding
procedure Add_Recipient (Message : in out AWS_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is
pragma Unreferenced (Kind);
begin
if Message.To = null then
Message.To := new AWS.SMTP.Recipients (1 .. 1);
else
declare
To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1);
begin
To (Message.To'Range) := Message.To.all;
Free (Message.To);
Message.To := To;
end;
end if;
Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Add_Recipient;
-- ------------------------------
-- Set the subject of the message.
-- ------------------------------
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String) is
begin
Message.Subject := To_Unbounded_String (Subject);
end Set_Subject;
-- ------------------------------
-- Set the body of the message.
-- ------------------------------
overriding
procedure Set_Body (Message : in out AWS_Mail_Message;
Content : in String) is
begin
Message.Content := To_Unbounded_String (Content);
end Set_Body;
-- ------------------------------
-- Send the email message.
-- ------------------------------
overriding
procedure Send (Message : in out AWS_Mail_Message) is
Result : AWS.SMTP.Status;
begin
if Message.To = null then
return;
end if;
if Message.Manager.Enable then
Log.Info ("Send email to {0}", "");
AWS.SMTP.Client.Send (Server => Message.Manager.Server,
From => Message.From,
To => Message.To.all,
Subject => To_String (Message.Subject),
Message => To_String (Message.Content),
Status => Result);
else
Log.Info ("Disable send email to {0}", "");
end if;
end Send;
-- ------------------------------
-- Deletes the mail message.
-- ------------------------------
overriding
procedure Finalize (Message : in out AWS_Mail_Message) is
begin
Log.Info ("Finalize mail message");
Free (Message.To);
end Finalize;
-- ------------------------------
-- Create a SMTP based mail manager and configure it according to the properties.
-- ------------------------------
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is
Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost");
Port : constant String := Props.Get (Name => "smtp.port", Default => "25");
Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1");
Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager;
begin
Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port);
Result.Self := Result;
Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true";
Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server,
Port => Positive'Value (Port));
return Result.all'Access;
end Create_Manager;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is
Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message;
begin
Result.Manager := Manager.Self;
return Result.all'Access;
end Create_Message;
end AWA.Mail.Clients.AWS_SMTP;
|
Fix compilation warning, ignore Kind parameter
|
Fix compilation warning, ignore Kind parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
992362b86359c8776748dc243418ebd37e3feebc
|
ARM/STM32/drivers/dma2d/stm32-dma2d-polling.adb
|
ARM/STM32/drivers/dma2d/stm32-dma2d-polling.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of 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 STM32_SVD.DMA2D; use STM32_SVD.DMA2D;
package body STM32.DMA2D.Polling is
Transferring : Boolean := False;
procedure DMA2D_Init_Transfer;
procedure DMA2D_Wait_Transfer;
---------------------------
-- DMA2D_InitAndTransfer --
---------------------------
procedure DMA2D_Init_Transfer
is
begin
Transferring := True;
DMA2D_Periph.IFCR.CTCIF := True;
DMA2D_Periph.IFCR.CCTCIF := True;
DMA2D_Periph.CR.START := True;
end DMA2D_Init_Transfer;
-------------------------
-- DMA2D_Wait_Transfer --
-------------------------
procedure DMA2D_Wait_Transfer is
begin
if not Transferring then
return;
end if;
Transferring := False;
if DMA2D_Periph.ISR.CEIF then -- Conf error
raise Constraint_Error with "DMA2D Configuration error";
elsif DMA2D_Periph.ISR.TEIF then -- Transfer error
raise Constraint_Error with "DMA2D Transfer error";
else
while not DMA2D_Periph.ISR.TCIF loop -- Transfer completed
if DMA2D_Periph.ISR.TEIF then
raise Constraint_Error with "DMA2D Transfer error";
end if;
end loop;
DMA2D_Periph.IFCR.CTCIF := True; -- Clear the TCIF flag
end if;
end DMA2D_Wait_Transfer;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
STM32.DMA2D.DMA2D_Init
(Init => DMA2D_Init_Transfer'Access,
Wait => DMA2D_Wait_Transfer'Access);
end Initialize;
end STM32.DMA2D.Polling;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of 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 STM32_SVD.DMA2D; use STM32_SVD.DMA2D;
package body STM32.DMA2D.Polling is
Transferring : Boolean := False;
procedure DMA2D_Init_Transfer;
procedure DMA2D_Wait_Transfer;
---------------------------
-- DMA2D_InitAndTransfer --
---------------------------
procedure DMA2D_Init_Transfer
is
begin
Transferring := True;
DMA2D_Periph.IFCR.CTCIF := True;
DMA2D_Periph.IFCR.CCTCIF := True;
DMA2D_Periph.CR.START := True;
end DMA2D_Init_Transfer;
-------------------------
-- DMA2D_Wait_Transfer --
-------------------------
procedure DMA2D_Wait_Transfer is
begin
if not Transferring then
return;
end if;
if DMA2D_Periph.ISR.CEIF then -- Conf error
Transferring := False;
raise Constraint_Error with "DMA2D Configuration error";
elsif DMA2D_Periph.ISR.TEIF then -- Transfer error
Transferring := False;
raise Constraint_Error with "DMA2D Transfer error";
else
while not DMA2D_Periph.ISR.TCIF loop -- Transfer completed
if DMA2D_Periph.ISR.TEIF then
Transferring := False;
raise Constraint_Error with "DMA2D Transfer error";
end if;
end loop;
DMA2D_Periph.IFCR.CTCIF := True; -- Clear the TCIF flag
Transferring := False;
end if;
end DMA2D_Wait_Transfer;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
STM32.DMA2D.DMA2D_Init
(Init => DMA2D_Init_Transfer'Access,
Wait => DMA2D_Wait_Transfer'Access);
end Initialize;
end STM32.DMA2D.Polling;
|
make sure the Transferring flag is reset only after IRQ ack
|
STM32.DMA2D: make sure the Transferring flag is reset only after IRQ ack
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library
|
48aae336ded775ad9562d34a235c3346f9269c8b
|
src/ado-queries-loaders.adb
|
src/ado-queries-loaders.adb
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
Last_Query : Query_Index := 0;
Last_File : File_Index := 0;
-- Convert a Time to an Unsigned_32.
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32;
pragma Inline_Always (To_Unsigned_32);
-- Get the modification time of the XML query file associated with the query.
function Modification_Time (File : in Query_File_Info) return Unsigned_32;
-- Initialize the query SQL pattern with the value
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Register the query definition in the query file. Registration is done
-- in the package elaboration phase.
-- ------------------------------
procedure Register (File : in Query_File_Access;
Query : in Query_Definition_Access) is
begin
Last_Query := Last_Query + 1;
Query.File := File;
Query.Next := File.Queries;
Query.Query := Last_Query;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
Last_File := Last_File + 1;
File.Next := Query_Files;
File.File := Last_File;
Query_Files := File;
end if;
end Register;
function Find_Driver (Name : in String) return Integer;
function Find_Driver (Name : in String) return Integer is
begin
if Name'Length = 0 then
return 0;
end if;
declare
Driver : constant Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (File : in Query_File_Info) return Unsigned_32 is
Path : constant String := To_String (File.Path);
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Path));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Path);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (File : in out Query_File_Info) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (File);
begin
if File.Last_Modified = M then
return False;
end if;
File.Last_Modified := M;
return True;
end;
end Is_Modified;
-- ------------------------------
-- Initialize the query SQL pattern with the value
-- ------------------------------
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object) is
begin
Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value);
end Set_Query_Pattern;
procedure Read_Query (Manager : in Query_Manager;
File : in out Query_File_Info) is
type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE,
FIELD_PROPERTY_NAME, FIELD_QUERY_NAME,
FIELD_SQL_DRIVER,
FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY);
-- The Query_Loader holds context and state information for loading
-- the XML query file and initializing the Query_Definition.
type Query_Loader is record
-- File : Query_File_Access;
Hash_Value : Unbounded_String;
Query_Def : Query_Definition_Access;
Query : Query_Info_Ref.Ref;
Driver : Integer;
end record;
type Query_Loader_Access is access all Query_Loader;
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object) is
use ADO.Drivers;
begin
case Field is
when FIELD_CLASS_NAME =>
Append (Into.Hash_Value, " class=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_TYPE =>
Append (Into.Hash_Value, " type=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_NAME =>
Append (Into.Hash_Value, " name=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_QUERY_NAME =>
Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
if Into.Query_Def /= null then
Into.Query := Query_Info_Ref.Create;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_QUERY =>
if Into.Query_Def /= null then
-- Now we can safely setup the query info associated with the query definition.
Manager.Queries (Into.Query_Def.Query) := Into.Query;
end if;
Into.Query_Def := null;
end case;
end Set_Member;
package Query_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader,
Element_Type_Access => Query_Loader_Access,
Fields => Query_Info_Fields,
Set_Member => Set_Member);
Loader : aliased Query_Loader;
Sql_Mapper : aliased Query_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
Mapper : Util.Serialize.Mappers.Processing;
Path : constant String := To_String (File.Path);
begin
Log.Info ("Reading XML query {0}", Path);
-- Loader.File := Into;
Loader.Driver := 0;
-- Create the mapping to load the XML query file.
Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME);
Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE);
Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME);
Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME);
Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL);
Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT);
Sql_Mapper.Add_Mapping ("query", FIELD_QUERY);
Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Mapper, Loader'Access);
-- Read the XML query file.
Reader.Parse (Path, Mapper);
File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Path);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Manager : in Query_Manager;
Into : in Query_Definition_Access) is
begin
if Manager.Queries (Into.Query).Is_Null
or else Is_Modified (Manager.Files (Into.File.File))
then
Read_Query (Manager, Manager.Files (Into.File.File));
end if;
end Read_Query;
-- ------------------------------
-- Initialize the queries to look in the list of directories specified by <b>Paths</b>.
-- Each search directory is separated by ';' (yes, even on Unix).
-- When <b>Load</b> is true, read the XML query file and initialize the query
-- definitions from that file.
-- ------------------------------
procedure Initialize (Manager : in out Query_Manager;
Config : in ADO.Drivers.Connections.Configuration'Class) is
Paths : constant String := Config.Get_Property ("ado.queries.paths");
Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true";
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
if Manager.Queries = null then
Manager.Queries := new Query_Table (1 .. Last_Query);
end if;
if Manager.Files = null then
Manager.Files := new File_Table (1 .. Last_File);
end if;
Manager.Driver := Config.Get_Driver;
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all,
Paths => Paths);
begin
Manager.Files (File.File).File := File;
Manager.Files (File.File).Last_Modified := 0;
Manager.Files (File.File).Next_Check := 0;
Manager.Files (File.File).Path := To_Unbounded_String (Path);
if Load then
Read_Query (Manager, Manager.Files (File.File));
end if;
end;
File := File.Next;
end loop;
end Initialize;
-- ------------------------------
-- Find the query identified by the given name.
-- ------------------------------
function Find_Query (Name : in String) return Query_Definition_Access is
File : Query_File_Access := Query_Files;
begin
while File /= null loop
declare
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
end;
File := File.Next;
end loop;
Log.Warn ("Query {0} not found", Name);
return null;
end Find_Query;
package body File is
begin
File.Name := Name'Access;
File.Sha1_Map := Hash'Access;
end File;
package body Query is
begin
Query.Name := Query_Name'Access;
Query.File := File;
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
Last_Query : Query_Index := 0;
Last_File : File_Index := 0;
-- Convert a Time to an Unsigned_32.
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32;
pragma Inline_Always (To_Unsigned_32);
-- Get the modification time of the XML query file associated with the query.
function Modification_Time (File : in Query_File_Info) return Unsigned_32;
-- Initialize the query SQL pattern with the value
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Register the query definition in the query file. Registration is done
-- in the package elaboration phase.
-- ------------------------------
procedure Register (File : in Query_File_Access;
Query : in Query_Definition_Access) is
begin
Last_Query := Last_Query + 1;
Query.File := File;
Query.Next := File.Queries;
Query.Query := Last_Query;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
Last_File := Last_File + 1;
File.Next := Query_Files;
File.File := Last_File;
Query_Files := File;
end if;
end Register;
function Find_Driver (Name : in String) return Integer;
function Find_Driver (Name : in String) return Integer is
begin
if Name'Length = 0 then
return 0;
end if;
declare
Driver : constant Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (File : in Query_File_Info) return Unsigned_32 is
Path : constant String := To_String (File.Path);
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Path));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Path);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (File : in out Query_File_Info) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (File);
begin
if File.Last_Modified = M then
return False;
end if;
File.Last_Modified := M;
return True;
end;
end Is_Modified;
-- ------------------------------
-- Initialize the query SQL pattern with the value
-- ------------------------------
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object) is
begin
Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value);
end Set_Query_Pattern;
procedure Read_Query (Manager : in Query_Manager;
File : in out Query_File_Info) is
type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE,
FIELD_PROPERTY_NAME, FIELD_QUERY_NAME,
FIELD_SQL_DRIVER,
FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY);
-- The Query_Loader holds context and state information for loading
-- the XML query file and initializing the Query_Definition.
type Query_Loader is record
-- File : Query_File_Access;
Hash_Value : Unbounded_String;
Query_Def : Query_Definition_Access;
Query : Query_Info_Ref.Ref;
Driver : Integer;
end record;
type Query_Loader_Access is access all Query_Loader;
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object) is
use ADO.Drivers;
begin
case Field is
when FIELD_CLASS_NAME =>
Append (Into.Hash_Value, " class=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_TYPE =>
Append (Into.Hash_Value, " type=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_NAME =>
Append (Into.Hash_Value, " name=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_QUERY_NAME =>
Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
if Into.Query_Def /= null then
Into.Query := Query_Info_Ref.Create;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_QUERY =>
if Into.Query_Def /= null then
-- Now we can safely setup the query info associated with the query definition.
Manager.Queries (Into.Query_Def.Query) := Into.Query;
end if;
Into.Query_Def := null;
end case;
end Set_Member;
package Query_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader,
Element_Type_Access => Query_Loader_Access,
Fields => Query_Info_Fields,
Set_Member => Set_Member);
Loader : aliased Query_Loader;
Sql_Mapper : aliased Query_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
Mapper : Util.Serialize.Mappers.Processing;
Path : constant String := To_String (File.Path);
begin
Log.Info ("Reading XML query {0}", Path);
-- Loader.File := Into;
Loader.Driver := 0;
-- Create the mapping to load the XML query file.
Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME);
Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE);
Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME);
Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME);
Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL);
Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT);
Sql_Mapper.Add_Mapping ("query/sql-count/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query", FIELD_QUERY);
Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Mapper, Loader'Access);
-- Read the XML query file.
Reader.Parse (Path, Mapper);
File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Path);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Manager : in Query_Manager;
Into : in Query_Definition_Access) is
begin
if Manager.Queries (Into.Query).Is_Null
or else Is_Modified (Manager.Files (Into.File.File))
then
Read_Query (Manager, Manager.Files (Into.File.File));
end if;
end Read_Query;
-- ------------------------------
-- Initialize the queries to look in the list of directories specified by <b>Paths</b>.
-- Each search directory is separated by ';' (yes, even on Unix).
-- When <b>Load</b> is true, read the XML query file and initialize the query
-- definitions from that file.
-- ------------------------------
procedure Initialize (Manager : in out Query_Manager;
Config : in ADO.Drivers.Connections.Configuration'Class) is
Paths : constant String := Config.Get_Property ("ado.queries.paths");
Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true";
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
if Manager.Queries = null then
Manager.Queries := new Query_Table (1 .. Last_Query);
end if;
if Manager.Files = null then
Manager.Files := new File_Table (1 .. Last_File);
end if;
Manager.Driver := Config.Get_Driver;
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all,
Paths => Paths);
begin
Manager.Files (File.File).File := File;
Manager.Files (File.File).Last_Modified := 0;
Manager.Files (File.File).Next_Check := 0;
Manager.Files (File.File).Path := To_Unbounded_String (Path);
if Load then
Read_Query (Manager, Manager.Files (File.File));
end if;
end;
File := File.Next;
end loop;
end Initialize;
-- ------------------------------
-- Find the query identified by the given name.
-- ------------------------------
function Find_Query (Name : in String) return Query_Definition_Access is
File : Query_File_Access := Query_Files;
begin
while File /= null loop
declare
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
end;
File := File.Next;
end loop;
Log.Warn ("Query {0} not found", Name);
return null;
end Find_Query;
package body File is
begin
File.Name := Name'Access;
File.Sha1_Map := Hash'Access;
end File;
package body Query is
begin
Query.Name := Query_Name'Access;
Query.File := File;
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
Fix handling <sql-count driver=X> definitions
|
Fix handling <sql-count driver=X> definitions
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
211afb96186b42221d3e453e78b7aadae3a7d0a0
|
src/asf-views-nodes-jsf.adb
|
src/asf-views-nodes-jsf.adb
|
-----------------------------------------------------------------------
-- views.nodes.jsf -- JSF Core Tag Library
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Converters;
with ASF.Validators.Texts;
with ASF.Validators.Numbers;
with ASF.Components.Holders;
with ASF.Components.Core.Views;
package body ASF.Views.Nodes.Jsf is
use ASF;
use EL.Objects;
-- ------------------------------
-- Converter Tag
-- ------------------------------
-- ------------------------------
-- Create the Converter Tag
-- ------------------------------
function Create_Converter_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node;
Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"converterId");
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
if Conv = null then
Node.Error ("Missing 'converterId' attribute");
else
Node.Converter := EL.Objects.To_Object (Conv.Value);
end if;
return Node.all'Access;
end Create_Converter_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children. Get the specified converter and
-- add it to the parent component. This operation does not create any
-- new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Converter_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Converters.Converter_Access;
Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter);
begin
if not (Parent.all in Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Value_Holder");
return;
end if;
if Cvt = null then
Node.Error ("Converter was not found");
return;
end if;
declare
VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access;
begin
VH.Set_Converter (Converter => Cvt);
end;
end Build_Components;
-- ------------------------------
-- Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Validator Tag
-- ------------------------------
function Create_Validator_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node;
Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"validatorId");
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
if Vid = null then
Node.Error ("Missing 'validatorId' attribute");
else
Node.Validator := EL.Objects.To_Object (Vid.Value);
end if;
return Node.all'Access;
end Create_Validator_Tag_Node;
-- ------------------------------
-- Get the specified validator and add it to the parent component.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Validator_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Validators.Validator_Access;
V : Validators.Validator_Access;
Shared : Boolean;
begin
if not (Parent.all in Editable_Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Editable_Value_Holder");
return;
end if;
Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared);
if V = null then
Node.Error ("Validator was not found");
return;
end if;
declare
VH : constant access Editable_Value_Holder'Class
:= Editable_Value_Holder'Class (Parent.all)'Access;
begin
VH.Add_Validator (Validator => V, Shared => Shared);
end;
end Build_Components;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
procedure Get_Validator (Node : in Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
begin
Validator := Context.Get_Validator (Node.Validator);
Shared := True;
end Get_Validator;
-- ------------------------------
-- Range Validator Tag
-- ------------------------------
-- Create the Range_Validator Tag
function Create_Range_Validator_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Range_Validator_Tag_Node;
-- Get the validator instance that corresponds to the range validator.
-- Returns in <b>Validator</b> the validator instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
overriding
procedure Get_Validator (Node : in Range_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Long_Long_Integer := Long_Long_Integer'First;
Max : Long_Long_Integer := Long_Long_Integer'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context));
end if;
if Node.Maximum /= null then
Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max));
return;
end if;
Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Length Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Length_Validator Tag. Verifies that the XML node defines
-- the <b>minimum</b> or the <b>maximum</b> or both attributes.
-- ------------------------------
function Create_Length_Validator_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Length_Validator_Tag_Node;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
overriding
procedure Get_Validator (Node : in Length_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Natural := 0;
Max : Natural := Natural'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context)));
end if;
if Node.Maximum /= null then
Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context)));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Natural'Image (Min), Natural'Image (Max));
return;
end if;
Validator := Validators.Texts.Create_Length_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Attribute Tag
-- ------------------------------
-- ------------------------------
-- Create the Attribute Tag
-- ------------------------------
function Create_Attribute_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Attribute_Tag_Node_Access := new Attribute_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Attr_Name := Find_Attribute (Attributes, "name");
Node.Value := Find_Attribute (Attributes, "value");
if Node.Attr_Name = null then
Node.Error ("Missing 'name' attribute");
end if;
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
return Node.all'Access;
end Create_Attribute_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- Adds the attribute to the component node.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Attribute_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use EL.Expressions;
begin
if Node.Attr_Name /= null and Node.Value /= null then
declare
Name : constant EL.Objects.Object := Get_Value (Node.Attr_Name.all, Context);
begin
Node.Attr.Name := EL.Objects.To_Unbounded_String (Name);
if Node.Value.Binding /= null then
declare
Expr : constant EL.Expressions.Expression
:= ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context);
begin
Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr);
end;
else
Parent.Set_Attribute (Def => Node.Attr'Access,
Value => Get_Value (Node.Value.all, Context));
end if;
end;
end if;
end Build_Components;
-- ------------------------------
-- Facet Tag
-- ------------------------------
-- ------------------------------
-- Create the Facet Tag
-- ------------------------------
function Create_Facet_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Facet_Name := Find_Attribute (Attributes, "name");
if Node.Facet_Name = null then
Node.Error ("Missing 'name' attribute");
end if;
return Node.all'Access;
end Create_Facet_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the facet component of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Facet_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
begin
null;
end Build_Components;
-- ------------------------------
-- Metadata Tag
-- ------------------------------
-- ------------------------------
-- Create the Metadata Tag
-- ------------------------------
function Create_Metadata_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Metadata_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as a metadata information
-- facet for the UIView parent component.
-- ------------------------------
overriding
procedure Build_Components (Node : access Metadata_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Core.Views;
begin
if not (Parent.all in UIView'Class) then
Node.Error ("Parent component of <f:metadata> must be a <f:view>");
return;
end if;
declare
UI : constant UIViewMetaData_Access := new UIViewMetaData;
begin
UIView'Class (Parent.all).Set_Metadata (UI, Node);
Build_Attributes (UI.all, Node.all, Context);
UI.Initialize (UI.Get_Context.all);
Node.Build_Children (UI.all'Access, Context);
end;
end Build_Components;
end ASF.Views.Nodes.Jsf;
|
-----------------------------------------------------------------------
-- views.nodes.jsf -- JSF Core Tag Library
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Converters;
with ASF.Validators.Texts;
with ASF.Validators.Numbers;
with ASF.Components.Holders;
with ASF.Components.Core.Views;
package body ASF.Views.Nodes.Jsf is
use ASF;
use EL.Objects;
-- ------------------------------
-- Converter Tag
-- ------------------------------
-- ------------------------------
-- Create the Converter Tag
-- ------------------------------
function Create_Converter_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node;
Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"converterId");
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
if Conv = null then
Node.Error ("Missing 'converterId' attribute");
else
Node.Converter := EL.Objects.To_Object (Conv.Value);
end if;
return Node.all'Access;
end Create_Converter_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children. Get the specified converter and
-- add it to the parent component. This operation does not create any
-- new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Converter_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Converters.Converter_Access;
Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter);
begin
if not (Parent.all in Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Value_Holder");
return;
end if;
if Cvt = null then
Node.Error ("Converter was not found");
return;
end if;
declare
VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access;
begin
VH.Set_Converter (Converter => Cvt);
end;
end Build_Components;
-- ------------------------------
-- Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Validator Tag
-- ------------------------------
function Create_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node;
Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"validatorId");
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
if Vid = null then
Node.Error ("Missing 'validatorId' attribute");
else
Node.Validator := EL.Objects.To_Object (Vid.Value);
end if;
return Node.all'Access;
end Create_Validator_Tag_Node;
-- ------------------------------
-- Get the specified validator and add it to the parent component.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Validator_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Validators.Validator_Access;
V : Validators.Validator_Access;
Shared : Boolean;
begin
if not (Parent.all in Editable_Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Editable_Value_Holder");
return;
end if;
Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared);
if V = null then
Node.Error ("Validator was not found");
return;
end if;
declare
VH : constant access Editable_Value_Holder'Class
:= Editable_Value_Holder'Class (Parent.all)'Access;
begin
VH.Add_Validator (Validator => V, Shared => Shared);
end;
end Build_Components;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
procedure Get_Validator (Node : in Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
begin
Validator := Context.Get_Validator (Node.Validator);
Shared := True;
end Get_Validator;
-- ------------------------------
-- Range Validator Tag
-- ------------------------------
-- Create the Range_Validator Tag
function Create_Range_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Range_Validator_Tag_Node;
-- Get the validator instance that corresponds to the range validator.
-- Returns in <b>Validator</b> the validator instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
overriding
procedure Get_Validator (Node : in Range_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Long_Long_Integer := Long_Long_Integer'First;
Max : Long_Long_Integer := Long_Long_Integer'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context));
end if;
if Node.Maximum /= null then
Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max));
return;
end if;
Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Length Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Length_Validator Tag. Verifies that the XML node defines
-- the <b>minimum</b> or the <b>maximum</b> or both attributes.
-- ------------------------------
function Create_Length_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Length_Validator_Tag_Node;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
overriding
procedure Get_Validator (Node : in Length_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Natural := 0;
Max : Natural := Natural'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context)));
end if;
if Node.Maximum /= null then
Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context)));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Natural'Image (Min), Natural'Image (Max));
return;
end if;
Validator := Validators.Texts.Create_Length_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Attribute Tag
-- ------------------------------
-- ------------------------------
-- Create the Attribute Tag
-- ------------------------------
function Create_Attribute_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name");
Node : Attribute_Tag_Node_Access;
begin
Node := new Attribute_Tag_Node;
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Attr_Name := Attr;
Node.Value := Find_Attribute (Attributes, "value");
if Node.Attr_Name = null then
Node.Error ("Missing 'name' attribute");
else
Node.Attr.Name := Attr.Value;
end if;
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
return Node.all'Access;
end Create_Attribute_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- Adds the attribute to the component node.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Attribute_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use EL.Expressions;
begin
if Node.Attr_Name /= null and Node.Value /= null then
if Node.Value.Binding /= null then
declare
Expr : constant EL.Expressions.Expression
:= ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context);
begin
Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr);
end;
else
Parent.Set_Attribute (Def => Node.Attr'Access,
Value => Get_Value (Node.Value.all, Context));
end if;
end if;
end Build_Components;
-- ------------------------------
-- Facet Tag
-- ------------------------------
-- ------------------------------
-- Create the Facet Tag
-- ------------------------------
function Create_Facet_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Facet_Name := Find_Attribute (Attributes, "name");
if Node.Facet_Name = null then
Node.Error ("Missing 'name' attribute");
end if;
return Node.all'Access;
end Create_Facet_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the facet component of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Facet_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
begin
null;
end Build_Components;
-- ------------------------------
-- Metadata Tag
-- ------------------------------
-- ------------------------------
-- Create the Metadata Tag
-- ------------------------------
function Create_Metadata_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
return Node.all'Access;
end Create_Metadata_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as a metadata information
-- facet for the UIView parent component.
-- ------------------------------
overriding
procedure Build_Components (Node : access Metadata_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Core.Views;
begin
if not (Parent.all in UIView'Class) then
Node.Error ("Parent component of <f:metadata> must be a <f:view>");
return;
end if;
declare
UI : constant UIViewMetaData_Access := new UIViewMetaData;
begin
UIView'Class (Parent.all).Set_Metadata (UI, Node);
Build_Attributes (UI.all, Node.all, Context);
UI.Initialize (UI.Get_Context.all);
Node.Build_Children (UI.all'Access, Context);
end;
end Build_Components;
end ASF.Views.Nodes.Jsf;
|
Change the Name parameter to a Binding access
|
Change the Name parameter to a Binding access
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
4f069f1ea3979f0b4bed3f91fb2134724e206f65
|
regtests/util-serialize-io-json-tests.ads
|
regtests/util-serialize-io-json-tests.ads
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- 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 Util.Serialize.IO.JSON.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Parse_Error (T : in out Test);
procedure Test_Parser (T : in out Test);
end Util.Serialize.IO.JSON.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Serialize.IO.JSON.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Parse_Error (T : in out Test);
procedure Test_Parser (T : in out Test);
-- Generate some output stream for the test.
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class);
-- Test the JSON output stream generation.
procedure Test_Output (T : in out Test);
end Util.Serialize.IO.JSON.Tests;
|
Declare Test_Output and Write_Stream procedures
|
Declare Test_Output and Write_Stream procedures
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2d167f7e107f68195f0081151ec8f08af586006f
|
src/ado-parameters.ads
|
src/ado-parameters.ads
|
-----------------------------------------------------------------------
-- ADO Parameters -- Parameters for queries
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Calendar;
with Ada.Containers.Indefinite_Vectors;
with ADO.Utils;
with ADO.Drivers.Dialects;
-- === Query Parameters ===
-- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost
-- all database types including boolean, numbers, strings, dates and blob. Parameters are
-- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types.
--
-- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt>
-- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name
-- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list
-- and uses the last position. In most cases, it is easier to bind a parameter with a name
-- as follows:
--
-- Query.Bind_Param ("name", "Joe");
--
-- and the SQL can use the following construct:
--
-- SELECT * FROM user WHERE name = :name
--
-- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it
-- as a position index. Setting a parameter is easier:
--
-- Query.Add_Param ("Joe");
--
-- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct:
--
-- SELECT * FROM user WHERE name = ?
--
-- === Parameter Expander ===
-- The parameter expander is a mechanism that allows to replace or inject values in the SQL
-- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander
-- is useful to replace parameters that are global to a session or to an application.
--
package ADO.Parameters is
use Ada.Strings.Unbounded;
type Token is new String;
type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER,
T_INTEGER, T_BOOLEAN, T_BLOB);
type Parameter (T : Parameter_Type;
Len : Natural;
Value_Len : Natural) is record
Position : Natural := 0;
Name : String (1 .. Len);
case T is
when T_NULL =>
null;
when T_LONG_INTEGER =>
Long_Num : Long_Long_Integer := 0;
when T_INTEGER =>
Num : Integer;
when T_BOOLEAN =>
Bool : Boolean;
when T_DATE =>
Time : Ada.Calendar.Time;
when T_BLOB =>
Data : ADO.Blob_Ref;
when others =>
Str : String (1 .. Value_Len);
end case;
end record;
type Expander is limited interface;
type Expander_Access is access all Expander'Class;
-- Expand the name from the given group into a target parameter value to be used in
-- the SQL query. The expander can look in a cache or in some configuration to find
-- the value associated with the name and return it. The Expander can return a
-- T_NULL when a value is not found or it may also raise some exception.
function Expand (Instance : in Expander;
Group : in String;
Name : in String) return Parameter is abstract;
type Abstract_List is abstract new Ada.Finalization.Controlled with private;
type Abstract_List_Access is access all Abstract_List'Class;
-- Set the SQL dialect description object.
procedure Set_Dialect (Params : in out Abstract_List;
D : in ADO.Drivers.Dialects.Dialect_Access);
-- Get the SQL dialect description object.
function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access;
-- Add the parameter in the list.
procedure Add_Parameter (Params : in out Abstract_List;
Param : in Parameter) is abstract;
-- Set the parameters from another parameter list.
procedure Set_Parameters (Parameters : in out Abstract_List;
From : in Abstract_List'Class) is abstract;
-- Return the number of parameters in the list.
function Length (Params : in Abstract_List) return Natural is abstract;
-- Return the parameter at the given position
function Element (Params : in Abstract_List;
Position : in Natural) return Parameter is abstract;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in Abstract_List;
Position : in Natural;
Process : not null access
procedure (Element : in Parameter)) is abstract;
-- Clear the list of parameters.
procedure Clear (Parameters : in out Abstract_List) is abstract;
-- Operations to bind a parameter
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Token);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Blob_Ref);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Utils.Identifier_Vector);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in ADO.Blob_Ref);
procedure Bind_Null_Param (Params : in out Abstract_List;
Position : in Natural);
procedure Bind_Null_Param (Params : in out Abstract_List;
Name : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Boolean);
procedure Add_Param (Params : in out Abstract_List;
Value : in Long_Long_Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in Identifier);
procedure Add_Param (Params : in out Abstract_List;
Value : in Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Unbounded_String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Ada.Calendar.Time);
-- Add a null parameter.
procedure Add_Null_Param (Params : in out Abstract_List);
-- Expand the SQL string with the query parameters. The following parameters syntax
-- are recognized and replaced:
-- <ul>
-- <li>? is replaced according to the current parameter index. The index is incremented
-- after each occurrence of ? character.
-- <li>:nnn is replaced by the parameter at index <b>nnn</b>.
-- <li>:name is replaced by the parameter with the name <b>name</b>
-- <li>$group[var-name] is replaced by using the expander interface.
-- </ul>
-- Parameter strings are escaped. When a parameter is not found, an empty string is used.
-- Returns the expanded SQL string.
function Expand (Params : in Abstract_List'Class;
SQL : in String) return String;
-- ------------------------------
-- List of parameters
-- ------------------------------
-- The <b>List</b> is an implementation of the parameter list.
type List is new Abstract_List with private;
procedure Add_Parameter (Params : in out List;
Param : in Parameter);
procedure Set_Parameters (Params : in out List;
From : in Abstract_List'Class);
-- Return the number of parameters in the list.
function Length (Params : in List) return Natural;
-- Return the parameter at the given position
function Element (Params : in List;
Position : in Natural) return Parameter;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in List;
Position : in Natural;
Process : not null access procedure (Element : in Parameter));
-- Clear the list of parameters.
procedure Clear (Params : in out List);
private
function Compare_On_Name (Left, Right : in Parameter) return Boolean;
package Parameter_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Parameter,
"=" => Compare_On_Name);
type Abstract_List is abstract new Ada.Finalization.Controlled with record
Dialect : ADO.Drivers.Dialects.Dialect_Access := null;
Expander : Expander_Access;
end record;
type List is new Abstract_List with record
Params : Parameter_Vectors.Vector;
end record;
end ADO.Parameters;
|
-----------------------------------------------------------------------
-- ADO Parameters -- Parameters for queries
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Calendar;
with Ada.Containers.Indefinite_Vectors;
with ADO.Utils;
with ADO.Drivers.Dialects;
-- === Query Parameters ===
-- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost
-- all database types including boolean, numbers, strings, dates and blob. Parameters are
-- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types.
--
-- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt>
-- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name
-- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list
-- and uses the last position. In most cases, it is easier to bind a parameter with a name
-- as follows:
--
-- Query.Bind_Param ("name", "Joe");
--
-- and the SQL can use the following construct:
--
-- SELECT * FROM user WHERE name = :name
--
-- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it
-- as a position index. Setting a parameter is easier:
--
-- Query.Add_Param ("Joe");
--
-- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct:
--
-- SELECT * FROM user WHERE name = ?
--
-- === Parameter Expander ===
-- The parameter expander is a mechanism that allows to replace or inject values in the SQL
-- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander
-- is useful to replace parameters that are global to a session or to an application.
--
package ADO.Parameters is
use Ada.Strings.Unbounded;
type Token is new String;
type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER,
T_INTEGER, T_BOOLEAN, T_BLOB);
type Parameter (T : Parameter_Type;
Len : Natural;
Value_Len : Natural) is record
Position : Natural := 0;
Name : String (1 .. Len);
case T is
when T_NULL =>
null;
when T_LONG_INTEGER =>
Long_Num : Long_Long_Integer := 0;
when T_INTEGER =>
Num : Integer;
when T_BOOLEAN =>
Bool : Boolean;
when T_DATE =>
Time : Ada.Calendar.Time;
when T_BLOB =>
Data : ADO.Blob_Ref;
when others =>
Str : String (1 .. Value_Len);
end case;
end record;
type Expander is limited interface;
type Expander_Access is access all Expander'Class;
-- Expand the name from the given group into a target parameter value to be used in
-- the SQL query. The expander can look in a cache or in some configuration to find
-- the value associated with the name and return it. The Expander can return a
-- T_NULL when a value is not found or it may also raise some exception.
function Expand (Instance : in Expander;
Group : in String;
Name : in String) return Parameter is abstract;
type Abstract_List is abstract new Ada.Finalization.Controlled with private;
type Abstract_List_Access is access all Abstract_List'Class;
-- Set the SQL dialect description object.
procedure Set_Dialect (Params : in out Abstract_List;
D : in ADO.Drivers.Dialects.Dialect_Access);
-- Set the cache expander to be used when expanding the SQL.
procedure Set_Expander (Params : in out Abstract_List;
Expander : in ADO.Parameters.Expander_Access);
-- Get the SQL dialect description object.
function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access;
-- Add the parameter in the list.
procedure Add_Parameter (Params : in out Abstract_List;
Param : in Parameter) is abstract;
-- Set the parameters from another parameter list.
procedure Set_Parameters (Parameters : in out Abstract_List;
From : in Abstract_List'Class) is abstract;
-- Return the number of parameters in the list.
function Length (Params : in Abstract_List) return Natural is abstract;
-- Return the parameter at the given position
function Element (Params : in Abstract_List;
Position : in Natural) return Parameter is abstract;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in Abstract_List;
Position : in Natural;
Process : not null access
procedure (Element : in Parameter)) is abstract;
-- Clear the list of parameters.
procedure Clear (Parameters : in out Abstract_List) is abstract;
-- Operations to bind a parameter
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Token);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Blob_Ref);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Utils.Identifier_Vector);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in ADO.Blob_Ref);
procedure Bind_Null_Param (Params : in out Abstract_List;
Position : in Natural);
procedure Bind_Null_Param (Params : in out Abstract_List;
Name : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Boolean);
procedure Add_Param (Params : in out Abstract_List;
Value : in Long_Long_Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in Identifier);
procedure Add_Param (Params : in out Abstract_List;
Value : in Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Unbounded_String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Ada.Calendar.Time);
-- Add a null parameter.
procedure Add_Null_Param (Params : in out Abstract_List);
-- Expand the SQL string with the query parameters. The following parameters syntax
-- are recognized and replaced:
-- <ul>
-- <li>? is replaced according to the current parameter index. The index is incremented
-- after each occurrence of ? character.
-- <li>:nnn is replaced by the parameter at index <b>nnn</b>.
-- <li>:name is replaced by the parameter with the name <b>name</b>
-- <li>$group[var-name] is replaced by using the expander interface.
-- </ul>
-- Parameter strings are escaped. When a parameter is not found, an empty string is used.
-- Returns the expanded SQL string.
function Expand (Params : in Abstract_List'Class;
SQL : in String) return String;
-- ------------------------------
-- List of parameters
-- ------------------------------
-- The <b>List</b> is an implementation of the parameter list.
type List is new Abstract_List with private;
procedure Add_Parameter (Params : in out List;
Param : in Parameter);
procedure Set_Parameters (Params : in out List;
From : in Abstract_List'Class);
-- Return the number of parameters in the list.
function Length (Params : in List) return Natural;
-- Return the parameter at the given position
function Element (Params : in List;
Position : in Natural) return Parameter;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in List;
Position : in Natural;
Process : not null access procedure (Element : in Parameter));
-- Clear the list of parameters.
procedure Clear (Params : in out List);
private
function Compare_On_Name (Left, Right : in Parameter) return Boolean;
package Parameter_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Parameter,
"=" => Compare_On_Name);
type Abstract_List is abstract new Ada.Finalization.Controlled with record
Dialect : ADO.Drivers.Dialects.Dialect_Access := null;
Expander : Expander_Access;
end record;
type List is new Abstract_List with record
Params : Parameter_Vectors.Vector;
end record;
end ADO.Parameters;
|
Declare the Set_Expander procedure
|
Declare the Set_Expander procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
59e84497476eccf4cbe12c0e36c929d007022ebd
|
awa/src/awa-modules.ads
|
awa/src/awa-modules.ads
|
-----------------------------------------------------------------------
-- awa-modules -- Application Module
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Hash;
with Ada.Strings.Unbounded;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Log.Loggers;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Serialize.IO;
with Util.Listeners;
with EL.Expressions;
with ASF.Beans;
with ASF.Applications;
with ADO.Sessions;
with AWA.Events;
limited with AWA.Applications;
-- == Introduction ==
-- A module is a software component that can be integrated in the
-- web application. The module can bring a set of service APIs,
-- some Ada beans and some presentation files. The AWA framework
-- allows to configure various parts of a module when it is integrated
-- in an application. Some modules are designed to be re-used by
-- several applications (for example a _mail_ module, a _users_
-- module, ...). Other modules could be specific to an application.
-- An application will be made of several modules, some will be
-- generic some others specific to the application.
--
-- == Registration ==
-- The module should have only one instance per application and it must
-- be registered when the application is initialized. The module
-- instance should be added to the application record as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Xxx : aliased Xxx_Module;
-- end record;
--
-- The application record must override the `Initialize_Module` procedure
-- and it must register the module instance. This is done as follows:
--
-- overriding
-- procedure Initialize_Modules (App : in out Application) is
-- begin
-- Register (App => App.Self.all'Access,
-- Name => Xxx.Module.NAME,
-- URI => "xxx",
-- Module => App.User_Module'Access);
-- end Initialize_Modules;
--
-- The module is registered under a unique name. That name is used
-- to load the module configuration.
--
-- == Configuration ==
-- The module is configured by using an XML or a properties file.
-- The configuration file is used to define:
--
-- * the Ada beans that the module defines and uses,
-- * the events that the module wants to receive and the action
-- that must be performed when the event is posted,
-- * the permissions that the module needs and how to check them,
-- * the navigation rules which are used for the module web interface,
-- * the servlet and filter mappings used by the module
--
-- The module configuration is located in the *config* directory
-- and must be the name of the module followed by the file extension
-- (example: `module-name`.xml or `module-name`.properties).
--
--
package AWA.Modules is
type Application_Access is access all AWA.Applications.Application'Class;
-- ------------------------------
-- Module manager
-- ------------------------------
--
-- The <b>Module_Manager</b> represents the root of the logic manager
type Module_Manager is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with private;
function Get_Value (Manager : in Module_Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Get the module configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Plugin : Module_Manager;
Name : String;
Default : String := "") return String;
-- Get the module configuration property identified by the <tt>Config</tt> parameter.
-- If the property does not exist, the default configuration value is returned.
function Get_Config (Plugin : in Module_Manager;
Config : in ASF.Applications.Config_Param) return String;
-- ------------------------------
-- Module
-- ------------------------------
type Module is abstract new Ada.Finalization.Limited_Controlled with private;
type Module_Access is access all Module'Class;
-- Get the module name
function Get_Name (Plugin : Module) return String;
-- Get the base URI for this module
function Get_URI (Plugin : Module) return String;
-- Get the application in which this module is registered.
function Get_Application (Plugin : in Module) return Application_Access;
-- Find the module with the given name
function Find_Module (Plugin : Module;
Name : String) return Module_Access;
-- Get the module configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Plugin : Module;
Name : String;
Default : String := "") return String;
-- Get the module configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Plugin : Module;
Name : String;
Default : Integer := -1) return Integer;
-- Get the module configuration property identified by the <tt>Config</tt> parameter.
-- If the property does not exist, the default configuration value is returned.
function Get_Config (Plugin : in Module;
Config : in ASF.Applications.Config_Param) return String;
-- Get the module configuration property identified by the <tt>Config</tt> parameter.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Plugin : in Module;
Name : in String;
Default : in String := "")
return EL.Expressions.Expression;
procedure Initialize (Manager : in out Module_Manager;
Module : in AWA.Modules.Module'Class);
procedure Initialize (Plugin : in out Module;
App : in Application_Access;
Props : in ASF.Applications.Config);
-- Initialize the configuration file parser represented by <b>Parser</b> to recognize
-- the specific configuration recognized by the module.
procedure Initialize_Parser (Plugin : in out Module;
Parser : in out Util.Serialize.IO.Parser'Class) is null;
-- Configures the module after its initialization and after having read its XML configuration.
procedure Configure (Plugin : in out Module;
Props : in ASF.Applications.Config) is null;
-- Send the event to the module. The module identified by <b>To</b> is
-- found and the event is posted on its event channel.
procedure Send_Event (Plugin : in Module;
Content : in AWA.Events.Module_Event'Class);
-- Get the database connection for reading
function Get_Session (Manager : Module)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (Manager : Module)
return ADO.Sessions.Master_Session;
-- Register under the given name a function to create the bean instance when
-- it is accessed for a first time. The scope defines the scope of the bean.
-- bean
procedure Register (Plugin : in out Module;
Name : in String;
Bind : in ASF.Beans.Class_Binding_Access);
-- Add a listener to the module listner list. The module will invoke the listner
-- depending on events or actions that occur in the module.
procedure Add_Listener (Into : in out Module;
Item : in Util.Listeners.Listener_Access);
-- Find the module with the given name in the application and add the listener to the
-- module listener list.
procedure Add_Listener (Plugin : in Module;
Name : in String;
Item : in Util.Listeners.Listener_Access);
-- Remove a listener from the module listener list.
procedure Remove_Listener (Into : in out Module;
Item : in Util.Listeners.Listener_Access);
-- Finalize the module.
overriding
procedure Finalize (Plugin : in out Module);
type Pool_Module is abstract new Module with private;
type Session_Module is abstract new Module with private;
generic
type Manager_Type is new Module_Manager with private;
type Manager_Type_Access is access all Manager_Type'Class;
Name : String;
function Get_Manager return Manager_Type_Access;
-- Get the database connection for reading
function Get_Session (Manager : Module_Manager)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (Manager : Module_Manager)
return ADO.Sessions.Master_Session;
-- Send the event to the module. The module identified by <b>To</b> is
-- found and the event is posted on its event channel.
procedure Send_Event (Manager : in Module_Manager;
Content : in AWA.Events.Module_Event'Class);
-- ------------------------------
-- Module Registry
-- ------------------------------
-- The module registry maintains the list of available modules with
-- operations to retrieve them either from a name or from the base URI.
type Module_Registry is limited private;
type Module_Registry_Access is access all Module_Registry;
-- Initialize the registry
procedure Initialize (Registry : in out Module_Registry;
Config : in ASF.Applications.Config);
-- Register the module in the registry.
procedure Register (Registry : in Module_Registry_Access;
App : in Application_Access;
Plugin : in Module_Access;
Name : in String;
URI : in String);
-- Find the module with the given name
function Find_By_Name (Registry : Module_Registry;
Name : String) return Module_Access;
-- Find the module mapped to a given URI
function Find_By_URI (Registry : Module_Registry;
URI : String) return Module_Access;
-- Iterate over the modules that have been registered and execute the <b>Process</b>
-- procedure on each of the module instance.
procedure Iterate (Registry : in Module_Registry;
Process : access procedure (Plugin : in out Module'Class));
private
use Ada.Strings.Unbounded;
type Module is abstract new Ada.Finalization.Limited_Controlled with record
Registry : Module_Registry_Access;
App : Application_Access := null;
Name : Unbounded_String;
URI : Unbounded_String;
Config : ASF.Applications.Config;
Self : Module_Access := null;
Listeners : Util.Listeners.List;
end record;
-- Map to find a module from its name or its URI
package Module_Maps is new
Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Module_Access,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
type Module_Registry is limited record
Config : ASF.Applications.Config;
Name_Map : Module_Maps.Map;
URI_Map : Module_Maps.Map;
end record;
type Module_Manager is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with record
Module : Module_Access := null;
end record;
type Pool_Module is new Module with record
D : Natural;
end record;
type Session_Module is new Module with record
P : Natural;
end record;
use Util.Log;
-- The logger (used by the generic Get function).
Log : constant Loggers.Logger := Loggers.Create ("AWA.Modules");
end AWA.Modules;
|
-----------------------------------------------------------------------
-- awa-modules -- Application Module
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Hash;
with Ada.Strings.Unbounded;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Log.Loggers;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Serialize.IO;
with Util.Listeners;
with EL.Expressions;
with ASF.Beans;
with ASF.Applications;
with ADO.Sessions;
with AWA.Events;
limited with AWA.Applications;
-- == Introduction ==
-- A module is a software component that can be integrated in the
-- web application. The module can bring a set of service APIs,
-- some Ada beans and some presentation files. The AWA framework
-- allows to configure various parts of a module when it is integrated
-- in an application. Some modules are designed to be re-used by
-- several applications (for example a _mail_ module, a _users_
-- module, ...). Other modules could be specific to an application.
-- An application will be made of several modules, some will be
-- generic some others specific to the application.
--
-- == Registration ==
-- The module should have only one instance per application and it must
-- be registered when the application is initialized. The module
-- instance should be added to the application record as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Xxx : aliased Xxx_Module;
-- end record;
--
-- The application record must override the `Initialize_Module` procedure
-- and it must register the module instance. This is done as follows:
--
-- overriding
-- procedure Initialize_Modules (App : in out Application) is
-- begin
-- Register (App => App.Self.all'Access,
-- Name => Xxx.Module.NAME,
-- URI => "xxx",
-- Module => App.User_Module'Access);
-- end Initialize_Modules;
--
-- The module is registered under a unique name. That name is used
-- to load the module configuration.
--
-- == Configuration ==
-- The module is configured by using an XML or a properties file.
-- The configuration file is used to define:
--
-- * the Ada beans that the module defines and uses,
-- * the events that the module wants to receive and the action
-- that must be performed when the event is posted,
-- * the permissions that the module needs and how to check them,
-- * the navigation rules which are used for the module web interface,
-- * the servlet and filter mappings used by the module
--
-- The module configuration is located in the *config* directory
-- and must be the name of the module followed by the file extension
-- (example: `module-name`.xml or `module-name`.properties).
--
--
package AWA.Modules is
type Application_Access is access all AWA.Applications.Application'Class;
-- ------------------------------
-- Module manager
-- ------------------------------
--
-- The <b>Module_Manager</b> represents the root of the logic manager
type Module_Manager is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with private;
function Get_Value (Manager : in Module_Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Get the module configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Plugin : Module_Manager;
Name : String;
Default : String := "") return String;
-- Get the module configuration property identified by the <tt>Config</tt> parameter.
-- If the property does not exist, the default configuration value is returned.
function Get_Config (Plugin : in Module_Manager;
Config : in ASF.Applications.Config_Param) return String;
-- ------------------------------
-- Module
-- ------------------------------
type Module is abstract new Ada.Finalization.Limited_Controlled with private;
type Module_Access is access all Module'Class;
-- Get the module name
function Get_Name (Plugin : Module) return String;
-- Get the base URI for this module
function Get_URI (Plugin : Module) return String;
-- Get the application in which this module is registered.
function Get_Application (Plugin : in Module) return Application_Access;
-- Find the module with the given name
function Find_Module (Plugin : Module;
Name : String) return Module_Access;
-- Get the module configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Plugin : Module;
Name : String;
Default : String := "") return String;
-- Get the module configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Plugin : Module;
Name : String;
Default : Integer := -1) return Integer;
-- Get the module configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Plugin : Module;
Name : String;
Default : Boolean := False) return Boolean;
-- Get the module configuration property identified by the <tt>Config</tt> parameter.
-- If the property does not exist, the default configuration value is returned.
function Get_Config (Plugin : in Module;
Config : in ASF.Applications.Config_Param) return String;
-- Get the module configuration property identified by the <tt>Config</tt> parameter.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Plugin : in Module;
Name : in String;
Default : in String := "")
return EL.Expressions.Expression;
procedure Initialize (Manager : in out Module_Manager;
Module : in AWA.Modules.Module'Class);
procedure Initialize (Plugin : in out Module;
App : in Application_Access;
Props : in ASF.Applications.Config);
-- Initialize the configuration file parser represented by <b>Parser</b> to recognize
-- the specific configuration recognized by the module.
procedure Initialize_Parser (Plugin : in out Module;
Parser : in out Util.Serialize.IO.Parser'Class) is null;
-- Configures the module after its initialization and after having read its XML configuration.
procedure Configure (Plugin : in out Module;
Props : in ASF.Applications.Config) is null;
-- Send the event to the module. The module identified by <b>To</b> is
-- found and the event is posted on its event channel.
procedure Send_Event (Plugin : in Module;
Content : in AWA.Events.Module_Event'Class);
-- Get the database connection for reading
function Get_Session (Manager : Module)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (Manager : Module)
return ADO.Sessions.Master_Session;
-- Register under the given name a function to create the bean instance when
-- it is accessed for a first time. The scope defines the scope of the bean.
-- bean
procedure Register (Plugin : in out Module;
Name : in String;
Bind : in ASF.Beans.Class_Binding_Access);
-- Add a listener to the module listner list. The module will invoke the listner
-- depending on events or actions that occur in the module.
procedure Add_Listener (Into : in out Module;
Item : in Util.Listeners.Listener_Access);
-- Find the module with the given name in the application and add the listener to the
-- module listener list.
procedure Add_Listener (Plugin : in Module;
Name : in String;
Item : in Util.Listeners.Listener_Access);
-- Remove a listener from the module listener list.
procedure Remove_Listener (Into : in out Module;
Item : in Util.Listeners.Listener_Access);
-- Finalize the module.
overriding
procedure Finalize (Plugin : in out Module);
type Pool_Module is abstract new Module with private;
type Session_Module is abstract new Module with private;
generic
type Manager_Type is new Module_Manager with private;
type Manager_Type_Access is access all Manager_Type'Class;
Name : String;
function Get_Manager return Manager_Type_Access;
-- Get the database connection for reading
function Get_Session (Manager : Module_Manager)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (Manager : Module_Manager)
return ADO.Sessions.Master_Session;
-- Send the event to the module. The module identified by <b>To</b> is
-- found and the event is posted on its event channel.
procedure Send_Event (Manager : in Module_Manager;
Content : in AWA.Events.Module_Event'Class);
-- ------------------------------
-- Module Registry
-- ------------------------------
-- The module registry maintains the list of available modules with
-- operations to retrieve them either from a name or from the base URI.
type Module_Registry is limited private;
type Module_Registry_Access is access all Module_Registry;
-- Initialize the registry
procedure Initialize (Registry : in out Module_Registry;
Config : in ASF.Applications.Config);
-- Register the module in the registry.
procedure Register (Registry : in Module_Registry_Access;
App : in Application_Access;
Plugin : in Module_Access;
Name : in String;
URI : in String);
-- Find the module with the given name
function Find_By_Name (Registry : Module_Registry;
Name : String) return Module_Access;
-- Find the module mapped to a given URI
function Find_By_URI (Registry : Module_Registry;
URI : String) return Module_Access;
-- Iterate over the modules that have been registered and execute the <b>Process</b>
-- procedure on each of the module instance.
procedure Iterate (Registry : in Module_Registry;
Process : access procedure (Plugin : in out Module'Class));
private
use Ada.Strings.Unbounded;
type Module is abstract new Ada.Finalization.Limited_Controlled with record
Registry : Module_Registry_Access;
App : Application_Access := null;
Name : Unbounded_String;
URI : Unbounded_String;
Config : ASF.Applications.Config;
Self : Module_Access := null;
Listeners : Util.Listeners.List;
end record;
-- Map to find a module from its name or its URI
package Module_Maps is new
Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Module_Access,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
type Module_Registry is limited record
Config : ASF.Applications.Config;
Name_Map : Module_Maps.Map;
URI_Map : Module_Maps.Map;
end record;
type Module_Manager is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with record
Module : Module_Access := null;
end record;
type Pool_Module is new Module with record
D : Natural;
end record;
type Session_Module is new Module with record
P : Natural;
end record;
use Util.Log;
-- The logger (used by the generic Get function).
Log : constant Loggers.Logger := Loggers.Create ("AWA.Modules");
end AWA.Modules;
|
Declare a Get_Config function on the module to retrieve a boolean configuration parameter
|
Declare a Get_Config function on the module to retrieve a boolean configuration parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0bf3d3137d7fe12239f5b4811face984e01a1897
|
src/util-strings.ads
|
src/util-strings.ads
|
-----------------------------------------------------------------------
-- Util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Sets;
with Util.Concurrent.Counters;
package Util.Strings is
pragma Preelaborate;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
-- Search for the first occurrence of the character in the string
-- after the from index. This implementation is 3-times faster than
-- the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Index (Source : in String;
Char : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the character in the string
-- before the from index and going backward.
-- This implementation is 3-times faster than the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Rindex (Source : in String;
Ch : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the pattern in the string.
function Index (Source : in String;
Pattern : in String;
From : in Positive;
Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Integer) return String;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Long_Long_Integer) return String;
package String_Access_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
package String_Set is new Ada.Containers.Hashed_Sets
(Element_Type => Name_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Keys);
-- String reference
type String_Ref is private;
-- Create a string reference from a string.
function To_String_Ref (S : in String) return String_Ref;
-- Create a string reference from an unbounded string.
function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref;
-- Get the string
function To_String (S : in String_Ref) return String;
-- Get the string as an unbounded string
function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String;
-- Compute the hash value of the string reference.
function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type;
-- Returns true if left and right string references are equivalent.
function Equivalent_Keys (Left, Right : in String_Ref) return Boolean;
function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys;
function "=" (Left : in String_Ref;
Right : in String) return Boolean;
function "=" (Left : in String_Ref;
Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean;
-- Returns the string length.
function Length (S : in String_Ref) return Natural;
private
pragma Inline (To_String_Ref);
pragma Inline (To_String);
type String_Record (Len : Natural) is limited record
Counter : Util.Concurrent.Counters.Counter;
Str : String (1 .. Len);
end record;
type String_Record_Access is access all String_Record;
type String_Ref is new Ada.Finalization.Controlled with record
Str : String_Record_Access := null;
end record;
pragma Finalize_Storage_Only (String_Ref);
-- Increment the reference counter.
overriding
procedure Adjust (Object : in out String_Ref);
-- Decrement the reference counter and free the allocated string.
overriding
procedure Finalize (Object : in out String_Ref);
end Util.Strings;
|
-----------------------------------------------------------------------
-- util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Sets;
private with Util.Concurrent.Counters;
package Util.Strings is
pragma Preelaborate;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
-- Search for the first occurrence of the character in the string
-- after the from index. This implementation is 3-times faster than
-- the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Index (Source : in String;
Char : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the character in the string
-- before the from index and going backward.
-- This implementation is 3-times faster than the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Rindex (Source : in String;
Ch : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the pattern in the string.
function Index (Source : in String;
Pattern : in String;
From : in Positive;
Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Integer) return String;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Long_Long_Integer) return String;
package String_Access_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
package String_Set is new Ada.Containers.Hashed_Sets
(Element_Type => Name_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Keys);
-- String reference
type String_Ref is private;
-- Create a string reference from a string.
function To_String_Ref (S : in String) return String_Ref;
-- Create a string reference from an unbounded string.
function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref;
-- Get the string
function To_String (S : in String_Ref) return String;
-- Get the string as an unbounded string
function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String;
-- Compute the hash value of the string reference.
function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type;
-- Returns true if left and right string references are equivalent.
function Equivalent_Keys (Left, Right : in String_Ref) return Boolean;
function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys;
function "=" (Left : in String_Ref;
Right : in String) return Boolean;
function "=" (Left : in String_Ref;
Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean;
-- Returns the string length.
function Length (S : in String_Ref) return Natural;
private
pragma Inline (To_String_Ref);
pragma Inline (To_String);
type String_Record (Len : Natural) is limited record
Counter : Util.Concurrent.Counters.Counter;
Str : String (1 .. Len);
end record;
type String_Record_Access is access all String_Record;
type String_Ref is new Ada.Finalization.Controlled with record
Str : String_Record_Access := null;
end record;
-- Increment the reference counter.
overriding
procedure Adjust (Object : in out String_Ref);
-- Decrement the reference counter and free the allocated string.
overriding
procedure Finalize (Object : in out String_Ref);
end Util.Strings;
|
Change with clause to a private with clause for concurrent counters
|
Change with clause to a private with clause for concurrent counters
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
fe90d2f5b9dbae93bf15666b547b56a48796f4be
|
src/wiki-filters.ads
|
src/wiki-filters.ads
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Nodes;
with Wiki.Strings;
-- == Filters ==
-- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt>
-- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations
-- and it forwards the different calls to a next wiki document instance. A filter can do some
-- operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type
-- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
package Wiki.Filters is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is new Ada.Finalization.Limited_Controlled with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map);
-- Add a section header with the given level in the document.
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Pop a HTML node with the given tag.
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a quote.
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Filter : in out Filter_Type);
private
type Filter_Type is new Ada.Finalization.Limited_Controlled with record
Next : Filter_Type_Access;
end record;
end Wiki.Filters;
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Nodes;
with Wiki.Strings;
-- == Filters ==
-- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt>
-- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations
-- and it forwards the different calls to a next wiki document instance. A filter can do some
-- operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type
-- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
package Wiki.Filters is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is new Ada.Finalization.Limited_Controlled with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map);
-- Add a section header with the given level in the document.
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Pop a HTML node with the given tag.
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a quote.
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document);
private
type Filter_Type is new Ada.Finalization.Limited_Controlled with record
Next : Filter_Type_Access;
end record;
end Wiki.Filters;
|
Add a Document parameter to the Finish procedure
|
Add a Document parameter to the Finish procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
13bf3466220a50ea07c9e3a3522ff76321f7fd6c
|
src/wiki-helpers-parser.adb
|
src/wiki-helpers-parser.adb
|
-----------------------------------------------------------------------
-- wiki-helpers-parser -- Generic procedure for the wiki parser
-- Copyright (C) 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
with Wiki.Streams;
procedure Wiki.Helpers.Parser (Engine : in out Engine_Type;
Content : in Element_Type;
Doc : in out Wiki.Documents.Document) is
type Wide_Input is new Wiki.Streams.Input_Stream with record
Pos : Positive;
Len : Natural;
end record;
overriding
procedure Read (Buf : in out Wide_Input;
Token : out Wiki.Strings.WChar;
Is_Eof : out Boolean);
procedure Read (Buf : in out Wide_Input;
Token : out Wiki.Strings.WChar;
Is_Eof : out Boolean) is
begin
if Buf.Pos <= Buf.Len then
Element (Content, Buf.Pos, Token);
Is_Eof := False;
else
Is_Eof := True;
Token := Wiki.Helpers.CR;
end if;
end Read;
Buffer : aliased Wide_Input;
begin
Buffer.Pos := 1;
Buffer.Len := Length (Content);
Parse (Engine, Buffer'Unchecked_Access, Doc);
end Wiki.Helpers.Parser;
|
-----------------------------------------------------------------------
-- wiki-helpers-parser -- Generic procedure for the wiki parser
-- Copyright (C) 2016, 2018, 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;
with Wiki.Streams;
procedure Wiki.Helpers.Parser (Engine : in out Engine_Type;
Content : in Element_Type;
Doc : in out Wiki.Documents.Document) is
type Wide_Input is new Wiki.Streams.Input_Stream with record
Pos : Positive;
Len : Natural;
end record;
-- Read the input stream and fill the `Into` buffer until either it is full or
-- we reach the end of line. Returns in `Last` the last valid position in the
-- `Into` buffer. When there is no character to read, return True in
-- the `Eof` indicator.
overriding
procedure Read (Input : in out Wide_Input;
Into : in out Wiki.Strings.WString;
Last : out Natural;
Eof : out Boolean);
overriding
procedure Read (Input : in out Wide_Input;
Into : in out Wiki.Strings.WString;
Last : out Natural;
Eof : out Boolean) is
Pos : Natural := Into'First;
Char : Wiki.Strings.WChar;
begin
Eof := False;
while Pos <= Into'Last loop
if Input.Pos <= Input.Len then
Element (Content, Input.Pos, Char);
else
Eof := True;
exit;
end if;
Into (Pos) := Char;
Pos := Pos + 1;
exit when Char = Helpers.CR or Char = Helpers.LF;
end loop;
Last := Pos - 1;
end Read;
Buffer : aliased Wide_Input;
begin
Buffer.Pos := 1;
Buffer.Len := Length (Content);
Parse (Engine, Buffer'Unchecked_Access, Doc);
end Wiki.Helpers.Parser;
|
Update the Read procedure to read a complete line
|
Update the Read procedure to read a complete line
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.