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
|
---|---|---|---|---|---|---|---|---|---|
b43153c9495e4a40dff50a9bdd574dac8b60f23f
|
samples/render.adb
|
samples/render.adb
|
-----------------------------------------------------------------------
-- render -- XHTML Rendering example
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with GNAT.Command_Line;
with ASF.Applications.Views;
with ASF.Components.Core;
with ASF.Contexts.Faces;
with ASF.Contexts.Writer.String;
with EL.Objects;
with EL.Contexts;
with EL.Contexts.Default;
with EL.Variables;
with EL.Variables.Default;
with ASF.Streams;
-- This example reads an XHTML file and renders the result.
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Fixed;
use ASF;
use ASF.Contexts.Faces;
use EL.Contexts.Default;
use EL.Variables;
use EL.Variables.Default;
use EL.Contexts;
use EL.Objects;
H : Applications.Views.View_Handler;
Writer : aliased Contexts.Writer.String.String_Writer;
Context : aliased Faces_Context;
View : Components.Core.UIViewRoot;
ELContext : aliased EL.Contexts.Default.Default_Context;
Variables : aliased Default_Variable_Mapper;
Resolver : aliased Default_ELResolver;
Conf : Applications.Config;
Output : ASF.Streams.Print_Stream;
begin
loop
case Getopt ("D:") is
when 'D' =>
declare
Value : constant String := Parameter;
Pos : constant Natural := Index (Value, "=");
begin
-- if Pos > 0 then
-- Variables.Set_Variable (Value (1 .. Pos - 1),
-- To_Object (Value (Pos + 1 .. Value'Last)));
-- else
-- Variables.Set_Variable (Value, To_Object(True));
-- end if;
null;
end;
when others =>
exit;
end case;
end loop;
Conf.Set ("view.ignore_white_spaces", "false");
Conf.Set ("view.escape_unknown_tags", "false");
Conf.Set ("view.ignore_empty_lines", "true");
declare
View_Name : constant String := Get_Argument;
begin
H.Initialize (Conf);
Context.Set_Response_Writer (Writer'Unchecked_Access);
Context.Set_ELContext (ELContext'Unchecked_Access);
ELContext.Set_Variable_Mapper (Variables'Unchecked_Access);
ELContext.Set_Resolver (Resolver'Unchecked_Access);
Writer.Initialize ("text/xml", "UTF-8", Output);
Set_Current (Context'Unchecked_Access);
H.Restore_View (View_Name, Context, View);
H.Render_View (Context, View);
Writer.Flush;
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Writer.Get_Response));
H.Close;
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'");
end;
end Render;
|
-----------------------------------------------------------------------
-- render -- XHTML Rendering example
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with GNAT.Command_Line;
with ASF.Applications.Main;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Contexts.Faces;
with EL.Objects;
with EL.Contexts;
with EL.Contexts.Default;
with EL.Variables;
with EL.Variables.Default;
with ASF.Streams;
-- This example reads an XHTML file and renders the result.
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Fixed;
use ASF;
use ASF.Contexts.Faces;
use EL.Contexts.Default;
use EL.Variables;
use EL.Variables.Default;
use EL.Contexts;
use EL.Objects;
App : Applications.Main.Application;
Conf : Applications.Config;
begin
loop
case Getopt ("D:") is
when 'D' =>
declare
Value : constant String := Parameter;
Pos : constant Natural := Index (Value, "=");
begin
-- if Pos > 0 then
-- Variables.Set_Variable (Value (1 .. Pos - 1),
-- To_Object (Value (Pos + 1 .. Value'Last)));
-- else
-- Variables.Set_Variable (Value, To_Object(True));
-- end if;
null;
end;
when others =>
exit;
end case;
end loop;
Conf.Set ("view.ignore_white_spaces", "false");
Conf.Set ("view.escape_unknown_tags", "false");
Conf.Set ("view.ignore_empty_lines", "true");
declare
View_Name : constant String := Get_Argument;
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
App.Initialize (Conf);
App.Dispatch (Page => View_Name,
Request => Req,
Response => Reply);
Reply.Read_Content (Content);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content));
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'");
end;
end Render;
|
Fix the render example to use the ASF Application
|
Fix the render example to use the ASF Application
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
e8a52292681212ba6fa2cdb28551bd3430dcbe46
|
mat/src/mat-readers-streams-sockets.ads
|
mat/src/mat-readers-streams-sockets.ads
|
-----------------------------------------------------------------------
-- mat-readers-sockets -- Reader for TCP/IP sockets
-- 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.Streams.Buffered;
with Util.Streams.Files;
with Util.Streams.Sockets;
with GNAT.Sockets;
package MAT.Readers.Streams.Sockets is
type Socket_Reader_Type is new Manager_Base with private;
type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class;
-- Open the socket to accept connections.
procedure Open (Reader : in out Socket_Reader_Type;
Address : in GNAT.Sockets.Sock_Addr_Type);
procedure Read_All (Reader : in out Socket_Reader_Type);
procedure Close (Reader : in out Socket_Reader_Type);
private
task type Socket_Reader_Task is
entry Start (S : in Socket_Reader_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type);
end Socket_Reader_Task;
type Socket_Reader_Type is new Manager_Base with record
Socket : aliased Util.Streams.Sockets.Socket_Stream;
Stream : Util.Streams.Buffered.Buffered_Stream;
Server : Socket_Reader_Task;
Stop : Boolean := False;
end record;
end MAT.Readers.Streams.Sockets;
|
-----------------------------------------------------------------------
-- mat-readers-sockets -- Reader for TCP/IP sockets
-- 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.Finalization;
with Util.Streams.Buffered;
with Util.Streams.Files;
with Util.Streams.Sockets;
with GNAT.Sockets;
package MAT.Readers.Streams.Sockets is
type Socket_Listener is new Ada.Finalization.Limited_Controlled with private;
type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private;
type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class;
-- Open the socket to accept connections.
procedure Open (Reader : in out Socket_Reader_Type;
Address : in GNAT.Sockets.Sock_Addr_Type);
procedure Close (Reader : in out Socket_Reader_Type);
private
task type Socket_Listener_Task is
entry Start (Address : in GNAT.Sockets.Sock_Addr_Type);
end Socket_Listener_Task;
task type Socket_Reader_Task is
entry Start (S : in Socket_Reader_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type);
end Socket_Reader_Task;
type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record
Socket : aliased Util.Streams.Sockets.Socket_Stream;
Server : Socket_Reader_Task;
Stop : Boolean := False;
end record;
type Socket_Listener is new Ada.Finalization.Limited_Controlled with record
Accept_Selector : GNAT.Sockets.Selector_Type;
Listener : Socket_Listener_Task;
end record;
end MAT.Readers.Streams.Sockets;
|
Define the Socket_Listener type to create the accept socket and wait for connections
|
Define the Socket_Listener type to create the accept socket and wait for connections
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
98f5d8449610266d0170398fb344d2ff027a1bc9
|
mat/src/mat-commands.ads
|
mat/src/mat-commands.ads
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
end MAT.Commands;
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
procedure Interactive (Target : in out MAT.Targets.Target_Type'Class);
end MAT.Commands;
|
Declare the Interactive procedure
|
Declare the Interactive procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f28edaabfdab49c96e517b92f951b63b5859ca19
|
src/util-beans-objects-datasets.adb
|
src/util-beans-objects-datasets.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Datasets -- Datasets
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Beans.Objects.Datasets is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Object_Array,
Name => Object_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Dataset_Array,
Name => Dataset_Array_Access);
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Dataset) return Natural is
begin
return From.Count;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Dataset;
Index : in Natural) is
begin
From.Current_Pos := Index;
From.Current.Data := From.Data (Index);
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- 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 Dataset;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Current_Pos);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Append a row in the dataset and call the fill procedure to populate
-- the row content.
-- ------------------------------
procedure Append (Into : in out Dataset;
Fill : not null access procedure (Data : in out Object_Array)) is
Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns);
begin
if Into.Data = null then
Into.Data := new Dataset_Array (1 .. 10);
elsif Into.Count >= Into.Data'Last then
declare
-- Sun's Java ArrayList use a 2/3 grow factor.
-- Python's array use 8/9.
Grow : constant Positive := (Into.Count * 2) / 3;
Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow);
begin
Set (Into.Data'Range) := Into.Data.all;
Free (Into.Data);
Into.Data := Set;
end;
end if;
Into.Count := Into.Count + 1;
Into.Data (Into.Count) := Data;
Fill (Data.all);
end Append;
-- ------------------------------
-- Add a column to the dataset. If the position is not specified,
-- the column count is incremented and the name associated with the last column.
-- Raises Invalid_State exception if the dataset contains some rows,
-- ------------------------------
procedure Add_Column (Into : in out Dataset;
Name : in String;
Pos : in Natural := 0) is
Col : Positive;
begin
if Into.Count /= 0 then
raise Invalid_State with "The dataset contains some rows.";
end if;
if Pos = 0 then
Col := Into.Columns + 1;
else
Col := Pos;
end if;
Into.Map.Insert (Name, Col);
if Into.Columns < Col then
Into.Columns := Col;
end if;
end Add_Column;
-- ------------------------------
-- Clear the content of the dataset.
-- ------------------------------
procedure Clear (Set : in out Dataset) is
begin
for I in 1 .. Set.Count loop
Free (Set.Data (I));
end loop;
Set.Count := 0;
Set.Current_Pos := 0;
Set.Current.Data := null;
end Clear;
-- ------------------------------
-- 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 Row;
Name : in String) return Util.Beans.Objects.Object is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
return From.Data (Dataset_Map.Element (Pos));
else
return 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 Row;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
From.Data (Dataset_Map.Element (Pos)) := Value;
end if;
end Set_Value;
-- ------------------------------
-- Initialize the dataset and the row bean instance.
-- ------------------------------
overriding
procedure Initialize (Set : in out Dataset) is
begin
Set.Row := To_Object (Value => Set.Current'Unchecked_Access,
Storage => STATIC);
Set.Current.Map := Set.Map'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Release the dataset storage.
-- ------------------------------
overriding
procedure Finalize (Set : in out Dataset) is
begin
Set.Clear;
Free (Set.Data);
end Finalize;
end Util.Beans.Objects.Datasets;
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Datasets -- Datasets
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Beans.Objects.Datasets is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Object_Array,
Name => Object_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Dataset_Array,
Name => Dataset_Array_Access);
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Dataset) return Natural is
begin
return From.Count;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Dataset;
Index : in Natural) is
begin
From.Current_Pos := Index;
From.Current.Data := From.Data (Index);
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- 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 Dataset;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Current_Pos);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Append a row in the dataset and call the fill procedure to populate
-- the row content.
-- ------------------------------
procedure Append (Into : in out Dataset;
Fill : not null access procedure (Data : in out Object_Array)) is
Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns);
begin
if Into.Data = null then
Into.Data := new Dataset_Array (1 .. 10);
elsif Into.Count >= Into.Data'Length then
declare
-- Sun's Java ArrayList use a 2/3 grow factor.
-- Python's array use 8/9.
Grow : constant Positive := Into.Count + (Into.Count * 2) / 3;
Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow);
begin
Set (Into.Data'Range) := Into.Data.all;
Free (Into.Data);
Into.Data := Set;
end;
end if;
Into.Count := Into.Count + 1;
Into.Data (Into.Count) := Data;
Fill (Data.all);
end Append;
-- ------------------------------
-- Add a column to the dataset. If the position is not specified,
-- the column count is incremented and the name associated with the last column.
-- Raises Invalid_State exception if the dataset contains some rows,
-- ------------------------------
procedure Add_Column (Into : in out Dataset;
Name : in String;
Pos : in Natural := 0) is
Col : Positive;
begin
if Into.Count /= 0 then
raise Invalid_State with "The dataset contains some rows.";
end if;
if Pos = 0 then
Col := Into.Columns + 1;
else
Col := Pos;
end if;
Into.Map.Insert (Name, Col);
if Into.Columns < Col then
Into.Columns := Col;
end if;
end Add_Column;
-- ------------------------------
-- Clear the content of the dataset.
-- ------------------------------
procedure Clear (Set : in out Dataset) is
begin
for I in 1 .. Set.Count loop
Free (Set.Data (I));
end loop;
Set.Count := 0;
Set.Current_Pos := 0;
Set.Current.Data := null;
end Clear;
-- ------------------------------
-- 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 Row;
Name : in String) return Util.Beans.Objects.Object is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
return From.Data (Dataset_Map.Element (Pos));
else
return 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 Row;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Pos : constant Dataset_Map.Cursor := From.Map.Find (Name);
begin
if From.Data /= null and then Dataset_Map.Has_Element (Pos) then
From.Data (Dataset_Map.Element (Pos)) := Value;
end if;
end Set_Value;
-- ------------------------------
-- Initialize the dataset and the row bean instance.
-- ------------------------------
overriding
procedure Initialize (Set : in out Dataset) is
begin
Set.Row := To_Object (Value => Set.Current'Unchecked_Access,
Storage => STATIC);
Set.Current.Map := Set.Map'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Release the dataset storage.
-- ------------------------------
overriding
procedure Finalize (Set : in out Dataset) is
begin
Set.Clear;
Free (Set.Data);
end Finalize;
end Util.Beans.Objects.Datasets;
|
Fix growth factor of the dataset
|
Fix growth factor of the dataset
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
f25172549c0d34929ea933ab19467143a71a215f
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 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.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
private with Wiki.Buffers;
private with Util.Stacks;
private with Wiki.Nodes;
private with Wiki.Html_Parser;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
subtype Parser_Type is Parser;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- 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 Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- 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 Wiki.Strings.UString;
Doc : in out Wiki.Documents.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.Documents.Document);
private
type Trim_End is (None, Left, Right, Both);
type Block;
type Content_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Content_Access;
Last : Natural := 0;
Content : Wiki.Strings.WString (1 .. Len);
end record;
procedure Next (Content : in out Content_Access;
Pos : in out Positive) with Inline_Always;
use Wiki.Strings.Wide_Wide_Builders;
type Block_Type is record
Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH;
Level : Natural := 0;
Marker : Wiki.Strings.WChar := ' ';
Number : Integer := 0;
end record;
type Parser_State_Type is (State_Html_Doctype,
State_Html_Comment,
State_Html_Attribute,
State_Html_Element);
type Block_Access is access all Block_Type;
package Block_Stack is new Util.Stacks (Element_Type => Block_Type,
Element_Type_Access => Block_Access);
type Parser_Handler is access procedure (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access);
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Previous_Syntax : Wiki_Syntax;
Document : Wiki.Documents.Document;
Parse_Block : Parser_Handler;
Parse_Inline : Parser_Handler;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Line_Buffer : Wiki.Buffers.Builder (512);
Text_Buffer : Wiki.Buffers.Builder (512);
Empty_Line : Boolean := True;
Is_Last_Line : Boolean := False;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
In_Table : Boolean := False;
Need_Paragraph : Boolean := True;
Pending_Paragraph : Boolean := False;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE;
Blocks : Block_Stack.Stack;
Previous_Line_Empty : Boolean := False;
Header_Level : Natural := 0;
Is_Empty_Paragraph : Boolean := True;
Pre_Tag_Counter : Natural := 0;
-- Pre-format code block
Preformat_Fence : Wiki.Strings.WChar;
Preformat_Indent : Natural := 0;
Preformat_Fcount : Natural := 0;
Preformat_Format : Wiki.Strings.BString (32);
Html : Wiki.Html_Parser.Parser_Type;
end record;
-- Read the next wiki input line in the line buffer.
procedure Read_Line (Parser : in out Parser_Type'Class;
Buffer : out Wiki.Buffers.Buffer_Access);
function Is_List_Item (P : in Parser;
Level : in Natural) return Boolean;
function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access;
From : in Positive;
Token : in Wiki.Strings.WChar) return Boolean;
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser;
Trim : in Trim_End := None);
procedure Flush_Block (Parser : in out Parser_Type);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
procedure Pop_List (P : in out Parser;
Level : in Natural;
Marker : in Wiki.Strings.WChar);
procedure Pop_List (P : in out Parser);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Process_Html (P : in out Parser;
Kind : in Wiki.Html_Parser.State_Type;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a single character sequence.
-- Example:
-- _name_ *bold* `code`
procedure Parse_Format (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence.
-- Example:
-- --name-- **bold** ~~strike~~
procedure Parse_Format_Double (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Push a new block kind on the block stack.
procedure Push_Block (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer := 0;
Marker : in Wiki.Strings.WChar := ' ';
Number : in Integer := 0);
-- Pop the current block stack.
procedure Pop_Block (P : in out Parser);
procedure Pop_All (P : in out Parser);
procedure Pop_Block_Until (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer);
procedure Append_Text (P : in out Parser;
Text : in Wiki.Strings.BString;
From : in Positive;
To : in Positive);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 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.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
private with Wiki.Buffers;
private with Util.Stacks;
private with Wiki.Nodes;
private with Wiki.Html_Parser;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
subtype Parser_Type is Parser;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- 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 Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- 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 Wiki.Strings.UString;
Doc : in out Wiki.Documents.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.Documents.Document);
private
type Trim_End is (None, Left, Right, Both);
type Block;
type Content_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Content_Access;
Last : Natural := 0;
Content : Wiki.Strings.WString (1 .. Len);
end record;
procedure Next (Content : in out Content_Access;
Pos : in out Positive) with Inline_Always;
use Wiki.Strings.Wide_Wide_Builders;
type Block_Type is record
Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH;
Level : Natural := 0;
Marker : Wiki.Strings.WChar := ' ';
Number : Integer := 0;
end record;
type Parser_State_Type is (State_Html_Doctype,
State_Html_Comment,
State_Html_Attribute,
State_Html_Element);
type Block_Access is access all Block_Type;
package Block_Stack is new Util.Stacks (Element_Type => Block_Type,
Element_Type_Access => Block_Access);
type Parser_Handler is access procedure (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access);
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Previous_Syntax : Wiki_Syntax;
Document : Wiki.Documents.Document;
Parse_Block : Parser_Handler;
Parse_Inline : Parser_Handler;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Line_Buffer : Wiki.Buffers.Builder (512);
Text_Buffer : Wiki.Buffers.Builder (512);
Empty_Line : Boolean := True;
Is_Last_Line : Boolean := False;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
In_Table : Boolean := False;
In_Html : Boolean := False;
Need_Paragraph : Boolean := True;
Pending_Paragraph : Boolean := False;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE;
Blocks : Block_Stack.Stack;
Previous_Line_Empty : Boolean := False;
Header_Level : Natural := 0;
Is_Empty_Paragraph : Boolean := True;
Pre_Tag_Counter : Natural := 0;
-- Pre-format code block
Preformat_Fence : Wiki.Strings.WChar;
Preformat_Indent : Natural := 0;
Preformat_Fcount : Natural := 0;
Preformat_Format : Wiki.Strings.BString (32);
Html : Wiki.Html_Parser.Parser_Type;
end record;
-- Read the next wiki input line in the line buffer.
procedure Read_Line (Parser : in out Parser_Type'Class;
Buffer : out Wiki.Buffers.Buffer_Access);
function Is_List_Item (P : in Parser;
Level : in Natural) return Boolean;
function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access;
From : in Positive;
Token : in Wiki.Strings.WChar) return Boolean;
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser;
Trim : in Trim_End := None);
procedure Flush_Block (Parser : in out Parser_Type);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
procedure Pop_List (P : in out Parser;
Level : in Natural;
Marker : in Wiki.Strings.WChar);
procedure Pop_List (P : in out Parser);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Process_Html (P : in out Parser;
Kind : in Wiki.Html_Parser.State_Type;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a single character sequence.
-- Example:
-- _name_ *bold* `code`
procedure Parse_Format (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence.
-- Example:
-- --name-- **bold** ~~strike~~
procedure Parse_Format_Double (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Push a new block kind on the block stack.
procedure Push_Block (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer := 0;
Marker : in Wiki.Strings.WChar := ' ';
Number : in Integer := 0);
-- Pop the current block stack.
procedure Pop_Block (P : in out Parser);
procedure Pop_All (P : in out Parser);
procedure Pop_Block_Until (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer);
procedure Append_Text (P : in out Parser;
Text : in Wiki.Strings.BString;
From : in Positive;
To : in Positive);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
Add In_Html boolean in the parser type
|
Add In_Html boolean in the parser type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
8f9853b3ac08766ee573ef0fbb2721ab6dd05f9d
|
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.Documents;
with Wiki.Streams;
-- === Wiki Parsers ===
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt>
-- instance with headers, paragraphs, links, and other elements.
--
-- Doc : Wiki.Documents.Document;
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- <tt>Set_Syntax</tt> procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that
-- the filter added last is called first.
--
-- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream
-- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure
-- completes, the <tt>Document</tt> instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
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 := 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 Wiki.Strings.WString;
Doc : in out Wiki.Documents.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.Documents.Document);
private
type Parser is tagged limited record
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Syntax : Wiki_Syntax;
Document : Wiki.Documents.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 : Wiki.Strings.WChar;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wiki.Strings.WChar);
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 Wiki.Strings.WChar);
-- 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 Wiki.Strings.WChar);
-- 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 Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Boolean;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
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.Documents;
with Wiki.Streams;
-- === Wiki Parsers ===
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt>
-- instance with headers, paragraphs, links, and other elements.
--
-- Doc : Wiki.Documents.Document;
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- <tt>Set_Syntax</tt> procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that
-- the filter added last is called first.
--
-- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream
-- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure
-- completes, the <tt>Document</tt> instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
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 := 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 Wiki.Strings.WString;
Doc : in out Wiki.Documents.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.Documents.Document);
private
type Parser is tagged limited record
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Syntax : Wiki_Syntax;
Document : Wiki.Documents.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 : Wiki.Strings.WChar;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wiki.Strings.WChar);
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 Wiki.Strings.WChar);
-- 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 Wiki.Strings.WChar);
-- 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 Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Boolean;
type String_Array is array (Positive range <>) of Wiki.String_Access;
-- Extract a list of parameters separated by the given separator (ex: '|').
procedure Parse_Parameters (P : in out Parser;
Separator : in Wiki.Strings.WChar;
Terminator : in Wiki.Strings.WChar;
Names : in String_Array);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
end Wiki.Parsers;
|
Declare the Parse_Parameters procedure
|
Declare the Parse_Parameters procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
785641f0d9035b41c357a45a33b385d3333a1fc3
|
src/wiki-writers.ads
|
src/wiki-writers.ads
|
-----------------------------------------------------------------------
-- wiki-writers -- Wiki writers
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
-- == Writer interfaces ==
-- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write
-- their outputs.
--
package Wiki.Writers is
use Ada.Strings.Wide_Wide_Unbounded;
type Writer_Type is limited interface;
type Writer_Type_Access is access all Writer_Type'Class;
procedure Write (Writer : in out Writer_Type;
Content : in Wide_Wide_String) is abstract;
-- Write a single character to the string builder.
procedure Write (Writer : in out Writer_Type;
Char : in Wide_Wide_Character) is abstract;
procedure Write (Writer : in out Writer_Type;
Content : in Unbounded_Wide_Wide_String) is abstract;
type Html_Writer_Type is limited interface and Writer_Type;
type Html_Writer_Type_Access is access all Html_Writer_Type'Class;
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wide_Wide_String) is abstract;
-- Start an XML element with the given name.
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is abstract;
-- Closes an XML element of the given name.
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is abstract;
-- Write a text escaping any character as necessary.
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Attribute (Writer : in out Html_Writer_Type'Class;
Name : in String;
Content : in String);
end Wiki.Writers;
|
-----------------------------------------------------------------------
-- wiki-writers -- Wiki writers
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
-- == Writer interfaces ==
-- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write
-- their outputs.
--
-- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to
-- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser
-- repeatedly while scanning the Wiki content.
package Wiki.Writers is
use Ada.Strings.Wide_Wide_Unbounded;
type Input_Stream is limited interface;
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
procedure Read (Input : in out Input_Stream;
Char : out Wide_Wide_Character;
Eof : out Boolean) is abstract;
type Writer_Type is limited interface;
type Writer_Type_Access is access all Writer_Type'Class;
procedure Write (Writer : in out Writer_Type;
Content : in Wide_Wide_String) is abstract;
-- Write a single character to the string builder.
procedure Write (Writer : in out Writer_Type;
Char : in Wide_Wide_Character) is abstract;
procedure Write (Writer : in out Writer_Type;
Content : in Unbounded_Wide_Wide_String) is abstract;
type Html_Writer_Type is limited interface and Writer_Type;
type Html_Writer_Type_Access is access all Html_Writer_Type'Class;
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wide_Wide_String) is abstract;
-- Start an XML element with the given name.
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is abstract;
-- Closes an XML element of the given name.
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is abstract;
-- Write a text escaping any character as necessary.
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Attribute (Writer : in out Html_Writer_Type'Class;
Name : in String;
Content : in String);
end Wiki.Writers;
|
Declare the Input_Stream interface
|
Declare the Input_Stream interface
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
734262e4d6a834ccbd45b51751b94c1e0e59b8b6
|
ibv_message_passing_ada_project/source/ibv_controller_process/ibv_controller_process_main.adb
|
ibv_message_passing_ada_project/source/ibv_controller_process/ibv_controller_process_main.adb
|
-- @file ibv_controller_process_main.adb
-- @date 11 Feb 2018
-- @author Chester Gillon
-- @details The main for the controller process written in Ada with communicates with
-- worker processing written in C via the ibv_message_transport library.
with ada.Text_IO;
with Interfaces.C;
use Interfaces.C;
with ibv_message_bw_interface_h;
with ibv_controller_worker_messages_h;
with Ada.Assertions;
with Ada.Numerics.Discrete_Random;
with stdint_h;
procedure Ibv_Controller_Process_Main is
type all_workers is range ibv_controller_worker_messages_h.FIRST_WORKER_NODE_ID .. ibv_controller_worker_messages_h.LAST_WORKER_NODE_ID;
type paths_to_workers_array is array (all_workers) of
ibv_message_bw_interface_h.tx_message_context_handle;
package next_worker_random is new Ada.Numerics.Discrete_Random (all_workers);
type random_int_range is range 0..65535;
package data_to_sum_random is new Ada.Numerics.Discrete_Random (random_int_range);
type num_ints_range is range 1..ibv_controller_worker_messages_h.MAX_INTEGERS_TO_SUM;
package num_ints_to_sum_random is new Ada.Numerics.Discrete_Random (num_ints_range);
-- @brief Wait for all worker processes to report they are ready to run the test
procedure await_workers_ready (communication_context : in ibv_message_bw_interface_h.communication_context_handle) is
rx_buffer : access ibv_message_bw_interface_h.rx_api_message_buffer;
num_remaining_workers : natural;
begin
num_remaining_workers := ibv_controller_worker_messages_h.NUM_WORKERS;
while num_remaining_workers > 0 loop
rx_buffer := ibv_message_bw_interface_h.await_any_rx_message (communication_context);
declare
msgs : ibv_controller_worker_messages_h.worker_to_controller_msgs;
pragma Import (C, msgs);
for msgs'Address use rx_buffer.data;
max_name_index : constant Interfaces.C.size_t := Interfaces.C.size_t (msgs.worker_ready.worker_executable_pathname_len) - 1;
begin
case ibv_controller_worker_messages_h.controller_worker_msg_ids'Val(rx_buffer.header.message_id) is
when ibv_controller_worker_messages_h.CW_WORKER_READY =>
ada.Text_IO.Put_Line ("worker " & stdint_h.uint32_t'Image (rx_buffer.header.source_instance) & " : " &
Interfaces.C.To_Ada (Item => msgs.worker_ready.worker_executable_pathname(0..max_name_index), Trim_Nul => false));
when others =>
raise Ada.Assertions.Assertion_Error with
"await_workers_ready unexpected message_id " & stdint_h.uint32_t'Image (rx_buffer.header.message_id);
end case;
end;
ibv_message_bw_interface_h.free_message (rx_buffer);
num_remaining_workers := num_remaining_workers - 1;
end loop;
end await_workers_ready;
-- @brief Process all available CW_SUM_RESULT replies from the workers
-- @detail This verifies that the expected sum has been returned, by using the returned
-- request_id to seed the same same random number generators for the number and
-- data values sent to calculate an expected sum.
-- This avoids needing to keep track of the outstanding request messages.
procedure process_sum_result_replies (communication_context : in ibv_message_bw_interface_h.communication_context_handle;
num_outstanding_replies : in out natural) is
rx_buffer : access ibv_message_bw_interface_h.rx_api_message_buffer;
begin
loop
rx_buffer := ibv_message_bw_interface_h.poll_rx_paths (communication_context);
if rx_buffer /= null then
declare
msgs : ibv_controller_worker_messages_h.worker_to_controller_msgs;
pragma Import (C, msgs);
for msgs'Address use rx_buffer.data;
expected_sum : natural;
data_generator : data_to_sum_random.Generator;
num_ints_generator : num_ints_to_sum_random.Generator;
begin
case ibv_controller_worker_messages_h.controller_worker_msg_ids'Val(rx_buffer.header.message_id) is
when ibv_controller_worker_messages_h.CW_SUM_RESULT =>
data_to_sum_random.Reset (Gen => data_generator,
Initiator => Standard.Integer(msgs.sum_result.request_id));
num_ints_to_sum_random.Reset (Gen => num_ints_generator,
Initiator => Standard.Integer(msgs.sum_result.request_id));
expected_sum := 0;
for ints_to_sum in 1 .. num_ints_to_sum_random.Random (num_ints_generator) loop
expected_sum := expected_sum + natural (data_to_sum_random.Random (data_generator));
end loop;
if expected_sum /= natural (msgs.sum_result.sum) then
raise Ada.Assertions.Assertion_Error with
"expected_sum=" & Natural'Image (expected_sum) & " actual_sum=" & stdint_h.uint32_t'Image (msgs.sum_result.sum);
end if;
num_outstanding_replies := num_outstanding_replies - 1;
ibv_message_bw_interface_h.free_message (rx_buffer);
when others =>
raise Ada.Assertions.Assertion_Error with
"process_sum_result_replies unexpected message_id " & stdint_h.uint32_t'Image (rx_buffer.header.message_id);
end case;
end;
else
exit;
end if;
end loop;
end process_sum_result_replies;
-- @brief Send a CW_SUM_INTEGERS message to a worker.
-- @details The number of integers to sum, and their values, are generated with a psuedo-random
-- pattern. This acts as a test of variable length messages.
procedure send_sum_integers (tx_buffer : access ibv_message_bw_interface_h.tx_api_message_buffer;
request_id : in Natural) is
msgs : ibv_controller_worker_messages_h.controller_to_worker_msgs;
pragma Import (C, msgs);
for msgs'Address use tx_buffer.data;
data_generator : data_to_sum_random.Generator;
num_ints_generator : num_ints_to_sum_random.Generator;
begin
data_to_sum_random.Reset (Gen => data_generator, Initiator => request_id);
num_ints_to_sum_random.Reset (Gen => num_ints_generator, Initiator => request_id);
tx_buffer.header.message_id := ibv_controller_worker_messages_h.controller_worker_msg_ids'Pos
(ibv_controller_worker_messages_h.CW_SUM_INTEGERS);
msgs.sum_integers.request_id := Interfaces.C.unsigned (request_id);
msgs.sum_integers.num_integers_to_sum :=
Interfaces.C.unsigned (num_ints_to_sum_random.Random (num_ints_generator));
for data_index in 0 .. (msgs.sum_integers.num_integers_to_sum - 1) loop
msgs.sum_integers.integers_to_sum(Integer(data_index)) :=
Interfaces.C.unsigned (data_to_sum_random.Random (data_generator));
end loop;
tx_buffer.header.message_length := msgs.sum_integers.integers_to_sum'Position +
((msgs.sum_integers.num_integers_to_sum * msgs.sum_integers.integers_to_sum(0)'Size) / 8);
ibv_message_bw_interface_h.send_message (tx_buffer);
end send_sum_integers;
-- @details Perform a test by sending a number of CW_SUM_INTEGERS messages to the workers,
-- and waiting for and then checking the CW_SUM_RESULT reply messages.
procedure perform_sum_integer_test (communication_context : in ibv_message_bw_interface_h.communication_context_handle;
paths_to_workers : in paths_to_workers_array;
num_requests_per_worker : in out ibv_controller_worker_messages_h.request_shutdown_msg_num_requests_per_worker_array) is
num_unsent_requests : natural := 10000;
num_outstanding_replies : natural := 0;
next_request_id : natural := 1;
next_worker_generator : next_worker_random.Generator;
worker_node_id : all_workers;
tx_buffer : access ibv_message_bw_interface_h.tx_api_message_buffer;
begin
-- Send requests to the workers, and process the reponses, until all requests
-- have been sent
worker_node_id := next_worker_random.Random (next_worker_generator);
while num_unsent_requests > 0 loop
process_sum_result_replies (communication_context => communication_context,
num_outstanding_replies => num_outstanding_replies);
tx_buffer := ibv_message_bw_interface_h.get_send_buffer_no_wait (paths_to_workers(worker_node_id));
if tx_buffer /= null then
declare
worker_node_index : constant Natural := natural(worker_node_id) - natural(all_workers'First);
begin
send_sum_integers (tx_buffer => tx_buffer, request_id => next_request_id);
num_unsent_requests := num_unsent_requests - 1;
num_outstanding_replies := num_outstanding_replies + 1;
num_requests_per_worker(worker_node_index) := num_requests_per_worker(worker_node_index) + 1;
worker_node_id := next_worker_random.Random (next_worker_generator);
next_request_id := next_request_id + 1;
end;
end if;
end loop;
-- Wait for outstanding replies from the workers
while num_outstanding_replies > 0 loop
process_sum_result_replies (communication_context => communication_context,
num_outstanding_replies => num_outstanding_replies);
end loop;
end perform_sum_integer_test;
-- @brief Send a message to all workers to tell them to shutdown
procedure shutdown_workers (paths_to_workers : in paths_to_workers_array;
num_requests_per_worker : in ibv_controller_worker_messages_h.request_shutdown_msg_num_requests_per_worker_array) is
tx_buffer : access ibv_message_bw_interface_h.tx_api_message_buffer;
begin
for node_id in all_workers loop
tx_buffer := ibv_message_bw_interface_h.get_send_buffer (paths_to_workers (node_id));
declare
msgs : ibv_controller_worker_messages_h.controller_to_worker_msgs;
pragma Import (C, msgs);
for msgs'Address use tx_buffer.data;
begin
msgs.request_shutdown.num_requests_per_worker := num_requests_per_worker;
tx_buffer.header.message_id := ibv_controller_worker_messages_h.controller_worker_msg_ids'Pos
(ibv_controller_worker_messages_h.CW_REQUEST_SHUTDOWN);
tx_buffer.header.message_length := msgs.request_shutdown'Size / 8;
ibv_message_bw_interface_h.send_message (tx_buffer);
end;
end loop;
end shutdown_workers;
communication_context : ibv_message_bw_interface_h.communication_context_handle;
paths_to_workers : paths_to_workers_array;
num_requests_per_worker : ibv_controller_worker_messages_h.request_shutdown_msg_num_requests_per_worker_array := (others => 0);
begin
-- Initialise, establishing connection with the workers
ibv_controller_worker_messages_h.register_controller_worker_messages;
communication_context :=
ibv_message_bw_interface_h.communication_context_initialise (Interfaces.C.int (ibv_controller_worker_messages_h.CONTROLLER_NODE_ID));
for node_id in all_workers loop
paths_to_workers(node_id) :=
ibv_message_bw_interface_h.get_tx_path_handle (context => communication_context,
destination_node => Interfaces.C.int (node_id),
instance => ibv_controller_worker_messages_h.controller_worker_path_instances'Pos
(ibv_controller_worker_messages_h.CONTROLLER_TO_WORKER_PATH));
end loop;
await_workers_ready (communication_context);
-- Run the test, communicating with the workers
perform_sum_integer_test (communication_context => communication_context, paths_to_workers => paths_to_workers,
num_requests_per_worker => num_requests_per_worker);
-- Finalise, shuting down the workers
shutdown_workers (paths_to_workers => paths_to_workers, num_requests_per_worker => num_requests_per_worker);
ibv_message_bw_interface_h.communication_context_finalise (communication_context);
end Ibv_Controller_Process_Main;
|
-- @file ibv_controller_process_main.adb
-- @date 11 Feb 2018
-- @author Chester Gillon
-- @details The main for the controller process written in Ada with communicates with
-- worker processing written in C via the ibv_message_transport library.
pragma Restrictions (No_Exceptions);
with ada.Text_IO;
with Interfaces.C;
use Interfaces.C;
with Interfaces.C.Strings;
with Interfaces.C.Extensions;
with ibv_message_bw_interface_h;
with ibv_controller_worker_messages_h;
with Ada.Assertions;
with Ada.Numerics.Discrete_Random;
with stdint_h;
procedure Ibv_Controller_Process_Main is
type all_workers is range ibv_controller_worker_messages_h.FIRST_WORKER_NODE_ID .. ibv_controller_worker_messages_h.LAST_WORKER_NODE_ID;
type paths_to_workers_array is array (all_workers) of
ibv_message_bw_interface_h.tx_message_context_handle;
package next_worker_random is new Ada.Numerics.Discrete_Random (all_workers);
type random_int_range is range 0..65535;
package data_to_sum_random is new Ada.Numerics.Discrete_Random (random_int_range);
type num_ints_range is range 1..ibv_controller_worker_messages_h.MAX_INTEGERS_TO_SUM;
package num_ints_to_sum_random is new Ada.Numerics.Discrete_Random (num_ints_range);
-- @brief Wait for all worker processes to report they are ready to run the test
procedure await_workers_ready (communication_context : in ibv_message_bw_interface_h.communication_context_handle) is
rx_buffer : access ibv_message_bw_interface_h.rx_api_message_buffer;
num_remaining_workers : natural;
begin
num_remaining_workers := ibv_controller_worker_messages_h.NUM_WORKERS;
while num_remaining_workers > 0 loop
rx_buffer := ibv_message_bw_interface_h.await_any_rx_message (communication_context);
declare
msgs : ibv_controller_worker_messages_h.worker_to_controller_msgs;
pragma Import (C, msgs);
for msgs'Address use rx_buffer.data;
max_name_index : constant Interfaces.C.size_t := Interfaces.C.size_t (msgs.worker_ready.worker_executable_pathname_len) - 1;
begin
case ibv_controller_worker_messages_h.controller_worker_msg_ids'Val(rx_buffer.header.message_id) is
when ibv_controller_worker_messages_h.CW_WORKER_READY =>
ada.Text_IO.Put_Line ("worker " & stdint_h.uint32_t'Image (rx_buffer.header.source_instance) & " : " &
Interfaces.C.To_Ada (Item => msgs.worker_ready.worker_executable_pathname(0..max_name_index), Trim_Nul => false));
when others =>
ibv_message_bw_interface_h.check_assert (assertion => Interfaces.C.Extensions.bool (false),
message => Interfaces.C.Strings.New_String ("await_workers_ready unexpected message"));
end case;
end;
ibv_message_bw_interface_h.free_message (rx_buffer);
num_remaining_workers := num_remaining_workers - 1;
end loop;
end await_workers_ready;
-- @brief Process all available CW_SUM_RESULT replies from the workers
-- @detail This verifies that the expected sum has been returned, by using the returned
-- request_id to seed the same same random number generators for the number and
-- data values sent to calculate an expected sum.
-- This avoids needing to keep track of the outstanding request messages.
procedure process_sum_result_replies (communication_context : in ibv_message_bw_interface_h.communication_context_handle;
num_outstanding_replies : in out natural) is
rx_buffer : access ibv_message_bw_interface_h.rx_api_message_buffer;
begin
loop
rx_buffer := ibv_message_bw_interface_h.poll_rx_paths (communication_context);
if rx_buffer /= null then
declare
msgs : ibv_controller_worker_messages_h.worker_to_controller_msgs;
pragma Import (C, msgs);
for msgs'Address use rx_buffer.data;
expected_sum : natural;
data_generator : data_to_sum_random.Generator;
num_ints_generator : num_ints_to_sum_random.Generator;
begin
case ibv_controller_worker_messages_h.controller_worker_msg_ids'Val(rx_buffer.header.message_id) is
when ibv_controller_worker_messages_h.CW_SUM_RESULT =>
data_to_sum_random.Reset (Gen => data_generator,
Initiator => Standard.Integer(msgs.sum_result.request_id));
num_ints_to_sum_random.Reset (Gen => num_ints_generator,
Initiator => Standard.Integer(msgs.sum_result.request_id));
expected_sum := 0;
for ints_to_sum in 1 .. num_ints_to_sum_random.Random (num_ints_generator) loop
expected_sum := expected_sum + natural (data_to_sum_random.Random (data_generator));
end loop;
if expected_sum /= natural (msgs.sum_result.sum) then
ibv_message_bw_interface_h.check_assert (assertion => Interfaces.C.Extensions.bool (false),
message => Interfaces.C.Strings.New_String ("process_sum_result_replies wrong sum"));
end if;
num_outstanding_replies := num_outstanding_replies - 1;
ibv_message_bw_interface_h.free_message (rx_buffer);
when others =>
ibv_message_bw_interface_h.check_assert (assertion => Interfaces.C.Extensions.bool (false),
message => Interfaces.C.Strings.New_String ("process_sum_result_replies unexpected message"));
end case;
end;
else
exit;
end if;
end loop;
end process_sum_result_replies;
-- @brief Send a CW_SUM_INTEGERS message to a worker.
-- @details The number of integers to sum, and their values, are generated with a psuedo-random
-- pattern. This acts as a test of variable length messages.
procedure send_sum_integers (tx_buffer : access ibv_message_bw_interface_h.tx_api_message_buffer;
request_id : in Natural) is
msgs : ibv_controller_worker_messages_h.controller_to_worker_msgs;
pragma Import (C, msgs);
for msgs'Address use tx_buffer.data;
data_generator : data_to_sum_random.Generator;
num_ints_generator : num_ints_to_sum_random.Generator;
begin
data_to_sum_random.Reset (Gen => data_generator, Initiator => request_id);
num_ints_to_sum_random.Reset (Gen => num_ints_generator, Initiator => request_id);
tx_buffer.header.message_id := ibv_controller_worker_messages_h.controller_worker_msg_ids'Pos
(ibv_controller_worker_messages_h.CW_SUM_INTEGERS);
msgs.sum_integers.request_id := Interfaces.C.unsigned (request_id);
msgs.sum_integers.num_integers_to_sum :=
Interfaces.C.unsigned (num_ints_to_sum_random.Random (num_ints_generator));
for data_index in 0 .. (msgs.sum_integers.num_integers_to_sum - 1) loop
msgs.sum_integers.integers_to_sum(Integer(data_index)) :=
Interfaces.C.unsigned (data_to_sum_random.Random (data_generator));
end loop;
tx_buffer.header.message_length := msgs.sum_integers.integers_to_sum'Position +
((msgs.sum_integers.num_integers_to_sum * msgs.sum_integers.integers_to_sum(0)'Size) / 8);
ibv_message_bw_interface_h.send_message (tx_buffer);
end send_sum_integers;
-- @details Perform a test by sending a number of CW_SUM_INTEGERS messages to the workers,
-- and waiting for and then checking the CW_SUM_RESULT reply messages.
procedure perform_sum_integer_test (communication_context : in ibv_message_bw_interface_h.communication_context_handle;
paths_to_workers : in paths_to_workers_array;
num_requests_per_worker : in out ibv_controller_worker_messages_h.request_shutdown_msg_num_requests_per_worker_array) is
num_unsent_requests : natural := 10000;
num_outstanding_replies : natural := 0;
next_request_id : natural := 1;
next_worker_generator : next_worker_random.Generator;
worker_node_id : all_workers;
tx_buffer : access ibv_message_bw_interface_h.tx_api_message_buffer;
begin
-- Send requests to the workers, and process the reponses, until all requests
-- have been sent
worker_node_id := next_worker_random.Random (next_worker_generator);
while num_unsent_requests > 0 loop
process_sum_result_replies (communication_context => communication_context,
num_outstanding_replies => num_outstanding_replies);
tx_buffer := ibv_message_bw_interface_h.get_send_buffer_no_wait (paths_to_workers(worker_node_id));
if tx_buffer /= null then
declare
worker_node_index : constant Natural := natural(worker_node_id) - natural(all_workers'First);
begin
send_sum_integers (tx_buffer => tx_buffer, request_id => next_request_id);
num_unsent_requests := num_unsent_requests - 1;
num_outstanding_replies := num_outstanding_replies + 1;
num_requests_per_worker(worker_node_index) := num_requests_per_worker(worker_node_index) + 1;
worker_node_id := next_worker_random.Random (next_worker_generator);
next_request_id := next_request_id + 1;
end;
end if;
end loop;
-- Wait for outstanding replies from the workers
while num_outstanding_replies > 0 loop
process_sum_result_replies (communication_context => communication_context,
num_outstanding_replies => num_outstanding_replies);
end loop;
end perform_sum_integer_test;
-- @brief Send a message to all workers to tell them to shutdown
procedure shutdown_workers (paths_to_workers : in paths_to_workers_array;
num_requests_per_worker : in ibv_controller_worker_messages_h.request_shutdown_msg_num_requests_per_worker_array) is
tx_buffer : access ibv_message_bw_interface_h.tx_api_message_buffer;
begin
for node_id in all_workers loop
tx_buffer := ibv_message_bw_interface_h.get_send_buffer (paths_to_workers (node_id));
declare
msgs : ibv_controller_worker_messages_h.controller_to_worker_msgs;
pragma Import (C, msgs);
for msgs'Address use tx_buffer.data;
begin
msgs.request_shutdown.num_requests_per_worker := num_requests_per_worker;
tx_buffer.header.message_id := ibv_controller_worker_messages_h.controller_worker_msg_ids'Pos
(ibv_controller_worker_messages_h.CW_REQUEST_SHUTDOWN);
tx_buffer.header.message_length := msgs.request_shutdown'Size / 8;
ibv_message_bw_interface_h.send_message (tx_buffer);
end;
end loop;
end shutdown_workers;
communication_context : ibv_message_bw_interface_h.communication_context_handle;
paths_to_workers : paths_to_workers_array;
num_requests_per_worker : ibv_controller_worker_messages_h.request_shutdown_msg_num_requests_per_worker_array := (others => 0);
begin
-- Initialise, establishing connection with the workers
ibv_controller_worker_messages_h.register_controller_worker_messages;
communication_context :=
ibv_message_bw_interface_h.communication_context_initialise (Interfaces.C.int (ibv_controller_worker_messages_h.CONTROLLER_NODE_ID));
for node_id in all_workers loop
paths_to_workers(node_id) :=
ibv_message_bw_interface_h.get_tx_path_handle (context => communication_context,
destination_node => Interfaces.C.int (node_id),
instance => ibv_controller_worker_messages_h.controller_worker_path_instances'Pos
(ibv_controller_worker_messages_h.CONTROLLER_TO_WORKER_PATH));
end loop;
await_workers_ready (communication_context);
-- Run the test, communicating with the workers
perform_sum_integer_test (communication_context => communication_context, paths_to_workers => paths_to_workers,
num_requests_per_worker => num_requests_per_worker);
-- Finalise, shuting down the workers
shutdown_workers (paths_to_workers => paths_to_workers, num_requests_per_worker => num_requests_per_worker);
ibv_message_bw_interface_h.communication_context_finalise (communication_context);
end Ibv_Controller_Process_Main;
|
Use the C check_assert to report a failure, rather than raising an Ada Assertion_Error. This reduces the number of branches reported in the Coverage for ibv_controller_process_main.adb from 129 hit out of 274 to 84 hit out of 158.
|
Use the C check_assert to report a failure, rather than raising an Ada Assertion_Error. This reduces the number of branches reported in the Coverage for ibv_controller_process_main.adb from 129 hit out of 274 to 84 hit out of 158.
|
Ada
|
mit
|
Chester-Gillon/ibv_message_passing,Chester-Gillon/ibv_message_passing,Chester-Gillon/ibv_message_passing
|
0fdd7bec725f4324586012cf8c41fe8a9858e196
|
regtests/ado-audits-tests.adb
|
regtests/ado-audits-tests.adb
|
-----------------------------------------------------------------------
-- ado-audits-tests -- Audit tests
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with Ada.Text_IO;
with Regtests.Audits.Model;
with ADO.SQL;
with ADO.Sessions.Entities;
package body ADO.Audits.Tests is
package Caller is new Util.Test_Caller (Test, "ADO.Audits");
type Test_Audit_Manager is new Audit_Manager with null record;
-- Save the audit changes in the database.
overriding
procedure Save (Manager : in out Test_Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array);
Audit_Instance : aliased Test_Audit_Manager;
-- Save the audit changes in the database.
overriding
procedure Save (Manager : in out Test_Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array) is
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Kind : constant ADO.Entity_Type
:= ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key);
begin
for C of Changes loop
declare
Audit : Regtests.Audits.Model.Audit_Ref;
begin
Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key));
Audit.Set_Entity_Type (Kind);
Audit.Set_Old_Value (UBO.To_String (C.Old_Value));
Audit.Set_New_Value (UBO.To_String (C.New_Value));
Audit.Set_Date (Now);
Audit.Save (Session);
end;
end loop;
end Save;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Audits.Audit_Field",
Test_Audit_Field'Access);
end Add_Tests;
procedure Set_Up (T : in out Test) is
begin
Regtests.Set_Audit_Manager (Audit_Instance'Access);
end Set_Up;
-- ------------------------------
-- Test populating Audit_Fields
-- ------------------------------
procedure Test_Audit_Field (T : in out Test) is
type Identifier_Array is array (1 .. 10) of ADO.Identifier;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Email : Regtests.Audits.Model.Email_Ref;
List : Identifier_Array;
begin
for I in List'Range loop
Email := Regtests.Audits.Model.Null_Email;
Email.Set_Email ("Email" & Util.Strings.Image (I) & "@nowhere.com");
Email.Set_Status (ADO.Nullable_Integer '(23, False));
Email.Save (DB);
List (I) := Email.Get_Id;
end loop;
DB.Commit;
for Id of List loop
Email.Load (DB, Id);
Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False));
Email.Save (DB);
Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@here.com");
Email.Save (DB);
Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@there.com");
Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False));
Email.Save (DB);
end loop;
DB.Commit;
for Id of List loop
Email.Load (DB, Id);
Email.Set_Status (ADO.Null_Integer);
Email.Save (DB);
end loop;
DB.Commit;
declare
Query : ADO.SQL.Query;
Audit_List : Regtests.Audits.Model.Audit_Vector;
begin
Query.Set_Filter ("entity_id = :entity_id");
for Id of List loop
Query.Bind_Param ("entity_id", Id);
Regtests.Audits.Model.List (Audit_List, DB, Query);
for A of Audit_List loop
Ada.Text_IO.Put_Line (ADO.Identifier'Image (Id) & " "
& ADO.Identifier'Image (A.Get_Id)
& " " & A.Get_Old_Value & " - "
& A.Get_New_Value);
Util.Tests.Assert_Equals (T, Natural (Id), Natural (A.Get_Entity_Id),
"Invalid audit record: id is wrong");
end loop;
Util.Tests.Assert_Equals (T, 7, Natural (Audit_List.Length),
"Invalid number of audit records");
end loop;
end;
end Test_Audit_Field;
end ADO.Audits.Tests;
|
-----------------------------------------------------------------------
-- ado-audits-tests -- Audit tests
-- Copyright (C) 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with Ada.Text_IO;
with Regtests.Audits.Model;
with ADO.SQL;
with ADO.Sessions.Entities;
package body ADO.Audits.Tests is
package Caller is new Util.Test_Caller (Test, "ADO.Audits");
type Test_Audit_Manager is new Audit_Manager with null record;
-- Save the audit changes in the database.
overriding
procedure Save (Manager : in out Test_Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array);
Audit_Instance : aliased Test_Audit_Manager;
-- Save the audit changes in the database.
overriding
procedure Save (Manager : in out Test_Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array) is
pragma Unreferenced (Manager);
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Kind : constant ADO.Entity_Type
:= ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key);
begin
for C of Changes loop
declare
Audit : Regtests.Audits.Model.Audit_Ref;
begin
Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key));
Audit.Set_Entity_Type (Kind);
Audit.Set_Old_Value (UBO.To_String (C.Old_Value));
Audit.Set_New_Value (UBO.To_String (C.New_Value));
Audit.Set_Date (Now);
Audit.Save (Session);
end;
end loop;
end Save;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Audits.Audit_Field",
Test_Audit_Field'Access);
end Add_Tests;
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
Regtests.Set_Audit_Manager (Audit_Instance'Access);
end Set_Up;
-- ------------------------------
-- Test populating Audit_Fields
-- ------------------------------
procedure Test_Audit_Field (T : in out Test) is
type Identifier_Array is array (1 .. 10) of ADO.Identifier;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Email : Regtests.Audits.Model.Email_Ref;
List : Identifier_Array;
begin
for I in List'Range loop
Email := Regtests.Audits.Model.Null_Email;
Email.Set_Email ("Email" & Util.Strings.Image (I) & "@nowhere.com");
Email.Set_Status (ADO.Nullable_Integer '(23, False));
Email.Save (DB);
List (I) := Email.Get_Id;
end loop;
DB.Commit;
for Id of List loop
Email.Load (DB, Id);
Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False));
Email.Save (DB);
Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@here.com");
Email.Save (DB);
Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@there.com");
Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False));
Email.Save (DB);
end loop;
DB.Commit;
for Id of List loop
Email.Load (DB, Id);
Email.Set_Status (ADO.Null_Integer);
Email.Save (DB);
end loop;
DB.Commit;
declare
Query : ADO.SQL.Query;
Audit_List : Regtests.Audits.Model.Audit_Vector;
begin
Query.Set_Filter ("entity_id = :entity_id");
for Id of List loop
Query.Bind_Param ("entity_id", Id);
Regtests.Audits.Model.List (Audit_List, DB, Query);
for A of Audit_List loop
Ada.Text_IO.Put_Line (ADO.Identifier'Image (Id) & " "
& ADO.Identifier'Image (A.Get_Id)
& " " & A.Get_Old_Value & " - "
& A.Get_New_Value);
Util.Tests.Assert_Equals (T, Natural (Id), Natural (A.Get_Entity_Id),
"Invalid audit record: id is wrong");
end loop;
Util.Tests.Assert_Equals (T, 7, Natural (Audit_List.Length),
"Invalid number of audit records");
end loop;
end;
end Test_Audit_Field;
end ADO.Audits.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
1c4b81c14f86f4ef8e4577eb024edf8bb508eec0
|
regtests/util-dates-tests.adb
|
regtests/util-dates-tests.adb
|
-----------------------------------------------------------------------
-- util-dates-tests - Test for dates
-- Copyright (C) 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Dates.ISO8601;
package body Util.Dates.Tests is
package Caller is new Util.Test_Caller (Test, "Dates");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Image",
Test_ISO8601_Image'Access);
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value",
Test_ISO8601_Value'Access);
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value (Errors)",
Test_ISO8601_Error'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Is_Same_Day",
Test_Is_Same_Day'Access);
end Add_Tests;
-- ------------------------------
-- Test converting a date in ISO8601.
-- ------------------------------
procedure Test_ISO8601_Image (T : in out Test) is
T1 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (1980, 1, 2, 10, 30, 23);
begin
Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1),
"Invalid Image");
Util.Tests.Assert_Equals (T, "1980", ISO8601.Image (T1, ISO8601.YEAR),
"Invalid Image (YEAR precision)");
Util.Tests.Assert_Equals (T, "1980-01", ISO8601.Image (T1, ISO8601.MONTH),
"Invalid Image (MONTH precision)");
Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1, ISO8601.DAY),
"Invalid Image (DAY precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10", ISO8601.Image (T1, ISO8601.HOUR),
"Invalid Image (DAY precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10:30", ISO8601.Image (T1, ISO8601.MINUTE),
"Invalid Image (MINUTE precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10:30:23", ISO8601.Image (T1, ISO8601.SECOND),
"Invalid Image (SECOND precision)");
end Test_ISO8601_Image;
-- ------------------------------
-- Test converting a string in ISO8601 into a date.
-- ------------------------------
procedure Test_ISO8601_Value (T : in out Test) is
Date : Ada.Calendar.Time;
begin
Date := ISO8601.Value ("1980");
Util.Tests.Assert_Equals (T, "1980-01-01", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-02");
Util.Tests.Assert_Equals (T, "1980-02", ISO8601.Image (Date, ISO8601.MONTH));
Date := ISO8601.Value ("1980-03-04");
Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-03-04");
Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-12-31");
Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date));
Date := ISO8601.Value ("19801231");
Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-12-31T11:23");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23", ISO8601.Image (Date, ISO8601.MINUTE));
Date := ISO8601.Value ("1980-12-31T11:23:34");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34", ISO8601.Image (Date, ISO8601.SECOND));
Date := ISO8601.Value ("1980-12-31T11:23:34.123");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34.123+00:00",
ISO8601.Image (Date, ISO8601.SUBSECOND));
Date := ISO8601.Value ("1980-12-31T11:23:34.123+04:30");
-- The date was normalized in GMT
Util.Tests.Assert_Equals (T, "1980-12-31T06:53:34.123+00:00",
ISO8601.Image (Date, ISO8601.SUBSECOND));
end Test_ISO8601_Value;
-- ------------------------------
-- Test value convertion errors.
-- ------------------------------
procedure Test_ISO8601_Error (T : in out Test) is
procedure Check (Date : in String);
procedure Check (Date : in String) is
begin
declare
Unused : constant Ada.Calendar.Time := ISO8601.Value (Date);
begin
T.Fail ("No exception raised for " & Date);
end;
exception
when Constraint_Error =>
null;
end Check;
begin
Check ("");
Check ("1980-");
Check ("1980:02:03");
Check ("1980-02-03u33:33");
Check ("1980-02-03u33");
Check ("1980-13-44");
Check ("1980-12-00");
Check ("1980-12-03T25:34");
Check ("1980-12-03T10x34");
Check ("1980-12-03T10:34p");
Check ("1980-12-31T11:23:34123");
Check ("1980-12-31T11:23:34,1");
Check ("1980-12-31T11:23:34,12");
Check ("1980-12-31T11:23:34x123");
Check ("1980-12-31T11:23:34.1234");
Check ("1980-12-31T11:23:34Zp");
Check ("1980-12-31T11:23:34+2");
Check ("1980-12-31T11:23:34+23x");
Check ("1980-12-31T11:23:34+99");
Check ("1980-12-31T11:23:34+10:0");
Check ("1980-12-31T11:23:34+10:03x");
end Test_ISO8601_Error;
-- ------------------------------
-- Test Is_Same_Day operation.
-- ------------------------------
procedure Test_Is_Same_Day (T : in out Test) is
procedure Check (D1, D2 : in String;
Same_Day : in Boolean);
procedure Check (D1, D2 : in String;
Same_Day : in Boolean) is
T1 : constant Ada.Calendar.Time := ISO8601.Value (D1);
T2 : constant Ada.Calendar.Time := ISO8601.Value (D2);
begin
T.Assert (Same_Day = Is_Same_Day (T1, T2), "Invalid Is_Same_Day for " & D1 & " " & D2);
T.Assert (Same_Day = Is_Same_Day (T2, T1), "Invalid Is_Same_Day for " & D2 & " " & D1);
end Check;
begin
Check ("1980-12-31T11:23:34.123", "1980-12-31T10:23:34.123", True);
Check ("1980-12-31T11:23:34.123", "1980-12-30T10:23:34.123", False);
Check ("1980-12-31T00:00:00", "1980-12-31T23:59:59", True);
end Test_Is_Same_Day;
end Util.Dates.Tests;
|
-----------------------------------------------------------------------
-- util-dates-tests - Test for dates
-- Copyright (C) 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Dates.ISO8601;
package body Util.Dates.Tests is
package Caller is new Util.Test_Caller (Test, "Dates");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Image",
Test_ISO8601_Image'Access);
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value",
Test_ISO8601_Value'Access);
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value (Errors)",
Test_ISO8601_Error'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Is_Same_Day",
Test_Is_Same_Day'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Day_Count",
Test_Get_Day_Count'Access);
end Add_Tests;
-- ------------------------------
-- Test converting a date in ISO8601.
-- ------------------------------
procedure Test_ISO8601_Image (T : in out Test) is
T1 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (1980, 1, 2, 10, 30, 23);
begin
Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1),
"Invalid Image");
Util.Tests.Assert_Equals (T, "1980", ISO8601.Image (T1, ISO8601.YEAR),
"Invalid Image (YEAR precision)");
Util.Tests.Assert_Equals (T, "1980-01", ISO8601.Image (T1, ISO8601.MONTH),
"Invalid Image (MONTH precision)");
Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1, ISO8601.DAY),
"Invalid Image (DAY precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10", ISO8601.Image (T1, ISO8601.HOUR),
"Invalid Image (DAY precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10:30", ISO8601.Image (T1, ISO8601.MINUTE),
"Invalid Image (MINUTE precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10:30:23", ISO8601.Image (T1, ISO8601.SECOND),
"Invalid Image (SECOND precision)");
end Test_ISO8601_Image;
-- ------------------------------
-- Test converting a string in ISO8601 into a date.
-- ------------------------------
procedure Test_ISO8601_Value (T : in out Test) is
Date : Ada.Calendar.Time;
begin
Date := ISO8601.Value ("1980");
Util.Tests.Assert_Equals (T, "1980-01-01", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-02");
Util.Tests.Assert_Equals (T, "1980-02", ISO8601.Image (Date, ISO8601.MONTH));
Date := ISO8601.Value ("1980-03-04");
Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-03-04");
Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-12-31");
Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date));
Date := ISO8601.Value ("19801231");
Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-12-31T11:23");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23", ISO8601.Image (Date, ISO8601.MINUTE));
Date := ISO8601.Value ("1980-12-31T11:23:34");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34", ISO8601.Image (Date, ISO8601.SECOND));
Date := ISO8601.Value ("1980-12-31T11:23:34.123");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34.123+00:00",
ISO8601.Image (Date, ISO8601.SUBSECOND));
Date := ISO8601.Value ("1980-12-31T11:23:34.123+04:30");
-- The date was normalized in GMT
Util.Tests.Assert_Equals (T, "1980-12-31T06:53:34.123+00:00",
ISO8601.Image (Date, ISO8601.SUBSECOND));
end Test_ISO8601_Value;
-- ------------------------------
-- Test value convertion errors.
-- ------------------------------
procedure Test_ISO8601_Error (T : in out Test) is
procedure Check (Date : in String);
procedure Check (Date : in String) is
begin
declare
Unused : constant Ada.Calendar.Time := ISO8601.Value (Date);
begin
T.Fail ("No exception raised for " & Date);
end;
exception
when Constraint_Error =>
null;
end Check;
begin
Check ("");
Check ("1980-");
Check ("1980:02:03");
Check ("1980-02-03u33:33");
Check ("1980-02-03u33");
Check ("1980-13-44");
Check ("1980-12-00");
Check ("1980-12-03T25:34");
Check ("1980-12-03T10x34");
Check ("1980-12-03T10:34p");
Check ("1980-12-31T11:23:34123");
Check ("1980-12-31T11:23:34,1");
Check ("1980-12-31T11:23:34,12");
Check ("1980-12-31T11:23:34x123");
Check ("1980-12-31T11:23:34.1234");
Check ("1980-12-31T11:23:34Zp");
Check ("1980-12-31T11:23:34+2");
Check ("1980-12-31T11:23:34+23x");
Check ("1980-12-31T11:23:34+99");
Check ("1980-12-31T11:23:34+10:0");
Check ("1980-12-31T11:23:34+10:03x");
end Test_ISO8601_Error;
-- ------------------------------
-- Test Is_Same_Day operation.
-- ------------------------------
procedure Test_Is_Same_Day (T : in out Test) is
procedure Check (D1, D2 : in String;
Same_Day : in Boolean);
procedure Check (D1, D2 : in String;
Same_Day : in Boolean) is
T1 : constant Ada.Calendar.Time := ISO8601.Value (D1);
T2 : constant Ada.Calendar.Time := ISO8601.Value (D2);
begin
T.Assert (Same_Day = Is_Same_Day (T1, T2), "Invalid Is_Same_Day for " & D1 & " " & D2);
T.Assert (Same_Day = Is_Same_Day (T2, T1), "Invalid Is_Same_Day for " & D2 & " " & D1);
end Check;
begin
Check ("1980-12-31T11:23:34.123", "1980-12-31T10:23:34.123", True);
Check ("1980-12-31T11:23:34.123", "1980-12-30T10:23:34.123", False);
Check ("1980-12-31T00:00:00", "1980-12-31T23:59:59", True);
end Test_Is_Same_Day;
-- ------------------------------
-- Test Get_Day_Count operation.
-- ------------------------------
procedure Test_Get_Day_Count (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, 366, Natural (Get_Day_Count (2020)));
Util.Tests.Assert_Equals (T, 365, Natural (Get_Day_Count (1983)));
Util.Tests.Assert_Equals (T, 366, Natural (Get_Day_Count (2000)));
Util.Tests.Assert_Equals (T, 365, Natural (Get_Day_Count (2001)));
end Test_Get_Day_Count;
end Util.Dates.Tests;
|
Implement Test_Get_Day_Count and register the test for execution
|
Implement Test_Get_Day_Count and register the test for execution
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
337c9d65b4b0786870c18e58e338bff5d9de60eb
|
src/babel-files-maps.adb
|
src/babel-files-maps.adb
|
-----------------------------------------------------------------------
-- babel-files-maps -- Hash maps for files and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Babel.Files.Maps is
-- ------------------------------
-- Find the file with the given name in the file map.
-- ------------------------------
function Find (From : in File_Map;
Name : in String) return File_Cursor is
begin
return From.Find (Key => Name'Unrestricted_Access);
end Find;
-- ------------------------------
-- Find the file with the given name in the file map.
-- ------------------------------
function Find (From : in File_Map;
Name : in String) return File_Type is
Pos : constant File_Cursor := From.Find (Key => Name'Unrestricted_Access);
begin
if File_Maps.Has_Element (Pos) then
return File_Maps.Element (Pos);
else
return NO_FILE;
end if;
end Find;
-- ------------------------------
-- Find the directory with the given name in the directory map.
-- ------------------------------
function Find (From : in Directory_Map;
Name : in String) return Directory_Cursor is
begin
return From.Find (Key => Name'Unrestricted_Access);
end Find;
-- ------------------------------
-- Find the directory with the given name in the directory map.
-- ------------------------------
function Find (From : in Directory_Map;
Name : in String) return Directory_Type is
Pos : constant Directory_Cursor := From.Find (Key => Name'Unrestricted_Access);
begin
if Directory_Maps.Has_Element (Pos) then
return Directory_Maps.Element (Pos);
else
return NO_DIRECTORY;
end if;
end Find;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Differential_Container;
Element : in File_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Differential_Container;
Element : in Directory_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Differential_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Differential_Container;
Name : in String) return File_Type is
begin
return Find (From.Known_Files, Name);
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Find (From.Known_Dirs, Name);
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
overriding
procedure Set_Directory (Into : in out Differential_Container;
Directory : in Directory_Type) is
begin
Default_Container (Into).Set_Directory (Directory);
Into.Known_Files.Clear;
Into.Known_Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Prepare the differential container by setting up the known files and known
-- directories. The <tt>Update</tt> procedure is called to give access to the
-- maps that can be updated.
-- ------------------------------
procedure Prepare (Container : in out Differential_Container;
Update : access procedure (Files : in out File_Map;
Dirs : in out Directory_Map)) is
begin
Update (Container.Known_Files, Container.Known_Dirs);
end Prepare;
end Babel.Files.Maps;
|
-----------------------------------------------------------------------
-- babel-files-maps -- Hash maps for files and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Babel.Files.Maps is
-- ------------------------------
-- Find the file with the given name in the file map.
-- ------------------------------
function Find (From : in File_Map;
Name : in String) return File_Cursor is
begin
return From.Find (Key => Name'Unrestricted_Access);
end Find;
-- ------------------------------
-- Find the file with the given name in the file map.
-- ------------------------------
function Find (From : in File_Map;
Name : in String) return File_Type is
Pos : constant File_Cursor := From.Find (Key => Name'Unrestricted_Access);
begin
if File_Maps.Has_Element (Pos) then
return File_Maps.Element (Pos);
else
return NO_FILE;
end if;
end Find;
-- ------------------------------
-- Insert the file in the file map.
-- ------------------------------
procedure Insert (Into : in out File_Map;
File : in File_Type) is
begin
Into.Insert (Key => File.Name'Unrestricted_Access, New_Item => File);
end Insert;
-- ------------------------------
-- Find the directory with the given name in the directory map.
-- ------------------------------
function Find (From : in Directory_Map;
Name : in String) return Directory_Cursor is
begin
return From.Find (Key => Name'Unrestricted_Access);
end Find;
-- ------------------------------
-- Find the directory with the given name in the directory map.
-- ------------------------------
function Find (From : in Directory_Map;
Name : in String) return Directory_Type is
Pos : constant Directory_Cursor := From.Find (Key => Name'Unrestricted_Access);
begin
if Directory_Maps.Has_Element (Pos) then
return Directory_Maps.Element (Pos);
else
return NO_DIRECTORY;
end if;
end Find;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Differential_Container;
Element : in File_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Differential_Container;
Element : in Directory_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Differential_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Differential_Container;
Name : in String) return File_Type is
begin
return Find (From.Known_Files, Name);
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Find (From.Known_Dirs, Name);
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
overriding
procedure Set_Directory (Into : in out Differential_Container;
Directory : in Directory_Type) is
begin
Default_Container (Into).Set_Directory (Directory);
Into.Known_Files.Clear;
Into.Known_Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Prepare the differential container by setting up the known files and known
-- directories. The <tt>Update</tt> procedure is called to give access to the
-- maps that can be updated.
-- ------------------------------
procedure Prepare (Container : in out Differential_Container;
Update : access procedure (Files : in out File_Map;
Dirs : in out Directory_Map)) is
begin
Update (Container.Known_Files, Container.Known_Dirs);
end Prepare;
end Babel.Files.Maps;
|
Implement the Insert procedure
|
Implement the Insert procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
a1a3481660fdef56c3cfcfc8f05780b6f7c8e232
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
with AWA.Questions.Services;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
Add the user identifier (if known) to the query to get his rating for the question
|
Add the user identifier (if known) to the query to get his rating for the question
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
6faeb70e0cd8a5e38418ffdf12e932ead8725f72
|
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;
pragma Linker_Options ("-ldl");
-- -----------------------
-- 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 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;
|
Move the linker option in the generated Util.Systems.Constants package
|
Move the linker option in the generated Util.Systems.Constants package
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
73f471be81e348d452db58b1d1031c57bf7b7155
|
src/asf-components-html-factory.adb
|
src/asf-components-html-factory.adb
|
-----------------------------------------------------------------------
-- html-factory -- Factory for HTML UI Components
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Base;
with ASF.Components.Html.Text;
with ASF.Components.Html.Lists;
with ASF.Components.Html.Links;
with ASF.Components.Html.Panels;
with ASF.Components.Html.Forms;
with ASF.Views.Nodes;
package body ASF.Components.Html.Factory is
use ASF.Components.Base;
function Create_Output return UIComponent_Access;
function Create_Output_Link return UIComponent_Access;
function Create_Output_Format return UIComponent_Access;
function Create_Label return UIComponent_Access;
function Create_List return UIComponent_Access;
function Create_PanelGroup return UIComponent_Access;
function Create_Form return UIComponent_Access;
function Create_Input return UIComponent_Access;
function Create_Command return UIComponent_Access;
-- ------------------------------
-- Create an UIOutput component
-- ------------------------------
function Create_Output return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutput;
end Create_Output;
-- ------------------------------
-- Create an UIOutputLink component
-- ------------------------------
function Create_Output_Link return UIComponent_Access is
begin
return new ASF.Components.Html.Links.UIOutputLink;
end Create_Output_Link;
-- ------------------------------
-- Create an UIOutput component
-- ------------------------------
function Create_Output_Format return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutputFormat;
end Create_Output_Format;
-- ------------------------------
-- Create a label component
-- ------------------------------
function Create_Label return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UILabel;
end Create_Label;
-- ------------------------------
-- Create an UIList component
-- ------------------------------
function Create_List return UIComponent_Access is
begin
return new ASF.Components.Html.Lists.UIList;
end Create_List;
-- ------------------------------
-- Create an UIPanelGroup component
-- ------------------------------
function Create_PanelGroup return UIComponent_Access is
begin
return new ASF.Components.Html.Panels.UIPanelGroup;
end Create_PanelGroup;
-- ------------------------------
-- Create an UIForm component
-- ------------------------------
function Create_Form return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIForm;
end Create_Form;
-- ------------------------------
-- Create an UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInput;
end Create_Input;
-- ------------------------------
-- Create an UICommand component
-- ------------------------------
function Create_Command return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UICommand;
end Create_Command;
use ASF.Views.Nodes;
URI : aliased constant String := "http://java.sun.com/jsf/html";
COMMAND_BUTTON_TAG : aliased constant String := "commandButton";
FORM_TAG : aliased constant String := "form";
INPUT_TAG : aliased constant String := "input";
LABEL_TAG : aliased constant String := "label";
LIST_TAG : aliased constant String := "list";
OUTPUT_FORMAT_TAG : aliased constant String := "outputFormat";
OUTPUT_LINK_TAG : aliased constant String := "outputLink";
OUTPUT_TEXT_TAG : aliased constant String := "outputText";
PANEL_GROUP_TAG : aliased constant String := "panelGroup";
Html_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => COMMAND_BUTTON_TAG'Access,
Component => Create_Command'Access,
Tag => Create_Component_Node'Access),
2 => (Name => FORM_TAG'Access,
Component => Create_Form'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => LABEL_TAG'Access,
Component => Create_Label'Access,
Tag => Create_Component_Node'Access),
5 => (Name => LIST_TAG'Access,
Component => Create_List'Access,
Tag => Create_Component_Node'Access),
6 => (Name => OUTPUT_FORMAT_TAG'Access,
Component => Create_Output_Format'Access,
Tag => Create_Component_Node'Access),
7 => (Name => OUTPUT_LINK_TAG'Access,
Component => Create_Output_Link'Access,
Tag => Create_Component_Node'Access),
8 => (Name => OUTPUT_TEXT_TAG'Access,
Component => Create_Output'Access,
Tag => Create_Component_Node'Access),
9 => (Name => PANEL_GROUP_TAG'Access,
Component => Create_PanelGroup'Access,
Tag => Create_Component_Node'Access)
);
Html_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Html_Bindings'Access);
-- ------------------------------
-- Get the HTML component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Html_Factory'Access;
end Definition;
end ASF.Components.Html.Factory;
|
-----------------------------------------------------------------------
-- html-factory -- Factory for HTML UI Components
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Base;
with ASF.Components.Html.Text;
with ASF.Components.Html.Lists;
with ASF.Components.Html.Links;
with ASF.Components.Html.Panels;
with ASF.Components.Html.Forms;
with ASF.Views.Nodes;
package body ASF.Components.Html.Factory is
use ASF.Components.Base;
function Create_Output return UIComponent_Access;
function Create_Output_Link return UIComponent_Access;
function Create_Output_Format return UIComponent_Access;
function Create_Label return UIComponent_Access;
function Create_List return UIComponent_Access;
function Create_PanelGroup return UIComponent_Access;
function Create_Form return UIComponent_Access;
function Create_Input return UIComponent_Access;
function Create_Command return UIComponent_Access;
-- ------------------------------
-- Create an UIOutput component
-- ------------------------------
function Create_Output return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutput;
end Create_Output;
-- ------------------------------
-- Create an UIOutputLink component
-- ------------------------------
function Create_Output_Link return UIComponent_Access is
begin
return new ASF.Components.Html.Links.UIOutputLink;
end Create_Output_Link;
-- ------------------------------
-- Create an UIOutput component
-- ------------------------------
function Create_Output_Format return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UIOutputFormat;
end Create_Output_Format;
-- ------------------------------
-- Create a label component
-- ------------------------------
function Create_Label return UIComponent_Access is
begin
return new ASF.Components.Html.Text.UILabel;
end Create_Label;
-- ------------------------------
-- Create an UIList component
-- ------------------------------
function Create_List return UIComponent_Access is
begin
return new ASF.Components.Html.Lists.UIList;
end Create_List;
-- ------------------------------
-- Create an UIPanelGroup component
-- ------------------------------
function Create_PanelGroup return UIComponent_Access is
begin
return new ASF.Components.Html.Panels.UIPanelGroup;
end Create_PanelGroup;
-- ------------------------------
-- Create an UIForm component
-- ------------------------------
function Create_Form return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIForm;
end Create_Form;
-- ------------------------------
-- Create an UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UIInput;
end Create_Input;
-- ------------------------------
-- Create an UICommand component
-- ------------------------------
function Create_Command return UIComponent_Access is
begin
return new ASF.Components.Html.Forms.UICommand;
end Create_Command;
use ASF.Views.Nodes;
URI : aliased constant String := "http://java.sun.com/jsf/html";
COMMAND_BUTTON_TAG : aliased constant String := "commandButton";
FORM_TAG : aliased constant String := "form";
INPUT_SECRET_TAG : aliased constant String := "inputSecret";
INPUT_TEXT_TAG : aliased constant String := "inputText";
LABEL_TAG : aliased constant String := "label";
LIST_TAG : aliased constant String := "list";
OUTPUT_FORMAT_TAG : aliased constant String := "outputFormat";
OUTPUT_LINK_TAG : aliased constant String := "outputLink";
OUTPUT_TEXT_TAG : aliased constant String := "outputText";
PANEL_GROUP_TAG : aliased constant String := "panelGroup";
Html_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => COMMAND_BUTTON_TAG'Access,
Component => Create_Command'Access,
Tag => Create_Component_Node'Access),
2 => (Name => FORM_TAG'Access,
Component => Create_Form'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_SECRET_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
5 => (Name => LABEL_TAG'Access,
Component => Create_Label'Access,
Tag => Create_Component_Node'Access),
6 => (Name => LIST_TAG'Access,
Component => Create_List'Access,
Tag => Create_Component_Node'Access),
7 => (Name => OUTPUT_FORMAT_TAG'Access,
Component => Create_Output_Format'Access,
Tag => Create_Component_Node'Access),
8 => (Name => OUTPUT_LINK_TAG'Access,
Component => Create_Output_Link'Access,
Tag => Create_Component_Node'Access),
9 => (Name => OUTPUT_TEXT_TAG'Access,
Component => Create_Output'Access,
Tag => Create_Component_Node'Access),
10 => (Name => PANEL_GROUP_TAG'Access,
Component => Create_PanelGroup'Access,
Tag => Create_Component_Node'Access)
);
Html_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Html_Bindings'Access);
-- ------------------------------
-- Get the HTML component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Html_Factory'Access;
end Definition;
end ASF.Components.Html.Factory;
|
Rename h:input into h:inputText and add h:inputSecret
|
Rename h:input into h:inputText and add h:inputSecret
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
953e187bf6bf587a26d61094d33dd622c46325f2
|
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.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
pragma Unreferenced (DB);
pragma Unreferenced (Cookie);
begin
raise Program_Error with "Not Implemented yet";
return Null_Info;
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.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
Parser : S_Expressions.Parsers.Memory_Parser
:= S_Expressions.Parsers.Create
(Decoder_Maps.Element (Cursor).all (Cookie));
begin
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;
|
implement the Decode function
|
comment_cookies: implement the Decode function
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
867f22b00d5ccea8b5673bebe63a9e7e8bd44215
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
-- ------------------------------
procedure Set_Size (Element : in File_Type;
Size : in File_Size) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
end Babel.Files;
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
-- ------------------------------
procedure Set_Size (Element : in File_Type;
Size : in File_Size) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type) is
begin
Into.Current := Directory;
Into.Files.Clear;
Into.Dirs.Clear;
end Set_Directory;
end Babel.Files;
|
Implement the Set_Directory operation
|
Implement the Set_Directory operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
5e70c9214c9b2f70962984e171430f1afb55f667
|
src/el-contexts-default.adb
|
src/el-contexts-default.adb
|
-----------------------------------------------------------------------
-- EL.Contexts -- Default contexts for evaluating an expression
-- 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.Variables;
with EL.Variables.Default;
package body EL.Contexts.Default is
-- ------------------------------
-- Retrieves the ELResolver associated with this ELcontext.
-- ------------------------------
overriding
function Get_Resolver (Context : Default_Context) return ELResolver_Access is
begin
return Context.Resolver;
end Get_Resolver;
-- ------------------------------
-- Set the ELResolver associated with this ELcontext.
-- ------------------------------
procedure Set_Resolver (Context : in out Default_Context;
Resolver : in ELResolver_Access) is
begin
Context.Resolver := Resolver;
end Set_Resolver;
-- ------------------------------
-- Retrieves the VariableMapper associated with this ELContext.
-- ------------------------------
overriding
function Get_Variable_Mapper (Context : Default_Context)
return access EL.Variables.VariableMapper'Class is
begin
return Context.Var_Mapper;
end Get_Variable_Mapper;
-- ------------------------------
-- Retrieves the FunctionMapper associated with this ELContext.
-- The FunctionMapper is only used when parsing an expression.
-- ------------------------------
overriding
function Get_Function_Mapper (Context : Default_Context)
return EL.Functions.Function_Mapper_Access is
begin
return Context.Function_Mapper;
end Get_Function_Mapper;
-- ------------------------------
-- Set the function mapper to be used when parsing an expression.
-- ------------------------------
overriding
procedure Set_Function_Mapper (Context : in out Default_Context;
Mapper : access EL.Functions.Function_Mapper'Class) is
begin
Context.Function_Mapper := Mapper.all'Unchecked_Access;
end Set_Function_Mapper;
-- ------------------------------
-- Set the VariableMapper associated with this ELContext.
-- ------------------------------
overriding
procedure Set_Variable_Mapper (Context : in out Default_Context;
Mapper : access EL.Variables.VariableMapper'Class) is
use EL.Variables;
begin
if Mapper = null then
Context.Var_Mapper := null;
else
Context.Var_Mapper := Mapper.all'Unchecked_Access;
end if;
end Set_Variable_Mapper;
procedure Set_Variable (Context : in out Default_Context;
Name : in String;
Value : access EL.Beans.Readonly_Bean'Class) is
use EL.Variables;
begin
if Context.Var_Mapper = null then
Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper;
end if;
Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value));
end Set_Variable;
-- ------------------------------
-- Get the value associated with a base object and a given property.
-- ------------------------------
overriding
function Get_Value (Resolver : Default_ELResolver;
Context : ELContext'Class;
Base : access EL.Beans.Readonly_Bean'Class;
Name : Unbounded_String) return Object is
pragma Unreferenced (Context);
R : Object;
begin
if Base /= null then
return Base.Get_Value (To_String (Name));
end if;
declare
Pos : constant Bean_Maps.Cursor := Resolver.Map.Find (Name);
begin
if Bean_Maps.Has_Element (Pos) then
return Bean_Maps.Element (Pos);
end if;
end;
return R;
end Get_Value;
-- ------------------------------
-- Set the value associated with a base object and a given property.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in Default_ELResolver;
Context : in ELContext'Class;
Base : access EL.Beans.Bean'Class;
Name : in Unbounded_String;
Value : in Object) is
begin
null;
end Set_Value;
-- ------------------------------
-- Register the value under the given name.
-- ------------------------------
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : access EL.Beans.Readonly_Bean'Class) is
begin
Resolver.Register (Name, To_Object (Value));
end Register;
-- ------------------------------
-- Register the value under the given name.
-- ------------------------------
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : in EL.Objects.Object) is
begin
Bean_Maps.Include (Resolver.Map, Name, Value);
end Register;
end EL.Contexts.Default;
|
-----------------------------------------------------------------------
-- EL.Contexts -- Default contexts for evaluating an expression
-- 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.Variables;
with EL.Variables.Default;
package body EL.Contexts.Default is
-- ------------------------------
-- Retrieves the ELResolver associated with this ELcontext.
-- ------------------------------
overriding
function Get_Resolver (Context : Default_Context) return ELResolver_Access is
begin
return Context.Resolver;
end Get_Resolver;
-- ------------------------------
-- Set the ELResolver associated with this ELcontext.
-- ------------------------------
procedure Set_Resolver (Context : in out Default_Context;
Resolver : in ELResolver_Access) is
begin
Context.Resolver := Resolver;
end Set_Resolver;
-- ------------------------------
-- Retrieves the VariableMapper associated with this ELContext.
-- ------------------------------
overriding
function Get_Variable_Mapper (Context : Default_Context)
return access EL.Variables.VariableMapper'Class is
begin
return Context.Var_Mapper;
end Get_Variable_Mapper;
-- ------------------------------
-- Retrieves the FunctionMapper associated with this ELContext.
-- The FunctionMapper is only used when parsing an expression.
-- ------------------------------
overriding
function Get_Function_Mapper (Context : Default_Context)
return EL.Functions.Function_Mapper_Access is
begin
return Context.Function_Mapper;
end Get_Function_Mapper;
-- ------------------------------
-- Set the function mapper to be used when parsing an expression.
-- ------------------------------
overriding
procedure Set_Function_Mapper (Context : in out Default_Context;
Mapper : access EL.Functions.Function_Mapper'Class) is
begin
if Mapper = null then
Context.Function_Mapper := null;
else
Context.Function_Mapper := Mapper.all'Unchecked_Access;
end if;
end Set_Function_Mapper;
-- ------------------------------
-- Set the VariableMapper associated with this ELContext.
-- ------------------------------
overriding
procedure Set_Variable_Mapper (Context : in out Default_Context;
Mapper : access EL.Variables.VariableMapper'Class) is
use EL.Variables;
begin
if Mapper = null then
Context.Var_Mapper := null;
else
Context.Var_Mapper := Mapper.all'Unchecked_Access;
end if;
end Set_Variable_Mapper;
procedure Set_Variable (Context : in out Default_Context;
Name : in String;
Value : access EL.Beans.Readonly_Bean'Class) is
use EL.Variables;
begin
if Context.Var_Mapper = null then
Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper;
end if;
Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value));
end Set_Variable;
-- ------------------------------
-- Get the value associated with a base object and a given property.
-- ------------------------------
overriding
function Get_Value (Resolver : Default_ELResolver;
Context : ELContext'Class;
Base : access EL.Beans.Readonly_Bean'Class;
Name : Unbounded_String) return Object is
pragma Unreferenced (Context);
R : Object;
begin
if Base /= null then
return Base.Get_Value (To_String (Name));
end if;
declare
Pos : constant Bean_Maps.Cursor := Resolver.Map.Find (Name);
begin
if Bean_Maps.Has_Element (Pos) then
return Bean_Maps.Element (Pos);
end if;
end;
return R;
end Get_Value;
-- ------------------------------
-- Set the value associated with a base object and a given property.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in Default_ELResolver;
Context : in ELContext'Class;
Base : access EL.Beans.Bean'Class;
Name : in Unbounded_String;
Value : in Object) is
begin
null;
end Set_Value;
-- ------------------------------
-- Register the value under the given name.
-- ------------------------------
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : access EL.Beans.Readonly_Bean'Class) is
begin
Resolver.Register (Name, To_Object (Value));
end Register;
-- ------------------------------
-- Register the value under the given name.
-- ------------------------------
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : in EL.Objects.Object) is
begin
Bean_Maps.Include (Resolver.Map, Name, Value);
end Register;
end EL.Contexts.Default;
|
Fix Set_Variable_Mapper to allow to set a null function mapper.
|
Fix Set_Variable_Mapper to allow to set a null function mapper.
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
802fb582b37a70c7bae1c98dfe702a3ec3da277f
|
src/http/util-http-rest.adb
|
src/http/util-http-rest.adb
|
-----------------------------------------------------------------------
-- util-http-rest -- REST API support
-- Copyright (C) 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.JSON;
package body Util.Http.Rest is
-- -----------------------
-- Execute an HTTP GET operation using the <b>Http</b> client on the given <b>URI</b>.
-- Upon successful reception of the response, parse the JSON result and populate the
-- serialization context associated with the parser.
-- -----------------------
procedure Get (Http : in out Client;
URI : in String;
Parser : in out Util.Serialize.IO.Parser'Class) is
Response : Util.Http.Clients.Response;
begin
Http.Get (URI, Response);
Http.Status := Response.Get_Status;
declare
Content : constant String := Response.Get_Body;
begin
Parser.Parse_String (Content);
end;
end Get;
-- -----------------------
-- Execute an HTTP GET operation on the given <b>URI</b> and parse the JSON response
-- into the target object refered to by <b>Into</b> by using the mapping described
-- in <b>Mapping</b>.
-- -----------------------
procedure Rest_Get (URI : in String;
Mapping : in Util.Serialize.Mappers.Mapper_Access;
Path : in String := "";
Into : in Element_Mapper.Element_Type_Access) is
Http : Util.Http.Rest.Client;
Reader : Util.Serialize.IO.JSON.Parser;
begin
Reader.Add_Mapping (Path, Mapping.all'Access);
Element_Mapper.Set_Context (Reader, Into);
Http.Get (URI, Reader);
end Rest_Get;
end Util.Http.Rest;
|
-----------------------------------------------------------------------
-- util-http-rest -- REST API support
-- Copyright (C) 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.JSON;
with Util.Serialize.Mappers;
package body Util.Http.Rest is
-- -----------------------
-- Execute an HTTP GET operation using the <b>Http</b> client on the given <b>URI</b>.
-- Upon successful reception of the response, parse the JSON result and populate the
-- serialization context associated with the parser.
-- -----------------------
procedure Get (Http : in out Client;
URI : in String;
Parser : in out Util.Serialize.IO.Parser'Class;
Sink : in out Util.Serialize.IO.Reader'Class) is
Response : Util.Http.Clients.Response;
begin
Http.Get (URI, Response);
Http.Status := Response.Get_Status;
declare
Content : constant String := Response.Get_Body;
begin
Parser.Parse_String (Content, Sink);
end;
end Get;
-- -----------------------
-- Execute an HTTP GET operation on the given <b>URI</b> and parse the JSON response
-- into the target object refered to by <b>Into</b> by using the mapping described
-- in <b>Mapping</b>.
-- -----------------------
procedure Rest_Get (URI : in String;
Mapping : in Util.Serialize.Mappers.Mapper_Access;
Path : in String := "";
Into : in Element_Mapper.Element_Type_Access) is
Http : Util.Http.Rest.Client;
Reader : Util.Serialize.IO.JSON.Parser;
Mapper : Util.Serialize.Mappers.Processing;
begin
Mapper.Add_Mapping (Path, Mapping.all'Access);
Element_Mapper.Set_Context (Mapper, Into);
Http.Get (URI, Reader, Mapper);
end Rest_Get;
end Util.Http.Rest;
|
Add parameter to the Get procedure Update the Rest procedure to use the new parser/mapper interfaces
|
Add parameter to the Get procedure
Update the Rest procedure to use the new parser/mapper interfaces
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
624d7543f4f59da2b00a313fd9ad1af8e757146f
|
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 := "12";
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 := "13";
copyright_years : constant String := "2015-2018";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.28";
default_pgsql : constant String := "10";
default_php : constant String := "7.2";
default_python3 : constant String := "3.7";
default_ruby : constant String := "2.5";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc8";
compiler_version : constant String := "8.2.0";
previous_compiler : constant String := "7.3.0";
binutils_version : constant String := "2.31.1";
previous_binutils : constant String := "2.30";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
raven_var : constant String := "/var/ravenports";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
Bump version (not done yet though)
|
Bump version (not done yet though)
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
d3e6bf349c003456c34e85672154acee1987fbc9
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "32";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "33";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
end Definitions;
|
Set to version 1.33
|
Set to version 1.33
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
1bae0d59ec14f2e8a4bb2f9dfaf2b665ee15d15f
|
src/base/beans/util-beans.ads
|
src/base/beans/util-beans.ads
|
-----------------------------------------------------------------------
-- util-beans -- Interface Definition with Getter and Setters
-- Copyright (C) 2009, 2010, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- = 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.
--
-- To use the packages described here, use the following GNAT project:
--
-- with "utilada_base";
--
-- @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, 2019, 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.
-----------------------------------------------------------------------
-- = 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.
--
-- To use the packages described here, use the following GNAT project:
--
-- with "utilada_base";
--
-- @include util-beans-objects.ads
-- @include util-beans-objects-maps.ads
-- @include util-beans-objects-vectors.ads
-- @include util-beans-objects-datasets.ads
-- @include util-beans-basic.ads
package Util.Beans is
pragma Preelaborate;
end Util.Beans;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
0bf6458d9ed1714de6e29f274bde633b24bd83ce
|
src/wiki-render.ads
|
src/wiki-render.ads
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package Wiki.Render is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Link_Renderer is limited interface;
type Link_Renderer_Access is access all Link_Renderer'Class;
-- Get the image link that must be rendered from the wiki image link.
procedure Make_Image_Link (Renderer : in Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is abstract;
-- Get the page link that must be rendered from the wiki page link.
procedure Make_Page_Link (Renderer : in Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is abstract;
type Default_Link_Renderer is new Link_Renderer with null record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
end Wiki.Render;
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Nodes;
package Wiki.Render is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Link_Renderer is limited interface;
type Link_Renderer_Access is access all Link_Renderer'Class;
-- Get the image link that must be rendered from the wiki image link.
procedure Make_Image_Link (Renderer : in Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is abstract;
-- Get the page link that must be rendered from the wiki page link.
procedure Make_Page_Link (Renderer : in Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is abstract;
type Default_Link_Renderer is new Link_Renderer with null record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- ------------------------------
-- Document renderer
-- ------------------------------
type Renderer is limited interface;
type Renderer_Access is access all Renderer'Class;
-- Render the node instance from the document.
procedure Render (Engine : in out Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is abstract;
-- Finish the rendering after complete wiki document nodes are rendered.
procedure Finish (Document : in out Renderer) is abstract;
end Wiki.Render;
|
Declare the Renderer interface with the Render and Finish operations
|
Declare the Renderer interface with the Render and Finish operations
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
49db376e09833c9df0e6f8d4c4adbdeea0f5a504
|
src/gen-commands-database.adb
|
src/gen-commands-database.adb
|
-----------------------------------------------------------------------
-- gen-commands-database -- Database creation from application model
-- Copyright (C) 2011, 2012, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Exceptions;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Util.Processes;
with Util.Streams.Texts;
with Util.Streams.Pipes;
with ADO.Drivers.Connections;
with ADO.Sessions.Factory;
with ADO.Sessions.Sources;
with ADO.Statements;
with ADO.Queries;
with ADO.Parameters;
with Gen.Database.Model;
package body Gen.Commands.Database is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Database");
-- Check if the database with the given name exists.
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Check if the database with the given name has some tables.
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
procedure Execute_Command (Command : in String;
Input : in String);
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Sessions.Sources.Data_Source;
Generator : in out Gen.Generator.Handler);
-- Create the database identified by the given name.
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String);
-- Create the user and grant him access to the database.
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String);
-- ------------------------------
-- Check if the database with the given name exists.
-- ------------------------------
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Database_List);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
D : constant String := Stmt.Get_String (0);
begin
if Name = D then
return True;
end if;
end;
Stmt.Next;
end loop;
return False;
end Has_Database;
-- ------------------------------
-- Check if the database with the given name has some tables.
-- ------------------------------
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Table_List);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
return Stmt.Has_Elements;
end Has_Tables;
-- ------------------------------
-- Create the database identified by the given name.
-- ------------------------------
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String) is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Creating database '{0}'", Name);
Query.Set_Query (Gen.Database.Model.Query_Create_Database);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
end Create_Database;
-- ------------------------------
-- Create the user and grant him access to the database.
-- ------------------------------
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String) is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name);
if Password'Length > 0 then
Query.Set_Query (Gen.Database.Model.Query_Create_User_With_Password);
else
Query.Set_Query (Gen.Database.Model.Query_Create_User_No_Password);
end if;
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Bind_Param ("user", ADO.Parameters.Token (User));
if Password'Length > 0 then
Stmt.Bind_Param ("password", Password);
end if;
Stmt.Execute;
Query.Set_Query (Gen.Database.Model.Query_Flush_Privileges);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
end Create_User_Grant;
-- ------------------------------
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
-- ------------------------------
procedure Execute_Command (Command : in String;
Input : in String) is
Proc : aliased Util.Streams.Pipes.Pipe_Stream;
Text : Util.Streams.Texts.Reader_Stream;
begin
if Input /= "" then
Proc.Set_Input_Stream (Input);
end if;
Text.Initialize (Proc'Unchecked_Access);
Proc.Open (Command, Util.Processes.READ);
while not Text.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Text.Read_Line (Line, Strip => False);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Log.Error ("{0}", Ada.Strings.Unbounded.To_String (Line));
end;
end loop;
Proc.Close;
if Proc.Get_Exit_Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Proc.Get_Exit_Status = 255 then
Log.Error ("Command not found: {0}", Command);
else
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Proc.Get_Exit_Status));
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read {0}", Input);
end Execute_Command;
-- ------------------------------
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
-- ------------------------------
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Sessions.Sources.Data_Source;
Generator : in out Gen.Generator.Handler) is
Database : constant String := Config.Get_Database;
Username : constant String := Config.Get_Property ("user");
Password : constant String := Config.Get_Property ("password");
Dir : constant String := Util.Files.Compose (Model, "mysql");
File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-mysql.sql");
begin
Log.Info ("Creating database tables using schema '{0}'", File);
if not Ada.Directories.Exists (File) then
Generator.Error ("SQL file '{0}' does not exist.", File);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
if Password'Length > 0 then
Execute_Command ("mysql --user=" & Username & " --password=" & Password & " "
& Database, File);
else
Execute_Command ("mysql --user=" & Username & " "
& Database, File);
end if;
end Create_Mysql_Tables;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name);
use Ada.Strings.Unbounded;
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String);
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Sessions.Sources.Data_Source;
Database : in String;
Username : in String;
Password : in String);
procedure Create_SQLite_Database (Model : in String;
Config : in ADO.Sessions.Sources.Data_Source;
Database : in String);
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Sessions.Sources.Data_Source;
Database : in String;
Username : in String;
Password : in String) is
Root_Config : ADO.Sessions.Sources.Data_Source := Config;
Factory : ADO.Sessions.Factory.Session_Factory;
Root_Connection : Unbounded_String;
Root_Hidden : Unbounded_String;
Pos : Natural;
begin
-- Build a connection string to create the database.
Pos := Util.Strings.Index (Database, ':');
Append (Root_Connection, Database (Database'First .. Pos));
Append (Root_Connection, "//");
Append (Root_Connection, Config.Get_Server);
if Config.Get_Port > 0 then
Append (Root_Connection, ':');
Append (Root_Connection, Util.Strings.Image (Config.Get_Port));
end if;
Append (Root_Connection, "/?user=");
Append (Root_Connection, Username);
Root_Hidden := Root_Connection;
if Password'Length > 0 then
Append (Root_Connection, "&password=");
Root_Hidden := Root_Connection;
Append (Root_Connection, Password);
Append (Root_Hidden, "XXXXXXXX");
else
Root_Config.Set_Property ("password", "");
end if;
Log.Info ("Connecting to {0} for database setup", Root_Hidden);
-- Initialize the session factory to connect to the
-- database defined by root connection (which should allow the database creation).
Root_Config.Set_Connection (To_String (Root_Connection));
Factory.Create (Root_Config);
declare
Name : constant String := Generator.Get_Project_Name;
DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session;
begin
-- Create the database only if it does not already exists.
if not Has_Database (DB, Config.Get_Database) then
Create_Database (DB, Config.Get_Database);
end if;
-- If some tables exist, don't try to create tables again.
-- We could improve by reading the current database schema, comparing with our
-- schema and create what is missing (new tables, new columns).
if Has_Tables (DB, Config.Get_Database) then
Generator.Error ("The database {0} exists", Config.Get_Database);
else
if Username /= Config.Get_Property ("user") then
-- Create the user grant. On MySQL, it is safe to do this several times.
Create_User_Grant (DB, Config.Get_Database,
Config.Get_Property ("user"),
Config.Get_Property ("password"));
end if;
-- And now create the tables by using the SQL script generated by Dyanmo.
Create_Mysql_Tables (Name, Model, Config, Generator);
end if;
end;
end Create_MySQL_Database;
-- ------------------------------
-- Create the SQLite database.
-- ------------------------------
procedure Create_SQLite_Database (Model : in String;
Config : in ADO.Sessions.Sources.Data_Source;
Database : in String) is
Name : constant String := Generator.Get_Project_Name;
Path : constant String := Config.Get_Database;
Dir : constant String := Util.Files.Compose (Model, "sqlite");
File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-sqlite.sql");
Cfg : constant String := Generator.Get_Config_Directory;
Cmd : constant String := Util.Files.Compose (Cfg, "sqlite-exit.sql");
begin
if Ada.Directories.Exists (Path) then
Log.Info ("Connecting to {0} for database setup", Database);
end if;
-- Initialize the session factory to connect to the
-- database defined by root connection (which should allow the database creation).
Log.Info ("Creating database tables using schema '{0}'", File);
if not Ada.Directories.Exists (File) then
Generator.Error ("SQL file '{0}' does not exist.", File);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
Execute_Command ("sqlite3 --batch --init " & File & " " & Path, Cmd);
end Create_SQLite_Database;
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String) is
Config : ADO.Sessions.Sources.Data_Source;
begin
Config.Set_Connection (Database);
Config.Set_Property ("ado.queries.paths", Generator.Get_Parameter ("ado.queries.paths"));
if Config.Get_Database = "" then
Generator.Error ("Invalid database connection: no database name specified");
return;
end if;
if Config.Get_Driver = "mysql" then
if Config.Get_Property ("user") = "" then
Generator.Error ("Invalid database connection: missing user property");
return;
end if;
Create_MySQL_Database (Model, Config, Database, Username, Password);
elsif Config.Get_Driver = "sqlite" then
Create_SQLite_Database (Model, Config, Database);
else
Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver);
end if;
-- Remember the database connection string.
Generator.Set_Project_Property ("database", Database);
Generator.Save_Project;
exception
when E : others =>
Generator.Error (Ada.Exceptions.Exception_Message (E));
end Create_Database;
Model : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Arg1 : constant String := (if Args.Get_Count > 1 then Args.Get_Argument (2) else "");
Arg2 : constant String := (if Args.Get_Count > 2 then Args.Get_Argument (3) else "");
Arg3 : constant String := (if Args.Get_Count > 3 then Args.Get_Argument (4) else "");
begin
Generator.Read_Project ("dynamo.xml");
-- Initialize the database drivers.
ADO.Drivers.Initialize (Generator.Get_Properties);
-- Check if a database is specified in the command line and use it.
if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then
Create_Database (Model, Arg1, Arg2, Arg3);
else
declare
Database : constant String := Generator.Get_Project_Property ("database");
begin
-- Otherwise, get the database identification from dynamo.xml configuration.
if Ada.Strings.Fixed.Index (Database, "://") = 0 then
Generator.Error ("No database specified.");
return;
end if;
Create_Database (Model, Database, Arg1, Arg2);
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-database: Creates the database");
Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]");
New_Line;
Put_Line (" Create the database specified by the connection string.");
Put_Line (" The connection string has the form:");
Put_Line (" driver://host[:port]/database");
New_Line;
Put_Line (" The database must not exist. The user specified in the connection string");
Put_Line (" is granted the access to the new database.");
end Help;
end Gen.Commands.Database;
|
-----------------------------------------------------------------------
-- gen-commands-database -- Database creation from application model
-- Copyright (C) 2011, 2012, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Exceptions;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings.Vectors;
with ADO.Drivers;
with ADO.Sessions.Sources;
with ADO.Schemas.Databases;
package body Gen.Commands.Database is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Database");
function Get_Schema_Path (Model_Dir : in String;
Model : in String;
Config : in ADO.Sessions.Sources.Data_Source) return String;
function Get_Schema_Path (Model_Dir : in String;
Model : in String;
Config : in ADO.Sessions.Sources.Data_Source) return String is
Driver : constant String := Config.Get_Driver;
Dir : constant String := Util.Files.Compose (Model_Dir, Driver);
begin
return Util.Files.Compose (Dir, "create-" & Model & "-" & Driver & ".sql");
end Get_Schema_Path;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name);
procedure Create_Database (Model_Dir : in String;
Database : in String;
Username : in String;
Password : in String);
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_Database (Model_Dir : in String;
Database : in String;
Username : in String;
Password : in String) is
Admin : ADO.Sessions.Sources.Data_Source;
Config : ADO.Sessions.Sources.Data_Source;
Messages : Util.Strings.Vectors.Vector;
begin
Config.Set_Connection (Database);
Admin := Config;
if Config.Get_Database = "" then
Generator.Error ("Invalid database connection: no database name specified");
return;
end if;
declare
Name : constant String := Generator.Get_Project_Name;
Path : constant String := Get_Schema_Path (Model_Dir, Name, Config);
begin
Log.Info ("Creating database tables using schema '{0}'", Path);
if not Ada.Directories.Exists (Path) then
Generator.Error ("SQL file '{0}' does not exist.", Path);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
if Config.Get_Driver = "mysql" or Config.Get_Driver = "postgresql" then
if Config.Get_Property ("user") = "" then
Generator.Error ("Invalid database connection: missing user property");
return;
end if;
Admin.Set_Property ("user", Username);
Admin.Set_Property ("password", Password);
elsif Config.Get_Driver /= "sqlite" then
Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver);
return;
end if;
Admin.Set_Database ("");
ADO.Schemas.Databases.Create_Database (Admin, Config, Path, Messages);
-- Report the messages
for Msg of Messages loop
Log.Error ("{0}", Msg);
end loop;
end;
-- Remember the database connection string.
Generator.Set_Project_Property ("database", Database);
Generator.Save_Project;
exception
when E : others =>
Generator.Error (Ada.Exceptions.Exception_Message (E));
end Create_Database;
Model : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Arg1 : constant String := (if Args.Get_Count > 1 then Args.Get_Argument (2) else "");
Arg2 : constant String := (if Args.Get_Count > 2 then Args.Get_Argument (3) else "");
Arg3 : constant String := (if Args.Get_Count > 3 then Args.Get_Argument (4) else "");
begin
Generator.Read_Project ("dynamo.xml");
-- Initialize the database drivers.
ADO.Drivers.Initialize (Generator.Get_Properties);
-- Check if a database is specified in the command line and use it.
if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then
Create_Database (Model, Arg1, Arg2, Arg3);
else
declare
Database : constant String := Generator.Get_Project_Property ("database");
begin
-- Otherwise, get the database identification from dynamo.xml configuration.
if Ada.Strings.Fixed.Index (Database, "://") = 0 then
Generator.Error ("No database specified.");
return;
end if;
Create_Database (Model, Database, Arg1, Arg2);
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-database: Creates the database");
Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]");
New_Line;
Put_Line (" Create the database specified by the connection string.");
Put_Line (" The connection string has the form:");
Put_Line (" driver://host[:port]/database");
New_Line;
Put_Line (" The database must not exist. The user specified in the connection string");
Put_Line (" is granted the access to the new database.");
end Help;
end Gen.Commands.Database;
|
Update the create-database command to use the ADO.Schemas.Databases.Create_Database operation
|
Update the create-database command to use the ADO.Schemas.Databases.Create_Database operation
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
e1bfa8ea4b67f12968a8023ca2b56cf77bdcccf7
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a section header in the document.
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a section header in the document.
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
end Wiki.Render.Html;
|
Remove Start_Element and End_Element procedures
|
Remove Start_Element and End_Element procedures
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
80929d225c968c04182f3c03a7c3d065e416bdd3
|
regtests/util-log-tests.adb
|
regtests/util-log-tests.adb
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Files;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
pragma Unreferenced (T);
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Log;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
end Test_Log_Perf;
-- ------------------------------
-- Test appending the log on several log files
-- ------------------------------
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_File_Appender_Modes (T : in out Test) is
use Ada.Directories;
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-append.log");
Props.Set ("log4j.appender.test.append", "true");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.appender.test_global", "File");
Props.Set ("log4j.appender.test_global.File", "test-append-global.log");
Props.Set ("log4j.appender.test_global.append", "false");
Props.Set ("log4j.appender.test_global.immediateFlush", "false");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG");
Props.Set ("log4j.rootCategory", "DEBUG,test_global,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Error ("This is the error test message");
end;
Props.Set ("log4j.appender.test_append", "File");
Props.Set ("log4j.appender.test_append.File", "test-append2.log");
Props.Set ("log4j.appender.test_append.append", "true");
Props.Set ("log4j.appender.test_append.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global");
Util.Log.Loggers.Initialize (Props);
declare
L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file");
begin
L1.Info ("L1-1 Writing a info message");
L2.Info ("L2-2 {0}: {1}", "Parameter", "Value");
L1.Info ("L1-3 Done");
L2.Error ("L2-4 This is the error test2 message");
end;
Props.Set ("log4j.appender.test_append.append", "plop");
Props.Set ("log4j.appender.test_append.immediateFlush", "falsex");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
T.Assert (Ada.Directories.Size ("test-append.log") > 100,
"Log file test-append.log is empty");
T.Assert (Ada.Directories.Size ("test-append2.log") > 100,
"Log file test-append2.log is empty");
T.Assert (Ada.Directories.Size ("test-append-global.log") > 100,
"Log file test-append.log is empty");
end Test_File_Appender_Modes;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_Console_Appender (T : in out Test) is
Props : Util.Properties.Manager;
File : Ada.Text_IO.File_Type;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, "test_err.log");
Ada.Text_IO.Set_Error (File);
Props.Set ("log4j.appender.test_console", "Console");
Props.Set ("log4j.appender.test_console.stderr", "true");
Props.Set ("log4j.appender.test_console.level", "WARN");
Props.Set ("log4j.rootCategory", "INFO,test_console");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Info ("INFO MESSAGE!");
L.Warn ("WARN MESSAGE!");
L.Error ("This {0} {1} {2} test message", "is", "the", "error");
end;
Ada.Text_IO.Flush (Ada.Text_IO.Current_Error);
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
Ada.Text_IO.Close (File);
Util.Files.Read_File ("test_err.log", Content);
Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content,
"Invalid console log (WARN)");
Util.Tests.Assert_Matches (T, ".*This is the error test message", Content,
"Invalid console log (ERROR)");
exception
when others =>
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
raise;
end Test_Console_Appender;
procedure Test_Missing_Config (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
Util.Log.Loggers.Initialize ("plop");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Missing_Config;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize",
Test_Missing_Config'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)",
Test_File_Appender_Modes'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console",
Test_Console_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Files;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
pragma Unreferenced (T);
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Log;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
end Test_Log_Perf;
-- ------------------------------
-- Test appending the log on several log files
-- ------------------------------
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_File_Appender_Modes (T : in out Test) is
use Ada.Directories;
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-append.log");
Props.Set ("log4j.appender.test.append", "true");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.appender.test_global", "File");
Props.Set ("log4j.appender.test_global.File", "test-append-global.log");
Props.Set ("log4j.appender.test_global.append", "false");
Props.Set ("log4j.appender.test_global.immediateFlush", "false");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG");
Props.Set ("log4j.rootCategory", "DEBUG,test_global,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Error ("This is the error test message");
end;
Props.Set ("log4j.appender.test_append", "File");
Props.Set ("log4j.appender.test_append.File", "test-append2.log");
Props.Set ("log4j.appender.test_append.append", "true");
Props.Set ("log4j.appender.test_append.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global");
Util.Log.Loggers.Initialize (Props);
declare
L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file");
begin
L1.Info ("L1-1 Writing a info message");
L2.Info ("L2-2 {0}: {1}", "Parameter", "Value");
L1.Info ("L1-3 Done");
L2.Error ("L2-4 This is the error test2 message");
end;
Props.Set ("log4j.appender.test_append.append", "plop");
Props.Set ("log4j.appender.test_append.immediateFlush", "falsex");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
T.Assert (Ada.Directories.Size ("test-append.log") > 100,
"Log file test-append.log is empty");
T.Assert (Ada.Directories.Size ("test-append2.log") > 100,
"Log file test-append2.log is empty");
T.Assert (Ada.Directories.Size ("test-append-global.log") > 100,
"Log file test-append.log is empty");
end Test_File_Appender_Modes;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_Console_Appender (T : in out Test) is
Props : Util.Properties.Manager;
File : Ada.Text_IO.File_Type;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, "test_err.log");
Ada.Text_IO.Set_Error (File);
Props.Set ("log4j.appender.test_console", "Console");
Props.Set ("log4j.appender.test_console.stderr", "true");
Props.Set ("log4j.appender.test_console.level", "WARN");
Props.Set ("log4j.rootCategory", "INFO,test_console");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Info ("INFO MESSAGE!");
L.Warn ("WARN MESSAGE!");
L.Error ("This {0} {1} {2} test message", "is", "the", "error");
end;
Ada.Text_IO.Flush (Ada.Text_IO.Current_Error);
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
Ada.Text_IO.Close (File);
Util.Files.Read_File ("test_err.log", Content);
Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content,
"Invalid console log (WARN)");
Util.Tests.Assert_Matches (T, ".*This is the error test message", Content,
"Invalid console log (ERROR)");
exception
when others =>
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
raise;
end Test_Console_Appender;
procedure Test_Missing_Config (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
Util.Log.Loggers.Initialize ("plop");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Missing_Config;
procedure Test_Log_Traceback (T : in out Test) is
Props : Util.Properties.Manager;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-traceback.log");
Props.Set ("log4j.appender.test.append", "false");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.rootCategory", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Error ("This is the error test message");
raise Constraint_Error with "Test";
exception
when E : others =>
L.Error ("Something wrong", E, True);
end;
Props.Set ("log4j.rootCategory", "DEBUG,console");
Props.Set ("log4j.appender.console", "Console");
Util.Log.Loggers.Initialize (Props);
Util.Files.Read_File ("test-traceback.log", Content);
Util.Tests.Assert_Matches (T, ".*Something wrong: Exception CONSTRAINT_ERROR:", Content,
"Invalid console log (ERROR)");
end Test_Log_Traceback;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Error",
Test_Log_Traceback'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize",
Test_Missing_Config'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)",
Test_File_Appender_Modes'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console",
Test_Console_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
Add Test_Log_Traceback and register the new test for execution
|
Add Test_Log_Traceback and register the new test for execution
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a9a72da8b6dbba393fa355f7ba83285e826b9a16
|
src/util-concurrent-fifos.adb
|
src/util-concurrent-fifos.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
First := Elements'First;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
Fix dequeue in the Clean_On_Dequeue instantiation mode
|
Fix dequeue in the Clean_On_Dequeue instantiation mode
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
|
4387c469db60f1a0fdafce122b025bd9eb77fd58
|
matp/src/memory/mat-memory-targets.adb
|
matp/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_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;
-- ------------------------------
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map) is
begin
Memory.Memory.Find (From, To, Into);
end Find;
-- ------------------------------
-- 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.Ceiling (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;
|
-----------------------------------------------------------------------
-- 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_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;
-- ------------------------------
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map) is
begin
Memory.Memory.Find (From, To, Into);
end Find;
-- ------------------------------
-- 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.Ceiling (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;
Iter := Freed_Slots.Find (Addr);
if not Allocation_Maps.Has_Element (Iter) then
Freed_Slots.Insert (Addr, Item);
end if;
end if;
exception
when others =>
Log.Error ("Free {0} raised some exception", MAT.Types.Hex_Image (Addr));
raise;
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;
|
Fix Probe_Free that could raise a key already in map exception
|
Fix Probe_Free that could raise a key already in map exception
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
9c5f83e7956395a526bb0779832bcf164257237f
|
regtests/ado-tests.adb
|
regtests/ado-tests.adb
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- 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.Exceptions;
with AUnit;
with AUnit.Test_Caller;
with ADO.Statements;
with ADO.Objects;
with ADO.Sessions;
with Regtests;
with Regtests.Simple.Model;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
package body ADO.Tests is
use Util.Log;
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests");
package Caller is new AUnit.Test_Caller (Test);
procedure Fail (T : in Test; Message : in String);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Fail (T : in Test; Message : in String) is
begin
T.Assert (False, Message);
end Fail;
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
Assert (T, Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
Assert (T, False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
Assert (T, 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);
Assert (T, Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
Assert (T, 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;
Fail (T, "Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
Fail (T, "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'Access);
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
Assert (T, 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;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
Assert (T, 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);
Assert (T, 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'Access);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
Assert (T, Result > 100, "Too few rows were deleted");
end Test_Delete_All;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Suite.Add_Test (Caller.Create ("Test Object_Ref.Load", Test_Load'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Save", Test_Create_Load'Access));
Suite.Add_Test (Caller.Create ("Test Master_Connection init error", Test_Not_Open'Access));
Suite.Add_Test (Caller.Create ("Test Sequences.Factory", Test_Allocate'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access));
Suite.Add_Test (Caller.Create ("Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access));
end Add_Tests;
end ADO.Tests;
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- 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.Exceptions;
with AUnit;
with AUnit.Test_Caller;
with ADO.Statements;
with ADO.Objects;
with ADO.Sessions;
with Regtests;
with Regtests.Simple.Model;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
package body ADO.Tests is
use Util.Log;
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests");
package Caller is new AUnit.Test_Caller (Test);
procedure Fail (T : in Test; Message : in String);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Fail (T : in Test; Message : in String) is
begin
T.Assert (False, Message);
end Fail;
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;
Fail (T, "Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
Fail (T, "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'Access);
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
Assert (T, 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;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : 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");
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'Access);
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;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Suite.Add_Test (Caller.Create ("Test Object_Ref.Load", Test_Load'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Save", Test_Create_Load'Access));
Suite.Add_Test (Caller.Create ("Test Master_Connection init error", Test_Not_Open'Access));
Suite.Add_Test (Caller.Create ("Test Sequences.Factory", Test_Allocate'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access));
Suite.Add_Test (Caller.Create ("Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access));
end Add_Tests;
end ADO.Tests;
|
Fix compilation with GNAT 2011
|
Fix compilation with GNAT 2011
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
2a501e95f9547bc74651585332cf743eb0be8c0a
|
src/ado-drivers.adb
|
src/ado-drivers.adb
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Ada.IO_Exceptions;
with ADO.Queries.Loaders;
package body ADO.Drivers is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers");
-- Global configuration properties (loaded by Initialize).
Global_Config : Util.Properties.Manager;
-- ------------------------------
-- Initialize the drivers and the library by reading the property file
-- and configure the runtime with it.
-- ------------------------------
procedure Initialize (Config : in String) is
begin
Log.Info ("Initialize using property file {0}", Config);
begin
Util.Properties.Load_Properties (Global_Config, Config);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Configuration file '{0}' does not exist", Config);
end;
Initialize (Global_Config);
end Initialize;
-- ------------------------------
-- Initialize the drivers and the library and configure the runtime with the given properties.
-- ------------------------------
procedure Initialize (Config : in Util.Properties.Manager'Class) is
begin
Global_Config := Util.Properties.Manager (Config);
-- Configure the XML query loader.
ADO.Queries.Loaders.Initialize (Global_Config.Get ("ado.queries.paths", ".;db"),
Global_Config.Get ("ado.queries.load", "false") = "true");
ADO.Drivers.Initialize;
end Initialize;
-- ------------------------------
-- Get the global configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
-- ------------------------------
function Get_Config (Name : in String;
Default : in String := "") return String is
begin
return Global_Config.Get (Name, Default);
end Get_Config;
-- Initialize the drivers which are available.
procedure Initialize is separate;
end ADO.Drivers;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Ada.IO_Exceptions;
with ADO.Queries.Loaders;
package body ADO.Drivers is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers");
-- Global configuration properties (loaded by Initialize).
Global_Config : Util.Properties.Manager;
-- ------------------------------
-- Initialize the drivers and the library by reading the property file
-- and configure the runtime with it.
-- ------------------------------
procedure Initialize (Config : in String) is
begin
Log.Info ("Initialize using property file {0}", Config);
begin
Util.Properties.Load_Properties (Global_Config, Config);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Configuration file '{0}' does not exist", Config);
end;
Initialize (Global_Config);
end Initialize;
-- ------------------------------
-- Initialize the drivers and the library and configure the runtime with the given properties.
-- ------------------------------
procedure Initialize (Config : in Util.Properties.Manager'Class) is
begin
Global_Config := Util.Properties.Manager (Config);
-- Configure the XML query loader.
ADO.Queries.Loaders.Initialize (Global_Config.Get ("ado.queries.paths", ".;db"),
Global_Config.Get ("ado.queries.load", "false") = "true");
-- Initialize the drivers.
ADO.Drivers.Initialize;
end Initialize;
-- ------------------------------
-- Get the global configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
-- ------------------------------
function Get_Config (Name : in String;
Default : in String := "") return String is
begin
return Global_Config.Get (Name, Default);
end Get_Config;
-- Initialize the drivers which are available.
procedure Initialize is separate;
end ADO.Drivers;
|
Add some comments
|
Add some comments
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
6f947e505e83045f3bc82721d0853bb87bb22678
|
tools/druss-commands-wifi.adb
|
tools/druss-commands-wifi.adb
|
-----------------------------------------------------------------------
-- druss-commands-wifi -- Wifi related commands
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with 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 out 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) = "show" 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;
|
-----------------------------------------------------------------------
-- druss-commands-wifi -- Wifi related commands
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with 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 out 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) = "show" then
Command.Do_Status (Args, Context);
else
Context.Console.Notice (N_USAGE, "Invalid sub-command: " & Args.Get_Argument (1));
Druss.Commands.Driver.Usage (Args, Context);
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP, "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;
|
Change Help command to accept in out command
|
Change Help command to accept in out command
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
4245ce9028d75fd073437783847ce0df99cf33a9
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "52";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "53";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
end Definitions;
|
Bump version
|
Bump version
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
d7387aae1d93417af8b8db7c45a1d963dacba7a9
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "66";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "67";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
bump synth version
|
bump synth version
Unfortunately, I already published v1.67 so another release is needed.
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
e759f393ab7a918debb39aa5d9fb53a84977b69d
|
src/ado-queries-loaders.adb
|
src/ado-queries-loaders.adb
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- 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 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;
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;
Query_List : Query_Definition_Access := null;
-- 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 (Query : in Query_Definition_Access) 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
Query.File := File;
Query.Next := File.Queries;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
File.Next := Query_Files;
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 ADO.Drivers.Driver_Access := ADO.Drivers.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 (Query : in Query_Definition_Access) return Unsigned_32 is
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (Query : in Query_Definition_Access) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if Query.File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (Query);
begin
if Query.File.Last_Modified = M then
return False;
end if;
Query.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 (Into : in Query_File_Access) 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);
-- 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_Access;
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
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 (Into.File.all, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
if Into.Query_Def /= null then
Into.Query := new Query_Info;
Into.Query_Def.Query := Into.Query;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if Into.Query /= null and Into.Driver >= 0 then
Set_Query_Pattern (Into.Query.Main_Query (ADO.Drivers.Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if Into.Query /= null and Into.Driver >= 0 then
Set_Query_Pattern (Into.Query.Count_Query (ADO.Drivers.Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
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;
begin
Log.Info ("Reading XML query {0}", Into.Path.all);
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);
Reader.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Reader, Loader'Access);
-- Read the XML query file.
Reader.Parse (Into.Path.all);
Into.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", Into.Path.all);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Into : in Query_Definition_Access) is
begin
if Into.Query = null or else Is_Modified (Into) then
Read_Query (Into.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 (Paths : in String;
Load : in Boolean) is
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Path.all,
Paths => Paths);
begin
File.Path := new String '(Path);
if Load then
Read_Query (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 Query is
begin
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- 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 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;
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;
Query_List : Query_Definition_Access := null;
-- 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 (Query : in Query_Definition_Access) 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
Query.File := File;
Query.Next := File.Queries;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
File.Next := Query_Files;
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 ADO.Drivers.Driver_Access := ADO.Drivers.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 (Query : in Query_Definition_Access) return Unsigned_32 is
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (Query : in Query_Definition_Access) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if Query.File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (Query);
begin
if Query.File.Last_Modified = M then
return False;
end if;
Query.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 (Into : in Query_File_Access) 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);
-- 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_Access;
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
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 (Into.File.all, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
Into.Query := null;
if Into.Query_Def /= null then
Into.Query := new Query_Info;
Into.Query_Def.Query := Into.Query;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if Into.Query /= null and Into.Driver >= 0 then
Set_Query_Pattern (Into.Query.Main_Query (ADO.Drivers.Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if Into.Query /= null and Into.Driver >= 0 then
Set_Query_Pattern (Into.Query.Count_Query (ADO.Drivers.Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
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;
begin
Log.Info ("Reading XML query {0}", Into.Path.all);
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);
Reader.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Reader, Loader'Access);
-- Read the XML query file.
Reader.Parse (Into.Path.all);
Into.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", Into.Path.all);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Into : in Query_Definition_Access) is
begin
if Into.Query = null or else Is_Modified (Into) then
Read_Query (Into.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 (Paths : in String;
Load : in Boolean) is
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Path.all,
Paths => Paths);
begin
File.Path := new String '(Path);
if Load then
Read_Query (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 Query is
begin
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
Clear the reference to the query info when a new query is found
|
Clear the reference to the query info when a new query is found
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
b30e5f7088ca524d53ce6fe15db0f904d47cc00e
|
awa/plugins/awa-blogs/src/awa-blogs-servlets.adb
|
awa/plugins/awa-blogs/src/awa-blogs-servlets.adb
|
-----------------------------------------------------------------------
-- awa-blogs-servlets -- Serve files saved in the storage service
-- 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 AWA.Images.Modules;
with AWA.Blogs.Modules;
package body AWA.Blogs.Servlets is
-- ------------------------------
-- Load the data content that correspond to the GET request and get the name as well
-- as mime-type and date.
-- ------------------------------
overriding
procedure Load (Server : in Image_Servlet;
Request : in out ASF.Requests.Request'Class;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Data : out ADO.Blob_Ref) is
pragma Unreferenced (Server, Name);
Post : constant String := Request.Get_Path_Parameter (1);
File : constant String := Request.Get_Path_Parameter (2);
Size : constant String := Request.Get_Path_Parameter (3);
Module : constant AWA.Blogs.Modules.Blog_Module_Access := Blogs.Modules.Get_Blog_Module;
Post_Id : ADO.Identifier;
File_Id : ADO.Identifier;
Width : Natural;
Height : Natural;
Img_Width : Natural;
Img_Height : Natural;
begin
Post_Id := ADO.Identifier'Value (Post);
File_Id := ADO.Identifier'Value (File);
AWA.Images.Modules.Get_Sizes (Dimension => Size,
Width => Width,
Height => Height);
Img_Width := Width;
Img_Height := Height;
Module.Load_Image (Post_Id => Post_Id,
Image_Id => File_Id,
Width => Img_Width,
Height => Img_Height,
Mime => Mime,
Date => Date,
Into => Data);
end Load;
end AWA.Blogs.Servlets;
|
-----------------------------------------------------------------------
-- awa-blogs-servlets -- Serve files saved in the storage service
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Images.Modules;
with AWA.Blogs.Modules;
package body AWA.Blogs.Servlets is
-- ------------------------------
-- Load the data content that correspond to the GET request and get the name as well
-- as mime-type and date.
-- ------------------------------
overriding
procedure Load (Server : in Image_Servlet;
Request : in out ASF.Requests.Request'Class;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Data : out ADO.Blob_Ref) is
pragma Unreferenced (Server, Name);
Post : constant String := Request.Get_Path_Parameter (1);
File : constant String := Request.Get_Path_Parameter (2);
Size : constant String := Request.Get_Path_Parameter (3);
Module : constant AWA.Blogs.Modules.Blog_Module_Access := Blogs.Modules.Get_Blog_Module;
Post_Id : ADO.Identifier;
File_Id : ADO.Identifier;
Width : Natural;
Height : Natural;
Img_Width : Natural;
Img_Height : Natural;
begin
Post_Id := ADO.Identifier'Value (Post);
File_Id := ADO.Identifier'Value (File);
AWA.Images.Modules.Get_Sizes (Dimension => Size,
Width => Width,
Height => Height);
Img_Width := Width;
Img_Height := Height;
Module.Load_Image (Post_Id => Post_Id,
Image_Id => File_Id,
Width => Img_Width,
Height => Img_Height,
Mime => Mime,
Date => Date,
Into => Data);
end Load;
-- ------------------------------
-- Get the expected return mode (content disposition for download or inline).
-- ------------------------------
overriding
function Get_Format (Server : in Image_Servlet;
Request : in ASF.Requests.Request'Class)
return AWA.Storages.Servlets.Get_Type is
pragma Unreferenced (Server, Request);
begin
return AWA.Storages.Servlets.DEFAULT;
end Get_Format;
end AWA.Blogs.Servlets;
|
Implement the Get_Format function
|
Implement the Get_Format function
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1f57e2946de052fe1e3ff9bc8342f5def00bc1f1
|
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.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;
overriding
procedure Do_Delete (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 ("Delete {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Delete (URL => URI, Data => "", Headers => Req.Headers,
Timeouts => Req.Timeouts);
end Do_Delete;
-- ------------------------------
-- 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;
|
-----------------------------------------------------------------------
-- 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;
overriding
procedure Do_Delete (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 ("Delete {0}", URI);
Reply.Delegate := Rep.all'Access;
-- Rep.Data := AWS.Client.Delete (URL => URI, Data => "", Headers => Req.Headers,
-- Timeouts => Req.Timeouts);
raise Program_Error with "Delete is not supported by AWS and there is no easy conditional"
& " compilation in Ada to enable Delete support for the latest AWS version. "
& "For now, you have to use curl, or install the latest AWS version and then "
& "uncomment the AWS.Client.Delete call and remove this exception.";
end Do_Delete;
-- ------------------------------
-- 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;
|
Revert the use of AWS.Client.Delete which is not available on AWS 2016 and forces to use AWS 2017 but AWS 2017 cannot be compiled out of the box with gcc 4.9 which is the default on Ubuntu 16.04. Avoid using AWS and use curl if one need to use the Delete operation, or, manually change the Do_Delete procedure.
|
Revert the use of AWS.Client.Delete which is not available on AWS 2016 and forces to use
AWS 2017 but AWS 2017 cannot be compiled out of the box with gcc 4.9 which is the default
on Ubuntu 16.04. Avoid using AWS and use curl if one need to use the Delete operation,
or, manually change the Do_Delete procedure.
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f3e773f2c53d866513d875eaef04a8969f684895
|
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.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
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 (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Comment => Bean);
end Create;
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
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);
elsif Name = "entity_id" then
From.Load_Comments (ADO.Utils.To_Identifier (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;
For_Entity_Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Into.Module.Get_Session;
begin
Into.Load_Comments (Session, For_Entity_Id);
end Load_Comments;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in out ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Into.Entity_Id := For_Entity_Id;
Query.Set_Query (AWA.Comments.Models.Query_Comment_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED)));
AWA.Comments.Models.List (Into, Session, Query);
end Load_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions.Entities;
with ADO.Queries;
with ADO.Utils;
with 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
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
pragma Unreferenced (Outcome);
begin
Bean.Module.Create_Comment (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Comment => Bean);
end Create;
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Save;
-- ------------------------------
-- Delete the comment.
-- ------------------------------
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean);
end Delete;
-- ------------------------------
-- Create a new comment bean instance.
-- ------------------------------
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_Bean_Access := new Comment_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "entity_id" then
From.Load_Comments (ADO.Utils.To_Identifier (Value));
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) with which the comments are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a comment on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
For_Entity_Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Into.Module.Get_Session;
begin
Into.Load_Comments (Session, For_Entity_Id);
end Load_Comments;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in out ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Into.Entity_Id := For_Entity_Id;
Query.Set_Query (AWA.Comments.Models.Query_Comment_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED)));
AWA.Comments.Models.List (Into, Session, Query);
end Load_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
Implement the Delete operation
|
Implement the Delete operation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
28d97946d694703239e45885121a1aa7c047cd3e
|
regtests/util-streams-sockets-tests.adb
|
regtests/util-streams-sockets-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-sockets-tests -- Unit tests for socket streams
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Util.Test_Caller;
with Util.Streams.Texts;
with Util.Tests.Servers;
package body Util.Streams.Sockets.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Sockets");
type Test_Server is new Util.Tests.Servers.Server with record
Count : Natural := 0;
end record;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect",
Test_Socket_Init'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write",
Test_Socket_Read'Access);
end Add_Tests;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class) is
pragma Unreferenced (Stream);
begin
if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then
Into.Count := Into.Count + 1;
end if;
end Process_Line;
-- ------------------------------
-- Test reading and writing on a socket stream.
-- ------------------------------
procedure Test_Socket_Read (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
Server : Test_Server;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Server.Start;
T.Assert (Server.Get_Port > 0, "The server was not started");
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
GNAT.Sockets.Port_Type (Server.Get_Port));
-- Let the server start.
delay 0.1;
-- Get a connection and write 10 lines.
Stream.Connect (Server => Addr);
Writer.Initialize (Output => Stream'Unchecked_Access,
Input => null,
Size => 1024);
for I in 1 .. 10 loop
Writer.Write ("Sending a line on the socket test-"
& Natural'Image (I) & ASCII.CR & ASCII.LF);
Writer.Flush;
end loop;
Writer.Close;
-- Stop the server and verify that 10 lines were received.
Server.Stop;
Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received");
end Test_Socket_Read;
-- ------------------------------
-- Test socket initialization.
-- ------------------------------
procedure Test_Socket_Init (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Fd : GNAT.Sockets.Socket_Type;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
80);
GNAT.Sockets.Create_Socket (Fd);
Stream.Open (Fd);
begin
Stream.Connect (Addr);
T.Assert (False, "No exception was raised");
exception
when Ada.IO_Exceptions.Use_Error =>
null;
end;
end Test_Socket_Init;
end Util.Streams.Sockets.Tests;
|
-----------------------------------------------------------------------
-- util-streams-sockets-tests -- Unit tests for socket streams
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Util.Test_Caller;
with Util.Streams.Texts;
with Util.Tests.Servers;
package body Util.Streams.Sockets.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Sockets");
type Test_Server is new Util.Tests.Servers.Server with record
Count : Natural := 0;
end record;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect",
Test_Socket_Init'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write",
Test_Socket_Read'Access);
end Add_Tests;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
pragma Unreferenced (Stream, Client);
begin
if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then
Into.Count := Into.Count + 1;
end if;
end Process_Line;
-- ------------------------------
-- Test reading and writing on a socket stream.
-- ------------------------------
procedure Test_Socket_Read (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
Server : Test_Server;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Server.Start;
T.Assert (Server.Get_Port > 0, "The server was not started");
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
GNAT.Sockets.Port_Type (Server.Get_Port));
-- Let the server start.
delay 0.1;
-- Get a connection and write 10 lines.
Stream.Connect (Server => Addr);
Writer.Initialize (Output => Stream'Unchecked_Access,
Input => null,
Size => 1024);
for I in 1 .. 10 loop
Writer.Write ("Sending a line on the socket test-"
& Natural'Image (I) & ASCII.CR & ASCII.LF);
Writer.Flush;
end loop;
Writer.Close;
-- Stop the server and verify that 10 lines were received.
Server.Stop;
Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received");
end Test_Socket_Read;
-- ------------------------------
-- Test socket initialization.
-- ------------------------------
procedure Test_Socket_Init (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Fd : GNAT.Sockets.Socket_Type;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
80);
GNAT.Sockets.Create_Socket (Fd);
Stream.Open (Fd);
begin
Stream.Connect (Addr);
T.Assert (False, "No exception was raised");
exception
when Ada.IO_Exceptions.Use_Error =>
null;
end;
end Test_Socket_Init;
end Util.Streams.Sockets.Tests;
|
Update unit test after changes in Process_Line
|
Update unit test after changes in Process_Line
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
dd071ef9109ed40b077b40308d7d3a7b6892dec2
|
src/ado.ads
|
src/ado.ads
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- 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 Interfaces.C;
package ADO is
subtype Int8 is Interfaces.C.signed_char;
subtype Int16 is Interfaces.C.short;
subtype Int32 is Interfaces.C.int;
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
end ADO;
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- 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 Interfaces.C;
package ADO is
type Identifier is new Integer;
NO_IDENTIFIER : constant Identifier := -1;
-- subtype Int8 is Interfaces.C.signed_char;
-- subtype Int16 is Interfaces.C.short;
-- subtype Int32 is Interfaces.C.int;
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
end ADO;
|
Define the Identifier type
|
Define the Identifier type
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
4f4038a9f5a5778e40a88c15a93dbc183789b8f1
|
matp/src/events/mat-events-targets.adb
|
matp/src/events/mat-events-targets.adb
|
-----------------------------------------------------------------------
-- 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.Unchecked_Deallocation;
package body MAT.Events.Targets is
ITERATE_COUNT : constant Event_Id_Type := 10_000;
-- ------------------------------
-- 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 is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
-- ------------------------------
-- 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) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
begin
return Left.Count < Right.Count;
end "<";
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in out Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the 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) is
begin
Target.Events.Get_Limits (First, Last);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
-- ------------------------------
-- 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)) is
begin
Target.Events.Iterate (Start, Finish, Process);
end Iterate;
-- ------------------------------
-- 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)) is
First_Event : Target_Event;
Last_Event : Target_Event;
First_Id : Event_Id_Type;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
-- Iterate over the events in groups of 10_000 to release the lock and give some
-- opportunity to the server thread to add new events.
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Process);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Iterate;
-- ------------------------------
-- Release the storage allocated for the events.
-- ------------------------------
overriding
procedure Finalize (Target : in out Target_Events) is
begin
Target.Events.Clear;
end Finalize;
protected body Event_Collector is
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Probe_Event_Type));
-- ------------------------------
-- Internal operation to update the event represented by <tt>Id</tt>.
-- ------------------------------
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Probe_Event_Type)) is
Iter : constant Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
if Event_Id_Maps.Has_Element (Iter) then
Block := Event_Id_Maps.Element (Iter);
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
Process (Block.Events (Pos));
end if;
end if;
end Update;
-- ------------------------------
-- 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) is
procedure Update_Size (Event : in out Probe_Event_Type);
procedure Update_Next (Event : in out Probe_Event_Type);
procedure Update_Size (Event : in out Probe_Event_Type) is
begin
Event.Size := Size;
Event.Prev_Id := Prev_Id;
end Update_Size;
procedure Update_Next (Event : in out Probe_Event_Type) is
begin
Event.Next_Id := Id;
end Update_Next;
begin
Update (Id, Update_Size'Access);
Update (Prev_Id, Update_Next'Access);
end Update_Event;
-- ------------------------------
-- Add the event in the list of events.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Event : in out Probe_Event_Type) is
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
First_Block : constant Event_Block_Access := Events.First_Element;
Last_Block : constant Event_Block_Access := Events.Last_Element;
begin
First := First_Block.Events (First_Block.Events'First);
Last := Last_Block.Events (Last_Block.Count);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
-- ------------------------------
-- 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)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Start <= Finish then
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos > Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
else
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id <= Finish;
Id := Id - 1;
if Pos = Block.Events'First then
Event_Id_Maps.Previous (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Count;
else
Pos := Pos - 1;
end if;
end loop;
end if;
Event_Id_Maps.Previous (Iter);
end if;
end loop;
end Iterate;
-- ------------------------------
-- Clear the events.
-- ------------------------------
procedure Clear is
procedure Free is
new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access);
begin
while not Events.Is_Empty loop
declare
Block : Event_Block_Access := Events.First_Element;
begin
Free (Block);
Events.Delete_First;
end;
end loop;
Current := null;
Last_Id := 0;
Ids.Clear;
end Clear;
end Event_Collector;
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.Unchecked_Deallocation;
package body MAT.Events.Targets is
ITERATE_COUNT : constant Event_Id_Type := 10_000;
-- ------------------------------
-- 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 is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
-- ------------------------------
-- 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) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
begin
return Left.Count < Right.Count;
end "<";
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in out Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
-- ------------------------------
-- 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 (Target : in out Target_Events;
Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type) is
begin
Target.Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the 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) is
begin
Target.Events.Get_Limits (First, Last);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
-- ------------------------------
-- 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)) is
begin
Target.Events.Iterate (Start, Finish, Process);
end Iterate;
-- ------------------------------
-- 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)) is
First_Event : Target_Event;
Last_Event : Target_Event;
First_Id : Event_Id_Type;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
-- Iterate over the events in groups of 10_000 to release the lock and give some
-- opportunity to the server thread to add new events.
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Process);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Iterate;
-- ------------------------------
-- Release the storage allocated for the events.
-- ------------------------------
overriding
procedure Finalize (Target : in out Target_Events) is
begin
Target.Events.Clear;
end Finalize;
protected body Event_Collector is
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Probe_Event_Type));
-- ------------------------------
-- Internal operation to update the event represented by <tt>Id</tt>.
-- ------------------------------
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Probe_Event_Type)) is
Iter : constant Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
if Event_Id_Maps.Has_Element (Iter) then
Block := Event_Id_Maps.Element (Iter);
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
Process (Block.Events (Pos));
end if;
end if;
end Update;
-- ------------------------------
-- 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) is
procedure Update_Size (Event : in out Probe_Event_Type);
procedure Update_Next (Event : in out Probe_Event_Type);
procedure Update_Size (Event : in out Probe_Event_Type) is
begin
Event.Size := Size;
Event.Prev_Id := Prev_Id;
end Update_Size;
procedure Update_Next (Event : in out Probe_Event_Type) is
begin
Event.Next_Id := Id;
end Update_Next;
begin
Update (Id, Update_Size'Access);
Update (Prev_Id, Update_Next'Access);
end Update_Event;
-- ------------------------------
-- Add the event in the list of events.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Event : in out Probe_Event_Type) is
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type) is
First_Block : constant Event_Block_Access := Events.First_Element;
Last_Block : constant Event_Block_Access := Events.Last_Element;
begin
First := First_Block.Events (First_Block.Events'First);
Last := Last_Block.Events (Last_Block.Count);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
-- ------------------------------
-- 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)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Start <= Finish then
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos > Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
else
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id <= Finish;
Id := Id - 1;
if Pos = Block.Events'First then
Event_Id_Maps.Previous (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Count;
else
Pos := Pos - 1;
end if;
end loop;
end if;
Event_Id_Maps.Previous (Iter);
end if;
end loop;
end Iterate;
-- ------------------------------
-- Clear the events.
-- ------------------------------
procedure Clear is
procedure Free is
new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access);
begin
while not Events.Is_Empty loop
declare
Block : Event_Block_Access := Events.First_Element;
begin
Free (Block);
Events.Delete_First;
end;
end loop;
Current := null;
Last_Id := 0;
Ids.Clear;
end Clear;
end Event_Collector;
end MAT.Events.Targets;
|
Implement the Update_Event procedure
|
Implement the Update_Event procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
db844047130196fc19260a07de206737374f0f6c
|
src/asf-beans-resolvers.adb
|
src/asf-beans-resolvers.adb
|
-----------------------------------------------------------------------
-- asf-beans-resolvers -- Resolver to create and give access to managed beans
-- 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 ASF.Sessions;
with ASF.Beans.Params;
with ASF.Beans.Flash;
with ASF.Beans.Globals;
with ASF.Beans.Headers;
package body ASF.Beans.Resolvers is
-- ------------------------------
-- Resolve the name represented by <tt>Name</tt> according to a base object <tt>Base</tt>.
-- The resolver tries to look first in pre-defined objects (params, flash, headers, initParam).
-- It then looks in the request and session attributes for the value. If the value was
-- not in the request or session, it uses the application bean factory to create the
-- new managed bean and adds it to the request or session.
-- ------------------------------
overriding
function Get_Value (Resolver : in ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : in Ada.Strings.Unbounded.Unbounded_String)
return Util.Beans.Objects.Object is
use type Util.Beans.Basic.Readonly_Bean_Access;
use type ASF.Requests.Request_Access;
Key : constant String := To_String (Name);
begin
if Base /= null then
return Base.Get_Value (Key);
elsif Key = ASF.Beans.Params.PARAM_ATTRIBUTE_NAME then
return ASF.Beans.Params.Instance;
elsif Key = ASF.Beans.Headers.HEADER_ATTRIBUTE_NAME then
return ASF.Beans.Headers.Instance;
elsif Key = ASF.Beans.Flash.FLASH_ATTRIBUTE_NAME then
return ASF.Beans.Flash.Instance;
elsif Key = ASF.Beans.Globals.INIT_PARAM_ATTRIBUTE_NAME then
return ASF.Beans.Globals.Instance;
end if;
declare
Result : Util.Beans.Objects.Object;
Scope : Scope_Type;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- Look in the resolver's attributes first.
Pos : constant Util.Beans.Objects.Maps.Cursor := Resolver.Attributes.Find (Key);
begin
if Util.Beans.Objects.Maps.Has_Element (Pos) then
return Util.Beans.Objects.Maps.Element (Pos);
elsif Resolver.Request /= null then
Result := Resolver.Request.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
-- If there is a session, look if the attribute is defined there.
declare
Session : ASF.Sessions.Session := Resolver.Request.Get_Session;
begin
if Session.Is_Valid then
Result := Session.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
end if;
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := Util.Beans.Objects.To_Object (Bean);
if Scope = SESSION_SCOPE then
Session.Set_Attribute (Name => Key,
Value => Result);
else
Resolver.Request.Set_Attribute (Name => Key,
Value => Result);
end if;
return Result;
end;
else
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := Util.Beans.Objects.To_Object (Bean);
Resolver.Attributes_Access.Include (Key, Result);
return Result;
end if;
end;
end Get_Value;
-- ------------------------------
-- Sets the value represented by the <tt>Name</tt> in the base object <tt>Base</tt>.
-- If there is no <tt>Base</tt> object, the request attribute with the given name is
-- updated to the given value.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in out ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Context);
Key : constant String := To_String (Name);
begin
if Base /= null then
Base.Set_Value (Name => Key, Value => Value);
else
Resolver.Request.Set_Attribute (Name => Key, Value => Value);
end if;
end Set_Value;
-- ------------------------------
-- Initialize the resolver.
-- ------------------------------
overriding
procedure Initialize (Resolver : in out ELResolver) is
begin
Resolver.Attributes_Access := Resolver.Attributes'Unchecked_Access;
end Initialize;
end ASF.Beans.Resolvers;
|
-----------------------------------------------------------------------
-- asf-beans-resolvers -- Resolver to create and give access to managed beans
-- 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 ASF.Sessions;
with ASF.Beans.Params;
with ASF.Beans.Flash;
with ASF.Beans.Globals;
with ASF.Beans.Headers;
package body ASF.Beans.Resolvers is
-- ------------------------------
-- Initialize the EL resolver to use the application bean factory and the given request.
-- ------------------------------
procedure Initialize (Resolver : in out ELResolver;
App : in ASF.Applications.Main.Application_Access;
Request : in ASF.Requests.Request_Access) is
begin
Resolver.Application := App;
Resolver.Request := Request;
Resolver.Attributes_Access := Resolver.Attributes'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Resolve the name represented by <tt>Name</tt> according to a base object <tt>Base</tt>.
-- The resolver tries to look first in pre-defined objects (params, flash, headers, initParam).
-- It then looks in the request and session attributes for the value. If the value was
-- not in the request or session, it uses the application bean factory to create the
-- new managed bean and adds it to the request or session.
-- ------------------------------
overriding
function Get_Value (Resolver : in ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : in Ada.Strings.Unbounded.Unbounded_String)
return Util.Beans.Objects.Object is
use type Util.Beans.Basic.Readonly_Bean_Access;
use type ASF.Requests.Request_Access;
Key : constant String := To_String (Name);
begin
if Base /= null then
return Base.Get_Value (Key);
elsif Key = ASF.Beans.Params.PARAM_ATTRIBUTE_NAME then
return ASF.Beans.Params.Instance;
elsif Key = ASF.Beans.Headers.HEADER_ATTRIBUTE_NAME then
return ASF.Beans.Headers.Instance;
elsif Key = ASF.Beans.Flash.FLASH_ATTRIBUTE_NAME then
return ASF.Beans.Flash.Instance;
elsif Key = ASF.Beans.Globals.INIT_PARAM_ATTRIBUTE_NAME then
return ASF.Beans.Globals.Instance;
end if;
declare
Result : Util.Beans.Objects.Object;
Scope : Scope_Type;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- Look in the resolver's attributes first.
Pos : constant Util.Beans.Objects.Maps.Cursor := Resolver.Attributes.Find (Key);
begin
if Util.Beans.Objects.Maps.Has_Element (Pos) then
return Util.Beans.Objects.Maps.Element (Pos);
elsif Resolver.Request /= null then
Result := Resolver.Request.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
-- If there is a session, look if the attribute is defined there.
declare
Session : ASF.Sessions.Session := Resolver.Request.Get_Session;
begin
if Session.Is_Valid then
Result := Session.Get_Attribute (Key);
if not Util.Beans.Objects.Is_Null (Result) then
return Result;
end if;
end if;
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := Util.Beans.Objects.To_Object (Bean);
if Scope = SESSION_SCOPE then
Session.Set_Attribute (Name => Key,
Value => Result);
else
Resolver.Request.Set_Attribute (Name => Key,
Value => Result);
end if;
return Result;
end;
else
Resolver.Application.Create (Name, Context, Bean, Scope);
if Bean = null then
return Resolver.Application.Get_Global (Name, Context);
end if;
Result := Util.Beans.Objects.To_Object (Bean);
Resolver.Attributes_Access.Include (Key, Result);
return Result;
end if;
end;
end Get_Value;
-- ------------------------------
-- Sets the value represented by the <tt>Name</tt> in the base object <tt>Base</tt>.
-- If there is no <tt>Base</tt> object, the request attribute with the given name is
-- updated to the given value.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in out ELResolver;
Context : in EL.Contexts.ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Context);
Key : constant String := To_String (Name);
begin
if Base /= null then
Base.Set_Value (Name => Key, Value => Value);
else
Resolver.Request.Set_Attribute (Name => Key, Value => Value);
end if;
end Set_Value;
-- ------------------------------
-- Initialize the resolver.
-- ------------------------------
overriding
procedure Initialize (Resolver : in out ELResolver) is
begin
Resolver.Attributes_Access := Resolver.Attributes'Unchecked_Access;
end Initialize;
end ASF.Beans.Resolvers;
|
Initialize the EL resolver to use the application bean factory and the given request.
|
Initialize the EL resolver to use the application bean factory and the
given request.
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
0a1f8aef5d33812f1b3461b66796d86eaf87ad8c
|
src/gen-artifacts-xmi.ads
|
src/gen-artifacts-xmi.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
with Util.Strings.Sets;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class;
Is_Predefined : in Boolean := False);
private
-- Read the UML profiles that are referenced by the current models.
-- The UML profiles are installed in the UML config directory for dynamo's installation.
procedure Read_Profiles (Handler : in out Artifact;
Context : in out Generator'Class);
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
-- A set of profiles that are necessary for the model definitions.
Profiles : aliased Util.Strings.Sets.Set;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Type_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Generator_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Literal_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Length_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012, 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 DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
with Util.Strings.Sets;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class;
Is_Predefined : in Boolean := False);
private
-- Read the UML profiles that are referenced by the current models.
-- The UML profiles are installed in the UML config directory for dynamo's installation.
procedure Read_Profiles (Handler : in out Artifact;
Context : in out Generator'Class);
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
-- A set of profiles that are necessary for the model definitions.
Profiles : aliased Util.Strings.Sets.Set;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Type_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Generator_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Literal_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Length_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Limited_Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
Add a Limited_Bean_Stereotype member in the XMI artifact
|
Add a Limited_Bean_Stereotype member in the XMI artifact
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
38c8ce0daacb3c1f9db8316a9aadaf4b2f1d8a6f
|
src/sys/os-unix/util-processes-os.adb
|
src/sys/os-unix/util-processes-os.adb
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2017, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Unchecked_Deallocation;
package body Util.Processes.Os is
use Util.Systems.Os;
use type Interfaces.C.size_t;
use type Util.Systems.Types.File_Type;
use type Ada.Directories.File_Kind;
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;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class) is
Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir);
begin
Interfaces.C.Strings.Free (Sys.Dir);
if Dir'Length > 0 then
if not Ada.Directories.Exists (Dir)
or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory
then
raise Ada.Directories.Name_Error with "Invalid directory: " & Dir;
end if;
Sys.Dir := Interfaces.C.Strings.New_String (Dir);
end if;
end Prepare_Working_Directory;
-- ------------------------------
-- Spawn a new process.
-- ------------------------------
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
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;
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
Sys.Prepare_Working_Directory (Proc);
-- 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 = 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 or Mode = READ_WRITE or Mode = READ_ALL or Mode = READ_WRITE_ALL then
if Sys_Pipe (Stdout_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stdout 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 Proc.To_Close /= null then
for Fd of Proc.To_Close.all loop
Result := Sys_Close (Fd);
end loop;
end if;
-- Handle stdin/stdout/stderr pipe redirections unless they are file-redirected.
if Sys.Err_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE
and (Mode = READ_ALL or Mode = READ_WRITE_ALL)
then
Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO);
end if;
-- Redirect stdin to the pipe unless we use file redirection.
if Sys.In_File = Null_Ptr and Stdin_Pipes (0) /= NO_FILE then
if Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO);
end if;
end if;
if Stdin_Pipes (0) /= NO_FILE and Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Close (Stdin_Pipes (0));
end if;
if Stdin_Pipes (1) /= NO_FILE then
Result := Sys_Close (Stdin_Pipes (1));
end if;
-- Redirect stdout to the pipe unless we use file redirection.
if Sys.Out_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then
if Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO);
end if;
end if;
if Stdout_Pipes (1) /= NO_FILE and Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Close (Stdout_Pipes (1));
end if;
if Stdout_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stdout_Pipes (0));
end if;
if Sys.Err_File = Null_Ptr and 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));
end if;
if Sys.In_File /= Null_Ptr then
-- Redirect the process input from a file.
declare
Fd : File_Type;
begin
Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#);
if Fd < 0 then
Sys_Exit (254);
end if;
if Fd /= STDIN_FILENO then
Result := Sys_Dup2 (Fd, STDIN_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if 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;
if Fd /= STDOUT_FILENO then
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if 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;
if Fd /= STDERR_FILENO then
Result := Sys_Dup2 (Fd, STDERR_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if Sys.Dir /= Null_Ptr then
Result := Sys_Chdir (Sys.Dir);
if Result < 0 then
Sys_Exit (253);
end if;
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;
To_Close : in File_Type_Array_Access) 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;
Sys.To_Close := To_Close;
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);
Interfaces.C.Strings.Free (Sys.Dir);
end Finalize;
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2017, 2018, 2019, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with Util.Strings;
package body Util.Processes.Os is
use Util.Systems.Os;
use type Interfaces.C.size_t;
use type Util.Systems.Types.File_Type;
use type Ada.Directories.File_Kind;
type Pipe_Type is array (0 .. 1) of File_Type;
procedure Close (Pipes : in out Pipe_Type);
procedure Free_Array (Argv : in out Util.Systems.Os.Ptr_Ptr_Array);
procedure Allocate (Into : in out Util.Systems.Os.Ptr_Ptr_Array;
Count : in Interfaces.C.size_t);
-- ------------------------------
-- 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;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class) is
Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir);
begin
Interfaces.C.Strings.Free (Sys.Dir);
if Dir'Length > 0 then
if not Ada.Directories.Exists (Dir)
or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory
then
raise Ada.Directories.Name_Error with "Invalid directory: " & Dir;
end if;
Sys.Dir := Interfaces.C.Strings.New_String (Dir);
end if;
end Prepare_Working_Directory;
-- ------------------------------
-- Spawn a new process.
-- ------------------------------
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
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;
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
Sys.Prepare_Working_Directory (Proc);
-- 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 = 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 or Mode = READ_WRITE or Mode = READ_ALL or Mode = READ_WRITE_ALL then
if Sys_Pipe (Stdout_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stdout 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 Proc.To_Close /= null then
for Fd of Proc.To_Close.all loop
Result := Sys_Close (Fd);
end loop;
end if;
-- Handle stdin/stdout/stderr pipe redirections unless they are file-redirected.
if Sys.Err_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE
and (Mode = READ_ALL or Mode = READ_WRITE_ALL)
then
Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO);
end if;
-- Redirect stdin to the pipe unless we use file redirection.
if Sys.In_File = Null_Ptr and Stdin_Pipes (0) /= NO_FILE then
if Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO);
end if;
end if;
if Stdin_Pipes (0) /= NO_FILE and Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Close (Stdin_Pipes (0));
end if;
if Stdin_Pipes (1) /= NO_FILE then
Result := Sys_Close (Stdin_Pipes (1));
end if;
-- Redirect stdout to the pipe unless we use file redirection.
if Sys.Out_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then
if Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO);
end if;
end if;
if Stdout_Pipes (1) /= NO_FILE and Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Close (Stdout_Pipes (1));
end if;
if Stdout_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stdout_Pipes (0));
end if;
if Sys.Err_File = Null_Ptr and 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));
end if;
if Sys.In_File /= Null_Ptr then
-- Redirect the process input from a file.
declare
Fd : File_Type;
begin
Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#);
if Fd < 0 then
Sys_Exit (254);
end if;
if Fd /= STDIN_FILENO then
Result := Sys_Dup2 (Fd, STDIN_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if 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;
if Fd /= STDOUT_FILENO then
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if 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;
if Fd /= STDERR_FILENO then
Result := Sys_Dup2 (Fd, STDERR_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if Sys.Dir /= Null_Ptr then
Result := Sys_Chdir (Sys.Dir);
if Result < 0 then
Sys_Exit (253);
end if;
end if;
if Sys.Envp /= null then
Result := Sys_Execve (Sys.Argv (0), Sys.Argv.all, Sys.Envp.all);
else
Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all);
end if;
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);
procedure Allocate (Into : in out Util.Systems.Os.Ptr_Ptr_Array;
Count : in Interfaces.C.size_t) is
begin
if Into = null then
Into := new Ptr_Array (0 .. 10);
elsif Count = Into'Last - 1 then
declare
N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Count + 32);
begin
N (0 .. Count) := Into (0 .. Count);
Free (Into);
Into := N;
end;
end if;
end Allocate;
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
begin
Allocate (Sys.Argv, Sys.Argc);
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;
-- ------------------------------
-- Clear the program arguments.
-- ------------------------------
overriding
procedure Clear_Arguments (Sys : in out System_Process) is
begin
if Sys.Argv /= null then
Free_Array (Sys.Argv);
end if;
Sys.Argc := 0;
end Clear_Arguments;
-- ------------------------------
-- Set the environment variable to be used by the process before its creation.
-- ------------------------------
overriding
procedure Set_Environment (Sys : in out System_Process;
Name : in String;
Value : in String) is
begin
if Sys.Envc > 0 then
for I in 0 .. Sys.Envc loop
declare
Env : Interfaces.C.Strings.chars_ptr := Sys.Envp (I);
V : constant String := Interfaces.C.Strings.Value (Env);
begin
if Util.Strings.Starts_With (V, Name & "=") then
Interfaces.C.Strings.Free (Env);
Sys.Envp (I) := Interfaces.C.Strings.New_String (Name & "=" & Value);
return;
end if;
end;
end loop;
end if;
Allocate (Sys.Envp, Sys.Envc);
Sys.Envp (Sys.Envc) := Interfaces.C.Strings.New_String (Name & "=" & Value);
Sys.Envc := Sys.Envc + 1;
Sys.Envp (Sys.Envc) := Interfaces.C.Strings.Null_Ptr;
end Set_Environment;
-- ------------------------------
-- 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;
To_Close : in File_Type_Array_Access) is
begin
if Input'Length > 0 then
Sys.In_File := Interfaces.C.Strings.New_String (Input);
else
Interfaces.C.Strings.Free (Sys.In_File);
end if;
if Output'Length > 0 then
Sys.Out_File := Interfaces.C.Strings.New_String (Output);
Sys.Out_Append := Append_Output;
else
Interfaces.C.Strings.Free (Sys.Out_File);
end if;
if Error'Length > 0 then
Sys.Err_File := Interfaces.C.Strings.New_String (Error);
Sys.Err_Append := Append_Error;
else
Interfaces.C.Strings.Free (Sys.Err_File);
end if;
Sys.To_Close := To_Close;
end Set_Streams;
procedure Free_Array (Argv : in out Util.Systems.Os.Ptr_Ptr_Array) is
begin
for I in Argv'Range loop
Interfaces.C.Strings.Free (Argv (I));
end loop;
Free (Argv);
end Free_Array;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
begin
if Sys.Argv /= null then
Free_Array (Sys.Argv);
end if;
if Sys.Envp /= null then
Free_Array (Sys.Envp);
end if;
Interfaces.C.Strings.Free (Sys.In_File);
Interfaces.C.Strings.Free (Sys.Out_File);
Interfaces.C.Strings.Free (Sys.Err_File);
Interfaces.C.Strings.Free (Sys.Dir);
end Finalize;
end Util.Processes.Os;
|
Implement Set_Environment and Clear_Arguments When launching a process, use Sys_Execve if we have a specific set of environment variables Clear the Envp array when the record is finalized.
|
Implement Set_Environment and Clear_Arguments
When launching a process, use Sys_Execve if we have a specific set of environment variables
Clear the Envp array when the record is finalized.
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
5d9bb039f0f3111452be8de67641d1d631011880
|
src/sys/os-unix/util-processes-os.adb
|
src/sys/os-unix/util-processes-os.adb
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Unchecked_Deallocation;
package body Util.Processes.Os is
use Util.Systems.Os;
use type Interfaces.C.size_t;
use type Util.Systems.Types.File_Type;
use type Ada.Directories.File_Kind;
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;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class) is
Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir);
begin
Interfaces.C.Strings.Free (Sys.Dir);
if Dir'Length > 0 then
if not Ada.Directories.Exists (Dir)
or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory
then
raise Ada.Directories.Name_Error with "Invalid directory: " & Dir;
end if;
Sys.Dir := Interfaces.C.Strings.New_String (Dir);
end if;
end Prepare_Working_Directory;
-- ------------------------------
-- Spawn a new process.
-- ------------------------------
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
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;
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
Sys.Prepare_Working_Directory (Proc);
-- 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 = 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 or Mode = READ_WRITE or Mode = READ_ALL then
if Sys_Pipe (Stdout_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stdout 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 Proc.To_Close /= null then
for Fd of Proc.To_Close.all loop
Result := Sys_Close (Fd);
end loop;
end if;
-- Handle stdin/stdout/stderr pipe redirections unless they are file-redirected.
if Sys.Err_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then
Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO);
end if;
-- Redirect stdin to the pipe unless we use file redirection.
if Sys.In_File = Null_Ptr and Stdin_Pipes (0) /= NO_FILE then
if Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO);
end if;
end if;
if Stdin_Pipes (0) /= NO_FILE and Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Close (Stdin_Pipes (0));
end if;
if Stdin_Pipes (1) /= NO_FILE then
Result := Sys_Close (Stdin_Pipes (1));
end if;
-- Redirect stdout to the pipe unless we use file redirection.
if Sys.Out_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then
if Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO);
end if;
end if;
if Stdout_Pipes (1) /= NO_FILE and Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Close (Stdout_Pipes (1));
end if;
if Stdout_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stdout_Pipes (0));
end if;
if Sys.Err_File = Null_Ptr and 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));
end if;
if Sys.In_File /= Null_Ptr then
-- Redirect the process input from a file.
declare
Fd : File_Type;
begin
Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#);
if Fd < 0 then
Sys_Exit (254);
end if;
if Fd /= STDIN_FILENO then
Result := Sys_Dup2 (Fd, STDIN_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if 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;
if Fd /= STDOUT_FILENO then
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if 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;
if Fd /= STDERR_FILENO then
Result := Sys_Dup2 (Fd, STDERR_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if Sys.Dir /= Null_Ptr then
Result := Sys_Chdir (Sys.Dir);
if Result < 0 then
Sys_Exit (253);
end if;
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;
To_Close : in File_Type_Array_Access) 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;
Sys.To_Close := To_Close;
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);
Interfaces.C.Strings.Free (Sys.Dir);
end Finalize;
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Unchecked_Deallocation;
package body Util.Processes.Os is
use Util.Systems.Os;
use type Interfaces.C.size_t;
use type Util.Systems.Types.File_Type;
use type Ada.Directories.File_Kind;
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;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class) is
Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir);
begin
Interfaces.C.Strings.Free (Sys.Dir);
if Dir'Length > 0 then
if not Ada.Directories.Exists (Dir)
or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory
then
raise Ada.Directories.Name_Error with "Invalid directory: " & Dir;
end if;
Sys.Dir := Interfaces.C.Strings.New_String (Dir);
end if;
end Prepare_Working_Directory;
-- ------------------------------
-- Spawn a new process.
-- ------------------------------
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
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;
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
Sys.Prepare_Working_Directory (Proc);
-- 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 = 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 or Mode = READ_WRITE or Mode = READ_ALL or Mode = READ_WRITE_ALL then
if Sys_Pipe (Stdout_Pipes'Address) /= 0 then
Cleanup;
raise Process_Error with "Cannot create stdout 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 Proc.To_Close /= null then
for Fd of Proc.To_Close.all loop
Result := Sys_Close (Fd);
end loop;
end if;
-- Handle stdin/stdout/stderr pipe redirections unless they are file-redirected.
if Sys.Err_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then
Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO);
end if;
-- Redirect stdin to the pipe unless we use file redirection.
if Sys.In_File = Null_Ptr and Stdin_Pipes (0) /= NO_FILE then
if Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO);
end if;
end if;
if Stdin_Pipes (0) /= NO_FILE and Stdin_Pipes (0) /= STDIN_FILENO then
Result := Sys_Close (Stdin_Pipes (0));
end if;
if Stdin_Pipes (1) /= NO_FILE then
Result := Sys_Close (Stdin_Pipes (1));
end if;
-- Redirect stdout to the pipe unless we use file redirection.
if Sys.Out_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then
if Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO);
end if;
end if;
if Stdout_Pipes (1) /= NO_FILE and Stdout_Pipes (1) /= STDOUT_FILENO then
Result := Sys_Close (Stdout_Pipes (1));
end if;
if Stdout_Pipes (0) /= NO_FILE then
Result := Sys_Close (Stdout_Pipes (0));
end if;
if Sys.Err_File = Null_Ptr and 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));
end if;
if Sys.In_File /= Null_Ptr then
-- Redirect the process input from a file.
declare
Fd : File_Type;
begin
Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#);
if Fd < 0 then
Sys_Exit (254);
end if;
if Fd /= STDIN_FILENO then
Result := Sys_Dup2 (Fd, STDIN_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if 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;
if Fd /= STDOUT_FILENO then
Result := Sys_Dup2 (Fd, STDOUT_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if 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;
if Fd /= STDERR_FILENO then
Result := Sys_Dup2 (Fd, STDERR_FILENO);
Result := Sys_Close (Fd);
end if;
end;
end if;
if Sys.Dir /= Null_Ptr then
Result := Sys_Chdir (Sys.Dir);
if Result < 0 then
Sys_Exit (253);
end if;
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;
To_Close : in File_Type_Array_Access) 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;
Sys.To_Close := To_Close;
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);
Interfaces.C.Strings.Free (Sys.Dir);
end Finalize;
end Util.Processes.Os;
|
Fix handling the READ_WRITE_ALL mode for Spawn
|
Fix handling the READ_WRITE_ALL mode for Spawn
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
eb4a52f34e867e43536e1af8e658926f45e7788e
|
src/asf-components-html-text.ads
|
src/asf-components-html-text.ads
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010, 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ASF.Components.Holders;
with ASF.Converters;
-- The <b>Text</b> package implements various components used to print text outputs.
--
-- See JSR 314 - JavaServer Faces Specification 4.1.10 UIOutput
--
-- The <b>UILabel</b> and <b>UIOutputFormat</b> components is ASF implementation of
-- the JavaServer Faces outputLabel and outputFormat components
-- (implemented with UIOutput in Java).
package ASF.Components.Html.Text is
-- ------------------------------
-- Output Component
-- ------------------------------
type UIOutput is new UIHtmlComponent and Holders.Value_Holder with private;
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
overriding
function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object;
-- Get the value of the component. If the component has a local
-- value which is not null, returns it. Otherwise, if we have a Value_Expression
-- evaluate and returns the value.
overriding
function Get_Value (UI : in UIOutput) return EL.Objects.Object;
-- Set the value to write on the output.
overriding
procedure Set_Value (UI : in out UIOutput;
Value : in EL.Objects.Object);
-- Get the converter that is registered on the component.
overriding
function Get_Converter (UI : in UIOutput)
return ASF.Converters.Converter_Access;
-- Set the converter to be used on the component.
overriding
procedure Set_Converter (UI : in out UIOutput;
Converter : in ASF.Converters.Converter_Access;
Release : in Boolean := False);
overriding
procedure Finalize (UI : in out UIOutput);
-- Get the value of the component and apply the To_String converter on it if there is one.
function Get_Formatted_Value (UI : in UIOutput;
Context : in Contexts.Faces.Faces_Context'Class) return String;
-- Format the value by appling the To_String converter on it if there is one.
function Get_Formatted_Value (UI : in UIOutput;
Value : in Util.Beans.Objects.Object;
Context : in Contexts.Faces.Faces_Context'Class) return String;
procedure Write_Output (UI : in UIOutput;
Context : in out Contexts.Faces.Faces_Context'Class;
Value : in String);
procedure Encode_Begin (UI : in UIOutput;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Label Component
-- ------------------------------
type UIOutputLabel is new UIOutput with private;
procedure Encode_Begin (UI : in UIOutputLabel;
Context : in out Contexts.Faces.Faces_Context'Class);
procedure Encode_End (UI : in UIOutputLabel;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- OutputFormat Component
-- ------------------------------
--
type UIOutputFormat is new UIOutput with private;
procedure Encode_Begin (UI : in UIOutputFormat;
Context : in out Contexts.Faces.Faces_Context'Class);
private
type UIOutput is new UIHtmlComponent and Holders.Value_Holder with record
Value : EL.Objects.Object;
Converter : ASF.Converters.Converter_Access := null;
Release_Converter : Boolean := False;
end record;
type UIOutputLabel is new UIOutput with null record;
type UIOutputFormat is new UIOutput with null record;
end ASF.Components.Html.Text;
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010, 2011, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ASF.Components.Holders;
with ASF.Converters;
-- The <b>Text</b> package implements various components used to print text outputs.
--
-- See JSR 314 - JavaServer Faces Specification 4.1.10 UIOutput
--
-- The <b>UILabel</b> and <b>UIOutputFormat</b> components is ASF implementation of
-- the JavaServer Faces outputLabel and outputFormat components
-- (implemented with UIOutput in Java).
package ASF.Components.Html.Text is
-- ------------------------------
-- Output Component
-- ------------------------------
type UIOutput is new UIHtmlComponent and Holders.Value_Holder with private;
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
overriding
function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object;
-- Get the value of the component. If the component has a local
-- value which is not null, returns it. Otherwise, if we have a Value_Expression
-- evaluate and returns the value.
overriding
function Get_Value (UI : in UIOutput) return EL.Objects.Object;
-- Set the value to write on the output.
overriding
procedure Set_Value (UI : in out UIOutput;
Value : in EL.Objects.Object);
-- Get the converter that is registered on the component.
overriding
function Get_Converter (UI : in UIOutput)
return ASF.Converters.Converter_Access;
-- Set the converter to be used on the component.
overriding
procedure Set_Converter (UI : in out UIOutput;
Converter : in ASF.Converters.Converter_Access;
Release : in Boolean := False);
-- Get the converter associated with the component
function Get_Converter (UI : in UIOutput;
Context : in Faces_Context'Class)
return access ASF.Converters.Converter'Class;
overriding
procedure Finalize (UI : in out UIOutput);
-- Get the value of the component and apply the To_String converter on it if there is one.
function Get_Formatted_Value (UI : in UIOutput;
Context : in Contexts.Faces.Faces_Context'Class) return String;
-- Format the value by appling the To_String converter on it if there is one.
function Get_Formatted_Value (UI : in UIOutput;
Value : in Util.Beans.Objects.Object;
Context : in Contexts.Faces.Faces_Context'Class) return String;
procedure Write_Output (UI : in UIOutput;
Context : in out Contexts.Faces.Faces_Context'Class;
Value : in String);
procedure Encode_Begin (UI : in UIOutput;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Label Component
-- ------------------------------
type UIOutputLabel is new UIOutput with private;
procedure Encode_Begin (UI : in UIOutputLabel;
Context : in out Contexts.Faces.Faces_Context'Class);
procedure Encode_End (UI : in UIOutputLabel;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- OutputFormat Component
-- ------------------------------
--
type UIOutputFormat is new UIOutput with private;
procedure Encode_Begin (UI : in UIOutputFormat;
Context : in out Contexts.Faces.Faces_Context'Class);
private
type UIOutput is new UIHtmlComponent and Holders.Value_Holder with record
Value : EL.Objects.Object;
Converter : ASF.Converters.Converter_Access := null;
Release_Converter : Boolean := False;
end record;
type UIOutputLabel is new UIOutput with null record;
type UIOutputFormat is new UIOutput with null record;
end ASF.Components.Html.Text;
|
Declare the Get_Converter function
|
Declare the Get_Converter function
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
de87929f2d43062aaf62d7514693e6189af876ee
|
awa/src/awa-applications-factory.ads
|
awa/src/awa-applications-factory.ads
|
-----------------------------------------------------------------------
-- awa-applications-factory -- Factory 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 ASF.Applications.Main;
with Security.Permissions;
package AWA.Applications.Factory is
-- ------------------------------
-- Application factory to setup the permission manager.
-- ------------------------------
type Application_Factory is new ASF.Applications.Main.Application_Factory with private;
-- Create the permission manager. The permission manager is created during
-- the initialization phase of the application. This implementation
-- creates a <b>AWA.Permissions.Services.Permission_Manager</b> object.
overriding
function Create_Permission_Manager (App : in Application_Factory)
return Security.Permissions.Permission_Manager_Access;
-- Set the application instance that will be used when creating the permission manager.
procedure Set_Application (Factory : in out ASF.Applications.Main.Application_Factory'Class;
App : in Application_Access);
private
type Application_Factory is new ASF.Applications.Main.Application_Factory with record
App : Application_Access := null;
end record;
end AWA.Applications.Factory;
|
-----------------------------------------------------------------------
-- awa-applications-factory -- Factory for AWA Applications
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications.Main;
with Security.Policies;
package AWA.Applications.Factory is
-- ------------------------------
-- Application factory to setup the permission manager.
-- ------------------------------
type Application_Factory is new ASF.Applications.Main.Application_Factory with private;
-- Create the security manager. The security manager is created during
-- the initialization phase of the application. This implementation
-- creates a <b>AWA.Permissions.Services.Permission_Manager</b> object.
overriding
function Create_Security_Manager (App : in Application_Factory)
return Security.Policies.Policy_Manager_Access;
-- Set the application instance that will be used when creating the permission manager.
procedure Set_Application (Factory : in out ASF.Applications.Main.Application_Factory'Class;
App : in Application_Access);
private
type Application_Factory is new ASF.Applications.Main.Application_Factory with record
App : Application_Access := null;
end record;
end AWA.Applications.Factory;
|
Rename Create_Permission_Manager into Create_Security_Manager
|
Rename Create_Permission_Manager into Create_Security_Manager
|
Ada
|
apache-2.0
|
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
6db120b22ead17904fa6d17200c0f7b82b9cb370
|
src/util-strings.ads
|
src/util-strings.ads
|
-----------------------------------------------------------------------
-- 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;
|
-----------------------------------------------------------------------
-- 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 True if the source string starts with the given prefix.
function Starts_With (Source : in String;
Prefix : in String) return Boolean;
-- 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;
|
Declare the Starts_With function to check if a string starts with a given prefix
|
Declare the Starts_With function to check if a string starts with a given prefix
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ddc6f44768a9a2e83aec277c26604eafcdb67b60
|
src/wiki-plugins.ads
|
src/wiki-plugins.ads
|
-----------------------------------------------------------------------
-- wiki-plugins -- Wiki plugins
-- 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.Attributes;
with Wiki.Documents;
with Wiki.Filters;
-- == Plugins ==
-- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki
-- engine to provide pluggable extensions in the Wiki.
--
package Wiki.Plugins is
pragma Preelaborate;
type Plugin_Context;
type Wiki_Plugin is limited interface;
type Wiki_Plugin_Access is access all Wiki_Plugin'Class;
type Plugin_Factory is limited interface;
type Plugin_Factory_Access is access all Plugin_Factory'Class;
-- Find a plugin knowing its name.
function Find (Factory : in Plugin_Factory;
Name : in String) return Wiki_Plugin_Access is abstract;
type Plugin_Context is limited record
Previous : access Plugin_Context;
Filters : Wiki.Filters.Filter_Chain;
Factory : Plugin_Factory_Access;
Variables : Wiki.Attributes.Attribute_List;
Syntax : Wiki.Wiki_Syntax;
Is_Hidden : Boolean := False;
Is_Included : Boolean := False;
end record;
-- Expand the plugin configured with the parameters for the document.
procedure Expand (Plugin : in out Wiki_Plugin;
Document : in out Wiki.Documents.Document;
Params : in out Wiki.Attributes.Attribute_List;
Context : in Plugin_Context) is abstract;
end Wiki.Plugins;
|
-----------------------------------------------------------------------
-- wiki-plugins -- Wiki plugins
-- 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.Attributes;
with Wiki.Documents;
with Wiki.Filters;
with Wiki.Strings;
-- == Plugins ==
-- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki
-- engine to provide pluggable extensions in the Wiki.
--
package Wiki.Plugins is
pragma Preelaborate;
type Plugin_Context;
type Wiki_Plugin is limited interface;
type Wiki_Plugin_Access is access all Wiki_Plugin'Class;
type Plugin_Factory is limited interface;
type Plugin_Factory_Access is access all Plugin_Factory'Class;
-- Find a plugin knowing its name.
function Find (Factory : in Plugin_Factory;
Name : in String) return Wiki_Plugin_Access is abstract;
type Plugin_Context is limited record
Previous : access Plugin_Context;
Filters : Wiki.Filters.Filter_Chain;
Factory : Plugin_Factory_Access;
Variables : Wiki.Attributes.Attribute_List;
Syntax : Wiki.Wiki_Syntax;
Ident : Wiki.Strings.UString;
Is_Hidden : Boolean := False;
Is_Included : Boolean := False;
end record;
-- Expand the plugin configured with the parameters for the document.
procedure Expand (Plugin : in out Wiki_Plugin;
Document : in out Wiki.Documents.Document;
Params : in out Wiki.Attributes.Attribute_List;
Context : in Plugin_Context) is abstract;
end Wiki.Plugins;
|
Add an Ident member to the wiki context
|
Add an Ident member to the wiki context
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
3f36397b87c1d358bbd89b4f1f17e0f4ce1a5fac
|
ARM/STMicro/STM32/drivers/stm32-i2c.adb
|
ARM/STMicro/STM32/drivers/stm32-i2c.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 STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_i2c.c --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief I2C HAL module driver. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
with Ada.Real_Time; use Ada.Real_Time;
with STM32.RCC; use STM32.RCC;
with STM32_SVD.I2C; use STM32_SVD.I2C;
package body STM32.I2C is
---------------
-- Configure --
---------------
procedure Configure
(Port : in out I2C_Port;
Clock_Speed : Word;
Mode : I2C_Device_Mode;
Duty_Cycle : I2C_Duty_Cycle;
Own_Address : Half_Word;
Ack : I2C_Acknowledgement;
Ack_Address : I2C_Acknowledge_Address)
is
CR1 : CR1_Register;
CCR : CCR_Register;
OAR1 : OAR1_Register;
PCLK1 : constant Word := System_Clock_Frequencies.PCLK1;
Freq_Range : constant Half_Word := Half_Word (PCLK1 / 1_000_000);
begin
-- Load CR2 and clear FREQ
Port.CR2 :=
(LAST => 0,
DMAEN => 0,
ITBUFEN => 0,
ITEVTEN => 0,
ITERREN => 0,
FREQ => UInt6 (Freq_Range),
others => <>);
Set_State (Port, Disabled);
if Clock_Speed <= 100_000 then
-- Mode selection to Standard Mode
CCR.F_S := 0;
CCR.CCR := UInt12 (PCLK1 / (Clock_Speed * 2));
if CCR.CCR < 4 then
CCR.CCR := 4;
end if;
Port.TRISE.TRISE := UInt6 (Freq_Range + 1);
else
-- Fast mode
CCR.F_S := 1;
if Duty_Cycle = DutyCycle_2 then
CCR.CCR := UInt12 (Pclk1 / (Clock_Speed * 3));
else
CCR.CCR := UInt12 (Pclk1 / (Clock_Speed * 25));
CCR.DUTY := 1;
end if;
if CCR.CCR = 0 then
CCR.CCR := 1;
end if;
CCR.CCR := CCR.CCR or 16#80#;
Port.TRISE.TRISE := UInt6 ((Word (Freq_Range) * 300) / 1000 + 1);
end if;
Port.CCR := CCR;
Set_State (Port, Enabled);
CR1 := Port.CR1;
case Mode is
when I2C_Mode =>
CR1.SMBUS := 0;
CR1.SMBTYPE := 0;
when SMBusDevice_Mode =>
CR1.SMBUS := 1;
CR1.SMBTYPE := 0;
when SMBusHost_Mode =>
CR1.SMBUS := 1;
CR1.SMBTYPE := 1;
end case;
CR1.ACK := I2C_Acknowledgement'Enum_Rep (Ack);
Port.CR1 := CR1;
OAR1.ADDMODE := (if Ack_Address = AcknowledgedAddress_10bit
then 1 else 0);
case Ack_Address is
when AcknowledgedAddress_7bit =>
OAR1.ADD0 := 0;
OAR1.ADD7 := UInt7 (Own_Address / 2);
OAR1.ADD10 := 0;
when AcknowledgedAddress_10bit =>
OAR1.Add0 := Bit (Own_Address and 2#1#);
OAR1.ADD7 := UInt7 ((Own_Address / 2) and 2#1111111#);
OAR1.Add10 := UInt2 (Own_Address / 2 ** 8);
end case;
Port.OAR1 := OAR1;
end Configure;
---------------
-- Set_State --
---------------
procedure Set_State (Port : in out I2C_Port; State : I2C_State) is
begin
Port.CR1.PE := (if State = Enabled then 1 else 0);
end Set_State;
------------------
-- Port_Enabled --
------------------
function Port_Enabled (Port : I2C_Port) return Boolean is
begin
return Port.CR1.PE = 1;
end Port_Enabled;
--------------------
-- Generate_Start --
--------------------
procedure Generate_Start (Port : in out I2C_Port; State : I2C_State) is
begin
Port.CR1.START := (if State = Enabled then 1 else 0);
end Generate_Start;
-------------------
-- Generate_Stop --
-------------------
procedure Generate_Stop (Port : in out I2C_Port; State : I2C_State) is
begin
Port.CR1.STOP := (if State = Enabled then 1 else 0);
end Generate_Stop;
--------------------
-- Send_7Bit_Addr --
--------------------
procedure Send_7Bit_Address
(Port : in out I2C_Port;
Address : Byte;
Direction : I2C_Direction)
is
Destination : Byte;
begin
if Direction = Receiver then
Destination := Address or 2#1#;
else
Destination := Address and (not 2#1#);
end if;
Port.DR.DR := Destination;
end Send_7Bit_Address;
--------------
-- Get_Flag --
--------------
function Status (Port : I2C_Port; Flag : I2C_Status_Flag) return Boolean is
begin
case Flag is
when Start_Bit =>
return Port.SR1.SB = 1;
when Address_Sent =>
return Port.SR1.ADDR = 1;
when Byte_Transfer_Finished =>
return Port.SR1.BTF = 1;
when Address_Sent_10bit =>
return Port.SR1.ADD10 = 1;
when Stop_Detection =>
return Port.SR1.STOPF = 1;
when Rx_Data_Register_Not_Empty =>
return Port.SR1.RxNE = 1;
when Tx_Data_Register_Empty =>
return Port.SR1.TxE = 1;
when Bus_Error =>
return Port.SR1.BERR = 1;
when Arbitration_Lost =>
return Port.SR1.ARLO = 1;
when Ack_Failure =>
return Port.SR1.AF = 1;
when UnderOverrun =>
return Port.SR1.OVR = 1;
when Packet_Error =>
return Port.SR1.PECERR = 1;
when Timeout =>
return Port.SR1.TIMEOUT = 1;
when SMB_Alert =>
return Port.SR1.SMBALERT = 1;
when Master_Slave_Mode =>
return Port.SR2.MSL = 1;
when Busy =>
return Port.SR2.BUSY = 1;
when Transmitter_Receiver_Mode =>
return Port.SR2.TRA = 1;
when General_Call =>
return Port.SR2.GENCALL = 1;
when SMB_Default =>
return Port.SR2.SMBDEFAULT = 1;
when SMB_Host =>
return Port.SR2.SMBHOST = 1;
when Dual_Flag =>
return Port.SR2.DUALF = 1;
end case;
end Status;
----------------
-- Clear_Flag --
----------------
procedure Clear_Status
(Port : in out I2C_Port;
Target : Clearable_I2C_Status_Flag)
is
Unref : Bit with Unreferenced;
begin
case Target is
when Bus_Error =>
Port.SR1.BERR := 0;
when Arbitration_Lost =>
Port.SR1.ARLO := 0;
when Ack_Failure =>
Port.SR1.AF := 0;
when UnderOverrun =>
Port.SR1.OVR := 0;
when Packet_Error =>
Port.SR1.PECERR := 0;
when Timeout =>
Port.SR1.TIMEOUT := 0;
when SMB_Alert =>
Port.SR1.SMBALERT := 0;
end case;
end Clear_Status;
-------------------------------
-- Clear_Address_Sent_Status --
-------------------------------
procedure Clear_Address_Sent_Status (Port : in out I2C_Port)
is
Unref : Bit with Volatile, Unreferenced;
begin
-- To clear the ADDR flag we have to read SR2 after reading SR1.
-- However, per the RM, section 27.6.7, page 850, we should only read
-- SR2 if the Address_Sent flag is set in SR1, or if the Stop_Detection
-- flag is cleared, because the Address_Sent flag could be set in
-- the middle of reading SR1 and SR2 but will be cleared by the
-- read sequence nonetheless.
if Status (Port, Start_Bit) or else Status (Port, Stop_Detection) then
Unref := Port.SR2.MSL;
end if;
end Clear_Address_Sent_Status;
---------------------------------
-- Clear_Stop_Detection_Status --
---------------------------------
procedure Clear_Stop_Detection_Status (Port : in out I2C_Port) is
Unref : Bit with Volatile, Unreferenced;
begin
Unref := Port.SR1.STOPF;
Port.CR1.PE := 1;
end Clear_Stop_Detection_Status;
-------------------
-- Wait_For_Flag --
-------------------
procedure Wait_For_State
(Port : I2C_Port;
Queried : I2C_Status_Flag;
State : I2C_State;
Time_Out : Natural := 1_000)
is
Expected : constant Boolean := State = Enabled;
Deadline : constant Time := Clock + Milliseconds (Time_Out);
begin
while Status (Port, Queried) /= Expected loop
if Clock >= Deadline then
raise I2C_Timeout;
end if;
end loop;
end Wait_For_State;
---------------
-- Send_Data --
---------------
procedure Send_Data (Port : in out I2C_Port; Data : Byte) is
begin
Port.DR.DR := Data;
end Send_Data;
---------------
-- Read_Data --
---------------
function Read_Data (Port : I2C_Port) return Byte is
begin
return Port.DR.DR;
end Read_Data;
--------------------
-- Set_Ack_Config --
--------------------
procedure Set_Ack_Config (Port : in out I2C_Port; State : I2C_State) is
begin
Port.CR1.ACK := (if State = Enabled then 1 else 0);
end Set_Ack_Config;
---------------------
-- Set_Nack_Config --
---------------------
procedure Set_Nack_Config
(Port : in out I2C_Port;
Pos : I2C_Nack_Position)
is
begin
Port.CR1.POS := (if Pos = Next then 1 else 0);
end Set_Nack_Config;
-----------
-- Start --
-----------
procedure Start
(Port : in out I2C_Port;
Address : Byte;
Direction : I2C_Direction)
is
begin
Generate_Start (Port, Enabled);
Wait_For_State (Port, Start_Bit, Enabled);
Set_Ack_Config (Port, Enabled);
Send_7Bit_Address (Port, Address, Direction);
while not Status (Port, Address_Sent) loop
if Status (Port, Ack_Failure) then
raise Program_Error;
end if;
end loop;
Clear_Address_Sent_Status (Port);
end Start;
--------------
-- Read_Ack --
--------------
function Read_Ack (Port : in out I2C_Port) return Byte is
begin
Set_Ack_Config (Port, Enabled);
Wait_For_State (Port, Rx_Data_Register_Not_Empty, Enabled);
return Read_Data (Port);
end Read_Ack;
---------------
-- Read_Nack --
---------------
function Read_Nack (Port : in out I2C_Port) return Byte is
begin
Set_Ack_Config (Port, Disabled);
Generate_Stop (Port, Enabled);
Wait_For_State (Port, Rx_Data_Register_Not_Empty, Enabled);
return Read_Data (Port);
end Read_Nack;
-----------
-- Write --
-----------
procedure Write (Port : in out I2C_Port; Data : Byte) is
begin
Wait_For_State (Port, Tx_Data_Register_Empty, Enabled);
Send_Data (Port, Data);
while
not Status (Port, Tx_Data_Register_Empty) or else
not Status (Port, Byte_Transfer_Finished)
loop
null;
end loop;
end Write;
----------
-- Stop --
----------
procedure Stop (Port : in out I2C_Port) is
begin
Generate_Stop (Port, Enabled);
end Stop;
----------------------
-- Enable_Interrupt --
----------------------
procedure Enable_Interrupt
(Port : in out I2C_Port;
Source : I2C_Interrupt)
is
begin
case Source is
when Error_Interrupt =>
Port.CR2.ITERREN := 1;
when Event_Interrupt =>
Port.CR2.ITEVTEN := 1;
when Buffer_Interrupt =>
Port.CR2.ITBUFEN := 1;
end case;
end Enable_Interrupt;
-----------------------
-- Disable_Interrupt --
-----------------------
-----------------------
-- Disable_Interrupt --
-----------------------
procedure Disable_Interrupt
(Port : in out I2C_Port;
Source : I2C_Interrupt)
is
begin
case Source is
when Error_Interrupt =>
Port.CR2.ITERREN := 0;
when Event_Interrupt =>
Port.CR2.ITEVTEN := 0;
when Buffer_Interrupt =>
Port.CR2.ITBUFEN := 0;
end case;
end Disable_Interrupt;
-------------
-- Enabled --
-------------
function Enabled
(Port : in out I2C_Port;
Source : I2C_Interrupt)
return Boolean
is
begin
case Source is
when Error_Interrupt =>
return Port.CR2.ITERREN = 1;
when Event_Interrupt =>
return Port.CR2.ITEVTEN = 1;
when Buffer_Interrupt =>
return Port.CR2.ITBUFEN = 1;
end case;
end Enabled;
end STM32.I2C;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_i2c.c --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief I2C HAL module driver. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
with Ada.Real_Time; use Ada.Real_Time;
with STM32.RCC; use STM32.RCC;
with STM32_SVD.I2C; use STM32_SVD.I2C;
package body STM32.I2C is
---------------
-- Configure --
---------------
procedure Configure
(Port : in out I2C_Port;
Clock_Speed : Word;
Mode : I2C_Device_Mode;
Duty_Cycle : I2C_Duty_Cycle;
Own_Address : Half_Word;
Ack : I2C_Acknowledgement;
Ack_Address : I2C_Acknowledge_Address)
is
CR1 : CR1_Register;
CCR : CCR_Register;
OAR1 : OAR1_Register;
PCLK1 : constant Word := System_Clock_Frequencies.PCLK1;
Freq_Range : constant Half_Word := Half_Word (PCLK1 / 1_000_000);
begin
if Freq_Range < 2 or else Freq_Range > 42 then
raise Program_Error with
"PCLK1 too high or too low: expected 2-42 MHz, current" &
Freq_Range'Img & " MHz";
end if;
-- Load CR2 and clear FREQ
Port.CR2 :=
(LAST => 0,
DMAEN => 0,
ITBUFEN => 0,
ITEVTEN => 0,
ITERREN => 0,
FREQ => UInt6 (Freq_Range),
others => <>);
Set_State (Port, Disabled);
if Clock_Speed <= 100_000 then
-- Mode selection to Standard Mode
CCR.F_S := 0;
CCR.CCR := UInt12 (PCLK1 / (Clock_Speed * 2));
if CCR.CCR < 4 then
CCR.CCR := 4;
end if;
Port.TRISE.TRISE := UInt6 (Freq_Range + 1);
else
-- Fast mode
CCR.F_S := 1;
if Duty_Cycle = DutyCycle_2 then
CCR.CCR := UInt12 (Pclk1 / (Clock_Speed * 3));
else
CCR.CCR := UInt12 (Pclk1 / (Clock_Speed * 25));
CCR.DUTY := 1;
end if;
if CCR.CCR = 0 then
CCR.CCR := 1;
end if;
CCR.CCR := CCR.CCR or 16#80#;
Port.TRISE.TRISE := UInt6 ((Word (Freq_Range) * 300) / 1000 + 1);
end if;
Port.CCR := CCR;
Set_State (Port, Enabled);
CR1 := Port.CR1;
case Mode is
when I2C_Mode =>
CR1.SMBUS := 0;
CR1.SMBTYPE := 0;
when SMBusDevice_Mode =>
CR1.SMBUS := 1;
CR1.SMBTYPE := 0;
when SMBusHost_Mode =>
CR1.SMBUS := 1;
CR1.SMBTYPE := 1;
end case;
CR1.ACK := I2C_Acknowledgement'Enum_Rep (Ack);
Port.CR1 := CR1;
OAR1.ADDMODE := (if Ack_Address = AcknowledgedAddress_10bit
then 1 else 0);
case Ack_Address is
when AcknowledgedAddress_7bit =>
OAR1.ADD0 := 0;
OAR1.ADD7 := UInt7 (Own_Address / 2);
OAR1.ADD10 := 0;
when AcknowledgedAddress_10bit =>
OAR1.Add0 := Bit (Own_Address and 2#1#);
OAR1.ADD7 := UInt7 ((Own_Address / 2) and 2#1111111#);
OAR1.Add10 := UInt2 (Own_Address / 2 ** 8);
end case;
Port.OAR1 := OAR1;
end Configure;
---------------
-- Set_State --
---------------
procedure Set_State (Port : in out I2C_Port; State : I2C_State) is
begin
Port.CR1.PE := (if State = Enabled then 1 else 0);
end Set_State;
------------------
-- Port_Enabled --
------------------
function Port_Enabled (Port : I2C_Port) return Boolean is
begin
return Port.CR1.PE = 1;
end Port_Enabled;
--------------------
-- Generate_Start --
--------------------
procedure Generate_Start (Port : in out I2C_Port; State : I2C_State) is
begin
Port.CR1.START := (if State = Enabled then 1 else 0);
end Generate_Start;
-------------------
-- Generate_Stop --
-------------------
procedure Generate_Stop (Port : in out I2C_Port; State : I2C_State) is
begin
Port.CR1.STOP := (if State = Enabled then 1 else 0);
end Generate_Stop;
--------------------
-- Send_7Bit_Addr --
--------------------
procedure Send_7Bit_Address
(Port : in out I2C_Port;
Address : Byte;
Direction : I2C_Direction)
is
Destination : Byte;
begin
if Direction = Receiver then
Destination := Address or 2#1#;
else
Destination := Address and (not 2#1#);
end if;
Port.DR.DR := Destination;
end Send_7Bit_Address;
--------------
-- Get_Flag --
--------------
function Status (Port : I2C_Port; Flag : I2C_Status_Flag) return Boolean is
begin
case Flag is
when Start_Bit =>
return Port.SR1.SB = 1;
when Address_Sent =>
return Port.SR1.ADDR = 1;
when Byte_Transfer_Finished =>
return Port.SR1.BTF = 1;
when Address_Sent_10bit =>
return Port.SR1.ADD10 = 1;
when Stop_Detection =>
return Port.SR1.STOPF = 1;
when Rx_Data_Register_Not_Empty =>
return Port.SR1.RxNE = 1;
when Tx_Data_Register_Empty =>
return Port.SR1.TxE = 1;
when Bus_Error =>
return Port.SR1.BERR = 1;
when Arbitration_Lost =>
return Port.SR1.ARLO = 1;
when Ack_Failure =>
return Port.SR1.AF = 1;
when UnderOverrun =>
return Port.SR1.OVR = 1;
when Packet_Error =>
return Port.SR1.PECERR = 1;
when Timeout =>
return Port.SR1.TIMEOUT = 1;
when SMB_Alert =>
return Port.SR1.SMBALERT = 1;
when Master_Slave_Mode =>
return Port.SR2.MSL = 1;
when Busy =>
return Port.SR2.BUSY = 1;
when Transmitter_Receiver_Mode =>
return Port.SR2.TRA = 1;
when General_Call =>
return Port.SR2.GENCALL = 1;
when SMB_Default =>
return Port.SR2.SMBDEFAULT = 1;
when SMB_Host =>
return Port.SR2.SMBHOST = 1;
when Dual_Flag =>
return Port.SR2.DUALF = 1;
end case;
end Status;
----------------
-- Clear_Flag --
----------------
procedure Clear_Status
(Port : in out I2C_Port;
Target : Clearable_I2C_Status_Flag)
is
Unref : Bit with Unreferenced;
begin
case Target is
when Bus_Error =>
Port.SR1.BERR := 0;
when Arbitration_Lost =>
Port.SR1.ARLO := 0;
when Ack_Failure =>
Port.SR1.AF := 0;
when UnderOverrun =>
Port.SR1.OVR := 0;
when Packet_Error =>
Port.SR1.PECERR := 0;
when Timeout =>
Port.SR1.TIMEOUT := 0;
when SMB_Alert =>
Port.SR1.SMBALERT := 0;
end case;
end Clear_Status;
-------------------------------
-- Clear_Address_Sent_Status --
-------------------------------
procedure Clear_Address_Sent_Status (Port : in out I2C_Port)
is
Unref : Bit with Volatile, Unreferenced;
begin
-- ADDR is cleared after reading both SR1 and SR2
Unref := Port.SR1.ADDR;
Unref := Port.SR2.MSL;
end Clear_Address_Sent_Status;
---------------------------------
-- Clear_Stop_Detection_Status --
---------------------------------
procedure Clear_Stop_Detection_Status (Port : in out I2C_Port) is
Unref : Bit with Volatile, Unreferenced;
begin
Unref := Port.SR1.STOPF;
Port.CR1.PE := 1;
end Clear_Stop_Detection_Status;
-------------------
-- Wait_For_Flag --
-------------------
procedure Wait_For_State
(Port : I2C_Port;
Queried : I2C_Status_Flag;
State : I2C_State;
Time_Out : Natural := 1_000)
is
Expected : constant Boolean := State = Enabled;
Deadline : constant Time := Clock + Milliseconds (Time_Out);
begin
while Status (Port, Queried) /= Expected loop
if Clock >= Deadline then
raise I2C_Timeout;
end if;
end loop;
end Wait_For_State;
---------------
-- Send_Data --
---------------
procedure Send_Data (Port : in out I2C_Port; Data : Byte) is
begin
Port.DR.DR := Data;
end Send_Data;
---------------
-- Read_Data --
---------------
function Read_Data (Port : I2C_Port) return Byte is
begin
return Port.DR.DR;
end Read_Data;
--------------------
-- Set_Ack_Config --
--------------------
procedure Set_Ack_Config (Port : in out I2C_Port; State : I2C_State) is
begin
Port.CR1.ACK := (if State = Enabled then 1 else 0);
end Set_Ack_Config;
---------------------
-- Set_Nack_Config --
---------------------
procedure Set_Nack_Config
(Port : in out I2C_Port;
Pos : I2C_Nack_Position)
is
begin
Port.CR1.POS := (if Pos = Next then 1 else 0);
end Set_Nack_Config;
-----------
-- Start --
-----------
procedure Start
(Port : in out I2C_Port;
Address : Byte;
Direction : I2C_Direction)
is
begin
Generate_Start (Port, Enabled);
Wait_For_State (Port, Start_Bit, Enabled);
Set_Ack_Config (Port, Enabled);
Send_7Bit_Address (Port, Address, Direction);
while not Status (Port, Address_Sent) loop
if Status (Port, Ack_Failure) then
raise Program_Error;
end if;
end loop;
Clear_Address_Sent_Status (Port);
end Start;
--------------
-- Read_Ack --
--------------
function Read_Ack (Port : in out I2C_Port) return Byte is
begin
Set_Ack_Config (Port, Enabled);
Wait_For_State (Port, Rx_Data_Register_Not_Empty, Enabled);
return Read_Data (Port);
end Read_Ack;
---------------
-- Read_Nack --
---------------
function Read_Nack (Port : in out I2C_Port) return Byte is
begin
Set_Ack_Config (Port, Disabled);
Generate_Stop (Port, Enabled);
Wait_For_State (Port, Rx_Data_Register_Not_Empty, Enabled);
return Read_Data (Port);
end Read_Nack;
-----------
-- Write --
-----------
procedure Write (Port : in out I2C_Port; Data : Byte) is
begin
Wait_For_State (Port, Tx_Data_Register_Empty, Enabled);
Send_Data (Port, Data);
while
not Status (Port, Tx_Data_Register_Empty) or else
not Status (Port, Byte_Transfer_Finished)
loop
null;
end loop;
end Write;
----------
-- Stop --
----------
procedure Stop (Port : in out I2C_Port) is
begin
Generate_Stop (Port, Enabled);
end Stop;
----------------------
-- Enable_Interrupt --
----------------------
procedure Enable_Interrupt
(Port : in out I2C_Port;
Source : I2C_Interrupt)
is
begin
case Source is
when Error_Interrupt =>
Port.CR2.ITERREN := 1;
when Event_Interrupt =>
Port.CR2.ITEVTEN := 1;
when Buffer_Interrupt =>
Port.CR2.ITBUFEN := 1;
end case;
end Enable_Interrupt;
-----------------------
-- Disable_Interrupt --
-----------------------
-----------------------
-- Disable_Interrupt --
-----------------------
procedure Disable_Interrupt
(Port : in out I2C_Port;
Source : I2C_Interrupt)
is
begin
case Source is
when Error_Interrupt =>
Port.CR2.ITERREN := 0;
when Event_Interrupt =>
Port.CR2.ITEVTEN := 0;
when Buffer_Interrupt =>
Port.CR2.ITBUFEN := 0;
end case;
end Disable_Interrupt;
-------------
-- Enabled --
-------------
function Enabled
(Port : in out I2C_Port;
Source : I2C_Interrupt)
return Boolean
is
begin
case Source is
when Error_Interrupt =>
return Port.CR2.ITERREN = 1;
when Event_Interrupt =>
return Port.CR2.ITEVTEN = 1;
when Buffer_Interrupt =>
return Port.CR2.ITBUFEN = 1;
end case;
end Enabled;
end STM32.I2C;
|
Fix the START status clearing of the I2C peripheral.
|
Fix the START status clearing of the I2C peripheral.
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
|
1d9965c16976a9d7d81ae81c3064e879b1cffeca
|
regtests/wiki-filters-html-tests.adb
|
regtests/wiki-filters-html-tests.adb
|
-----------------------------------------------------------------------
-- wiki-filters-html-tests -- Unit tests for wiki HTML filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Assertions;
with Util.Strings;
with Util.Log.Loggers;
package body Wiki.Filters.Html.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Wiki.Filters");
package Caller is new Util.Test_Caller (Test, "Wikis.Filters.Html");
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Html_Tag_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Wiki.Filters.Html.Find_Tag",
Test_Find_Tag'Access);
end Add_Tests;
-- Test Find_Tag operation.
procedure Test_Find_Tag (T : in out Test) is
begin
for I in Html_Tag_Type'Range loop
declare
Name : constant String := Html_Tag_Type'Image (I);
Wname : constant Wide_Wide_String := Html_Tag_Type'Wide_Wide_Image (I);
Pos : constant Natural := Util.Strings.Index (Name, '_');
Tag : constant Html_Tag_Type := Find_Tag (WName (WName'First .. Pos - 1));
begin
Log.Info ("Checking tag {0}", Name);
Assert_Equals (T, I, Tag, "Find_Tag failed");
end;
end loop;
end Test_Find_Tag;
end Wiki.Filters.Html.Tests;
|
-----------------------------------------------------------------------
-- wiki-filters-html-tests -- Unit tests for wiki HTML filters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Assertions;
with Util.Strings;
with Util.Log.Loggers;
package body Wiki.Filters.Html.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Wiki.Filters");
package Caller is new Util.Test_Caller (Test, "Wikis.Filters.Html");
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Html_Tag_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Wiki.Filters.Html.Find_Tag",
Test_Find_Tag'Access);
end Add_Tests;
-- ------------------------------
-- Test Find_Tag operation.
-- ------------------------------
procedure Test_Find_Tag (T : in out Test) is
begin
for I in Html_Tag_Type'Range loop
declare
Name : constant String := Html_Tag_Type'Image (I);
Wname : constant Wide_Wide_String := Html_Tag_Type'Wide_Wide_Image (I);
Pos : constant Natural := Util.Strings.Index (Name, '_');
Tag : constant Html_Tag_Type := Find_Tag (Wname (Wname'First .. Pos - 1));
begin
Log.Info ("Checking tag {0}", Name);
Assert_Equals (T, I, Tag, "Find_Tag failed");
Assert_Equals (T, UNKNOWN_TAG, Find_Tag (Wname (Wname'First .. Pos - 1) & "x"),
"Find_Tag must return UNKNOWN_TAG");
end;
end loop;
end Test_Find_Tag;
end Wiki.Filters.Html.Tests;
|
Add some tests for Find_Tag operation
|
Add some tests for Find_Tag operation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
e42e50abb0d3e1df68bda86a2a84cc890d4925f1
|
src/sys/processes/util-processes.ads
|
src/sys/processes/util-processes.ads
|
-----------------------------------------------------------------------
-- util-processes -- Process creation and control
-- Copyright (C) 2011, 2012, 2016, 2018, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams;
with Util.Systems.Types;
with Util.Systems.Os;
with Util.Strings.Vectors;
with Ada.Finalization;
with Ada.Strings.Unbounded;
package Util.Processes is
Invalid_State : exception;
Process_Error : exception;
-- The optional process pipes:
-- <dl>
-- <dt>NONE</dt>
-- <dd>the process will inherit the standard input, output and error.</dd>
-- <dt>READ</dt>
-- <dd>a pipe is created to read the process standard output.</dd>
-- <dt>READ_ERROR</dt>
-- <dd>a pipe is created to read the process standard error. The output and input are
-- inherited.</dd>
-- <dt>READ_ALL</dt>
-- <dd>similar to READ the same pipe is used for the process standard error.</dd>
-- <dt>WRITE</dt>
-- <dd>a pipe is created to write on the process standard input.</dd>
-- <dt>READ_WRITE</dt>
-- <dd>Combines the <b>READ</b> and <b>WRITE</b> modes.</dd>
-- <dt>READ_WRITE_ALL</dt>
-- <dd>Combines the <b>READ_ALL</b> and <b>WRITE</b> modes.</dd>
-- </dl>
type Pipe_Mode is (NONE, READ, READ_ERROR, READ_ALL, WRITE, READ_WRITE, READ_WRITE_ALL);
subtype String_Access is Ada.Strings.Unbounded.String_Access;
subtype File_Type is Util.Systems.Types.File_Type;
type Argument_List is array (Positive range <>) of String_Access;
subtype Process_Identifier is Util.Systems.Os.Process_Identifier;
use type Util.Systems.Os.Process_Identifier;
-- ------------------------------
-- Process
-- ------------------------------
type Process is limited private;
-- 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 (Proc : in out Process;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Proc : in out Process;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Proc : in out Process;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Proc : in out Process;
Path : in String);
-- 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 (Proc : in out Process;
Shell : in String);
-- Closes the given file descriptor in the child process before executing the command.
procedure Add_Close (Proc : in out Process;
Fd : in File_Type);
-- Append the argument to the current process argument list.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Append_Argument (Proc : in out Process;
Arg : in String);
-- Set the environment variable to be used by the process before its creation.
procedure Set_Environment (Proc : in out Process;
Name : in String;
Value : in String);
procedure Set_Environment (Proc : in out Process;
Iterate : not null access
procedure
(Process : not null access procedure
(Name : in String;
Value : in String)));
-- Spawn a new process with the given command and its arguments. The standard input, output
-- and error streams are either redirected to a file or to a stream object.
procedure Spawn (Proc : in out Process;
Command : in String;
Arguments : in Argument_List;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Arguments : in Util.Strings.Vectors.Vector;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Command : in String;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Mode : in Pipe_Mode := NONE);
-- Wait for the process to terminate.
procedure Wait (Proc : in out Process);
-- 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 (Proc : in out Process;
Signal : in Positive := 15);
-- Get the process exit status.
function Get_Exit_Status (Proc : in Process) return Integer;
-- Get the process identifier.
function Get_Pid (Proc : in Process) return Process_Identifier;
-- Returns True if the process is running.
function Is_Running (Proc : in Process) return Boolean;
-- Get the process input stream allowing to write on the process standard input.
function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access;
-- Get the process output stream allowing to read the process standard output.
function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access;
-- Get the process error stream allowing to read the process standard output.
function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access;
private
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
-- The <b>System_Process</b> interface is specific to the system. On Unix, it holds the
-- process identifier. On Windows, more information is necessary, including the process
-- and thread handles. It's a little bit overkill to setup an interface for this but
-- it looks cleaner than having specific system fields here.
type System_Process is limited interface;
type System_Process_Access is access all System_Process'Class;
type Process is new Ada.Finalization.Limited_Controlled with record
Pid : Process_Identifier := -1;
Sys : System_Process_Access := null;
Exit_Value : Integer := -1;
Dir : Ada.Strings.Unbounded.Unbounded_String;
In_File : Ada.Strings.Unbounded.Unbounded_String;
Out_File : Ada.Strings.Unbounded.Unbounded_String;
Err_File : Ada.Strings.Unbounded.Unbounded_String;
Shell : Ada.Strings.Unbounded.Unbounded_String;
Out_Append : Boolean := False;
Err_Append : Boolean := False;
Output : Util.Streams.Input_Stream_Access := null;
Input : Util.Streams.Output_Stream_Access := null;
Error : Util.Streams.Input_Stream_Access := null;
To_Close : File_Type_Array_Access;
end record;
-- Initialize the process instance.
overriding
procedure Initialize (Proc : in out Process);
-- Deletes the process instance.
overriding
procedure Finalize (Proc : in out Process);
-- Wait for the process to exit.
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is abstract;
-- 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 (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is abstract;
-- Spawn a new process.
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is abstract;
-- Clear the program arguments.
procedure Clear_Arguments (Sys : in out System_Process) is abstract;
-- Append the argument to the process argument list.
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is abstract;
-- Set the environment variable to be used by the process before its creation.
procedure Set_Environment (Sys : in out System_Process;
Name : in String;
Value : in String) is abstract;
-- Set the process input, output and error streams to redirect and use specified files.
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;
To_Close : in File_Type_Array_Access) is abstract;
-- Deletes the storage held by the system process.
procedure Finalize (Sys : in out System_Process) is abstract;
end Util.Processes;
|
-----------------------------------------------------------------------
-- util-processes -- Process creation and control
-- Copyright (C) 2011, 2012, 2016, 2018, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams;
with Util.Systems.Types;
with Util.Systems.Os;
with Util.Strings.Vectors;
with Ada.Finalization;
with Ada.Strings.Unbounded;
package Util.Processes is
Invalid_State : exception;
Process_Error : exception;
-- The optional process pipes:
-- <dl>
-- <dt>NONE</dt>
-- <dd>the process will inherit the standard input, output and error.</dd>
-- <dt>READ</dt>
-- <dd>a pipe is created to read the process standard output.</dd>
-- <dt>READ_ERROR</dt>
-- <dd>a pipe is created to read the process standard error. The output and input are
-- inherited.</dd>
-- <dt>READ_ALL</dt>
-- <dd>similar to READ the same pipe is used for the process standard error.</dd>
-- <dt>WRITE</dt>
-- <dd>a pipe is created to write on the process standard input.</dd>
-- <dt>READ_WRITE</dt>
-- <dd>Combines the <b>READ</b> and <b>WRITE</b> modes.</dd>
-- <dt>READ_WRITE_ALL</dt>
-- <dd>Combines the <b>READ_ALL</b> and <b>WRITE</b> modes.</dd>
-- </dl>
type Pipe_Mode is (NONE, READ, READ_ERROR, READ_ALL, WRITE, READ_WRITE, READ_WRITE_ALL);
subtype String_Access is Ada.Strings.Unbounded.String_Access;
subtype File_Type is Util.Systems.Types.File_Type;
type Argument_List is array (Positive range <>) of String_Access;
subtype Process_Identifier is Util.Systems.Os.Process_Identifier;
use type Util.Systems.Os.Process_Identifier;
-- ------------------------------
-- Process
-- ------------------------------
type Process is limited private;
-- 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 (Proc : in out Process;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Proc : in out Process;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Proc : in out Process;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Proc : in out Process;
Path : in String);
-- 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 (Proc : in out Process;
Shell : in String);
-- Closes the given file descriptor in the child process before executing the command.
procedure Add_Close (Proc : in out Process;
Fd : in File_Type);
-- Append the argument to the current process argument list.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Append_Argument (Proc : in out Process;
Arg : in String);
-- Set the environment variable to be used by the process before its creation.
procedure Set_Environment (Proc : in out Process;
Name : in String;
Value : in String);
procedure Set_Environment (Proc : in out Process;
Iterate : not null access
procedure
(Process : not null access procedure
(Name : in String;
Value : in String)));
-- Import the default environment variables from the current process.
procedure Set_Default_Environment (Proc : in out Process);
-- Spawn a new process with the given command and its arguments. The standard input, output
-- and error streams are either redirected to a file or to a stream object.
procedure Spawn (Proc : in out Process;
Command : in String;
Arguments : in Argument_List;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Arguments : in Util.Strings.Vectors.Vector;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Command : in String;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Mode : in Pipe_Mode := NONE);
-- Wait for the process to terminate.
procedure Wait (Proc : in out Process);
-- 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 (Proc : in out Process;
Signal : in Positive := 15);
-- Get the process exit status.
function Get_Exit_Status (Proc : in Process) return Integer;
-- Get the process identifier.
function Get_Pid (Proc : in Process) return Process_Identifier;
-- Returns True if the process is running.
function Is_Running (Proc : in Process) return Boolean;
-- Get the process input stream allowing to write on the process standard input.
function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access;
-- Get the process output stream allowing to read the process standard output.
function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access;
-- Get the process error stream allowing to read the process standard output.
function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access;
private
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
-- The <b>System_Process</b> interface is specific to the system. On Unix, it holds the
-- process identifier. On Windows, more information is necessary, including the process
-- and thread handles. It's a little bit overkill to setup an interface for this but
-- it looks cleaner than having specific system fields here.
type System_Process is limited interface;
type System_Process_Access is access all System_Process'Class;
type Process is new Ada.Finalization.Limited_Controlled with record
Pid : Process_Identifier := -1;
Sys : System_Process_Access := null;
Exit_Value : Integer := -1;
Dir : Ada.Strings.Unbounded.Unbounded_String;
In_File : Ada.Strings.Unbounded.Unbounded_String;
Out_File : Ada.Strings.Unbounded.Unbounded_String;
Err_File : Ada.Strings.Unbounded.Unbounded_String;
Shell : Ada.Strings.Unbounded.Unbounded_String;
Out_Append : Boolean := False;
Err_Append : Boolean := False;
Output : Util.Streams.Input_Stream_Access := null;
Input : Util.Streams.Output_Stream_Access := null;
Error : Util.Streams.Input_Stream_Access := null;
To_Close : File_Type_Array_Access;
end record;
-- Initialize the process instance.
overriding
procedure Initialize (Proc : in out Process);
-- Deletes the process instance.
overriding
procedure Finalize (Proc : in out Process);
-- Wait for the process to exit.
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is abstract;
-- 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 (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is abstract;
-- Spawn a new process.
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is abstract;
-- Clear the program arguments.
procedure Clear_Arguments (Sys : in out System_Process) is abstract;
-- Append the argument to the process argument list.
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is abstract;
-- Set the environment variable to be used by the process before its creation.
procedure Set_Environment (Sys : in out System_Process;
Name : in String;
Value : in String) is abstract;
-- Set the process input, output and error streams to redirect and use specified files.
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;
To_Close : in File_Type_Array_Access) is abstract;
-- Deletes the storage held by the system process.
procedure Finalize (Sys : in out System_Process) is abstract;
end Util.Processes;
|
Declare the Set_Default_Environment procedure
|
Declare the Set_Default_Environment procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8f1ed4cf8f8b9e8566bcba1d88e1787a802ce265
|
mat/src/memory/mat-memory-targets.adb
|
mat/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
-- ------------------------------
-- Find from the memory map the memory slots whose address intersects
-- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if
-- it does not already contains the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- 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
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;
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;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
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
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;
if Addr /= 0 then
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;
-- ------------------------------
-- Find from the memory map the memory slots whose address intersects
-- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if
-- it does not already contains the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Into);
end Find;
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;
-- ------------------------------
-- 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;
-- ------------------------------
-- Find from the memory map the memory slots whose address intersects
-- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if
-- it does not already contains the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- 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
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;
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;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
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
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;
if Addr /= 0 then
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;
-- ------------------------------
-- Find from the memory map the memory slots whose address intersects
-- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if
-- it does not already contains the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Into);
end Find;
end Memory_Allocator;
end MAT.Memory.Targets;
|
Implement the Thread_Information procedures
|
Implement the Thread_Information procedures
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f8707a218d20769fdc9646f4cce1412d8e216542
|
src/sys/os-windows/util-systems-os.ads
|
src/sys/os-windows/util-systems-os.ads
|
-----------------------------------------------------------------------
-- util-system-os -- Windows system operations
-- Copyright (C) 2011, 2012, 2015, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Systems.Types;
-- The <b>Util.Systems.Os</b> package defines various types and operations which are specific
-- to the OS (Windows).
package Util.Systems.Os is
-- The directory separator.
Directory_Separator : constant Character := '\';
-- The path separator.
Path_Separator : constant Character := ';';
-- The line ending separator.
Line_Separator : constant String := "" & ASCII.CR & ASCII.LF;
-- Defines several windows specific types.
type BOOL is mod 8;
type WORD is new Interfaces.C.short;
type DWORD is new Interfaces.C.unsigned_long;
type PDWORD is access all DWORD;
for PDWORD'Size use Standard'Address_Size;
function Get_Last_Error return Integer;
pragma Import (Stdcall, Get_Last_Error, "GetLastError");
-- Some useful error codes (See Windows document "System Error Codes (0-499)").
ERROR_BROKEN_PIPE : constant Integer := 109;
-- ------------------------------
-- Handle
-- ------------------------------
-- The windows HANDLE is defined as a void* in the C API.
subtype HANDLE is Util.Systems.Types.HANDLE;
type PHANDLE is access all HANDLE;
for PHANDLE'Size use Standard'Address_Size;
function Wait_For_Single_Object (H : in HANDLE;
Time : in DWORD) return DWORD;
pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject");
type Security_Attributes is record
Length : DWORD;
Security_Descriptor : System.Address;
Inherit : Boolean;
end record;
type LPSECURITY_ATTRIBUTES is access all Security_Attributes;
for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size;
-- ------------------------------
-- File operations
-- ------------------------------
subtype File_Type is Util.Systems.Types.File_Type;
NO_FILE : constant File_Type := System.Null_Address;
STD_INPUT_HANDLE : constant DWORD := -10;
STD_OUTPUT_HANDLE : constant DWORD := -11;
STD_ERROR_HANDLE : constant DWORD := -12;
function Get_Std_Handle (Kind : in DWORD) return File_Type;
pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle");
function STDIN_FILENO return File_Type
is (Get_Std_Handle (STD_INPUT_HANDLE));
function Close_Handle (Fd : in File_Type) return BOOL;
pragma Import (Stdcall, Close_Handle, "CloseHandle");
function Duplicate_Handle (SourceProcessHandle : in HANDLE;
SourceHandle : in HANDLE;
TargetProcessHandle : in HANDLE;
TargetHandle : in PHANDLE;
DesiredAccess : in DWORD;
InheritHandle : in BOOL;
Options : in DWORD) return BOOL;
pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle");
function Read_File (Fd : in File_Type;
Buf : in System.Address;
Size : in DWORD;
Result : in PDWORD;
Overlap : in System.Address) return BOOL;
pragma Import (Stdcall, Read_File, "ReadFile");
function Write_File (Fd : in File_Type;
Buf : in System.Address;
Size : in DWORD;
Result : in PDWORD;
Overlap : in System.Address) return BOOL;
pragma Import (Stdcall, Write_File, "WriteFile");
function Create_Pipe (Read_Handle : in PHANDLE;
Write_Handle : in PHANDLE;
Attributes : in LPSECURITY_ATTRIBUTES;
Buf_Size : in DWORD) return BOOL;
pragma Import (Stdcall, Create_Pipe, "CreatePipe");
-- type Size_T is mod 2 ** Standard'Address_Size;
subtype LPWSTR is Interfaces.C.Strings.chars_ptr;
subtype PBYTE is Interfaces.C.Strings.chars_ptr;
subtype Ptr is Interfaces.C.Strings.chars_ptr;
subtype LPCTSTR is System.Address;
subtype LPTSTR is System.Address;
type CommandPtr is access all Interfaces.C.wchar_array;
NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr;
type Startup_Info is record
cb : DWORD := 0;
lpReserved : LPWSTR := NULL_STR;
lpDesktop : LPWSTR := NULL_STR;
lpTitle : LPWSTR := NULL_STR;
dwX : DWORD := 0;
dwY : DWORD := 0;
dwXsize : DWORD := 0;
dwYsize : DWORD := 0;
dwXCountChars : DWORD := 0;
dwYCountChars : DWORD := 0;
dwFillAttribute : DWORD := 0;
dwFlags : DWORD := 0;
wShowWindow : WORD := 0;
cbReserved2 : WORD := 0;
lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr;
hStdInput : HANDLE := System.Null_Address;
hStdOutput : HANDLE := System.Null_Address;
hStdError : HANDLE := System.Null_Address;
end record;
-- pragma Pack (Startup_Info);
type Startup_Info_Access is access all Startup_Info;
type PROCESS_INFORMATION is record
hProcess : HANDLE := NO_FILE;
hThread : HANDLE := NO_FILE;
dwProcessId : DWORD;
dwThreadId : DWORD;
end record;
type Process_Information_Access is access all PROCESS_INFORMATION;
function Get_Current_Process return HANDLE;
pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess");
function Get_Exit_Code_Process (Proc : in HANDLE;
Code : in PDWORD) return BOOL;
pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess");
function Create_Process (Name : in LPCTSTR;
Command : in System.Address;
Process_Attributes : in LPSECURITY_ATTRIBUTES;
Thread_Attributes : in LPSECURITY_ATTRIBUTES;
Inherit_Handlers : in Boolean;
Creation_Flags : in DWORD;
Environment : in LPTSTR;
Directory : in LPCTSTR;
Startup_Info : in Startup_Info_Access;
Process_Info : in Process_Information_Access) return Integer;
pragma Import (Stdcall, Create_Process, "CreateProcessW");
-- Terminate the windows process and all its threads.
function Terminate_Process (Proc : in HANDLE;
Code : in DWORD) return Integer;
pragma Import (Stdcall, Terminate_Process, "TerminateProcess");
function Sys_Stat (Path : in LPWSTR;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, "_stat64");
function Sys_Fstat (Fs : in File_Type;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Fstat, "_fstat64");
private
-- kernel32 is used on Windows32 as well as Windows64.
pragma Linker_Options ("-lkernel32");
end Util.Systems.Os;
|
-----------------------------------------------------------------------
-- util-system-os -- Windows system operations
-- Copyright (C) 2011, 2012, 2015, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Systems.Types;
-- The <b>Util.Systems.Os</b> package defines various types and operations which are specific
-- to the OS (Windows).
package Util.Systems.Os is
-- The directory separator.
Directory_Separator : constant Character := '\';
-- The path separator.
Path_Separator : constant Character := ';';
-- The line ending separator.
Line_Separator : constant String := "" & ASCII.CR & ASCII.LF;
-- Defines several windows specific types.
type BOOL is mod 8;
type WORD is new Interfaces.C.short;
type DWORD is new Interfaces.C.unsigned_long;
type PDWORD is access all DWORD;
for PDWORD'Size use Standard'Address_Size;
function Get_Last_Error return Integer;
pragma Import (Stdcall, Get_Last_Error, "GetLastError");
-- Some useful error codes (See Windows document "System Error Codes (0-499)").
ERROR_BROKEN_PIPE : constant Integer := 109;
-- ------------------------------
-- Handle
-- ------------------------------
-- The windows HANDLE is defined as a void* in the C API.
subtype HANDLE is Util.Systems.Types.HANDLE;
type PHANDLE is access all HANDLE;
for PHANDLE'Size use Standard'Address_Size;
function Wait_For_Single_Object (H : in HANDLE;
Time : in DWORD) return DWORD;
pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject");
type Security_Attributes is record
Length : DWORD;
Security_Descriptor : System.Address;
Inherit : Boolean;
end record;
type LPSECURITY_ATTRIBUTES is access all Security_Attributes;
for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size;
-- ------------------------------
-- File operations
-- ------------------------------
subtype File_Type is Util.Systems.Types.File_Type;
NO_FILE : constant File_Type := System.Null_Address;
STD_INPUT_HANDLE : constant DWORD := -10;
STD_OUTPUT_HANDLE : constant DWORD := -11;
STD_ERROR_HANDLE : constant DWORD := -12;
function Get_Std_Handle (Kind : in DWORD) return File_Type;
pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle");
function STDIN_FILENO return File_Type
is (Get_Std_Handle (STD_INPUT_HANDLE));
function Close_Handle (Fd : in File_Type) return BOOL;
pragma Import (Stdcall, Close_Handle, "CloseHandle");
function Duplicate_Handle (SourceProcessHandle : in HANDLE;
SourceHandle : in HANDLE;
TargetProcessHandle : in HANDLE;
TargetHandle : in PHANDLE;
DesiredAccess : in DWORD;
InheritHandle : in BOOL;
Options : in DWORD) return BOOL;
pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle");
function Read_File (Fd : in File_Type;
Buf : in System.Address;
Size : in DWORD;
Result : in PDWORD;
Overlap : in System.Address) return BOOL;
pragma Import (Stdcall, Read_File, "ReadFile");
function Write_File (Fd : in File_Type;
Buf : in System.Address;
Size : in DWORD;
Result : in PDWORD;
Overlap : in System.Address) return BOOL;
pragma Import (Stdcall, Write_File, "WriteFile");
function Create_Pipe (Read_Handle : in PHANDLE;
Write_Handle : in PHANDLE;
Attributes : in LPSECURITY_ATTRIBUTES;
Buf_Size : in DWORD) return BOOL;
pragma Import (Stdcall, Create_Pipe, "CreatePipe");
-- type Size_T is mod 2 ** Standard'Address_Size;
subtype LPWSTR is Interfaces.C.Strings.chars_ptr;
subtype LPCSTR is Interfaces.C.Strings.chars_ptr;
subtype PBYTE is Interfaces.C.Strings.chars_ptr;
subtype Ptr is Interfaces.C.Strings.chars_ptr;
subtype LPCTSTR is System.Address;
subtype LPTSTR is System.Address;
type CommandPtr is access all Interfaces.C.wchar_array;
NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr;
type Startup_Info is record
cb : DWORD := 0;
lpReserved : LPWSTR := NULL_STR;
lpDesktop : LPWSTR := NULL_STR;
lpTitle : LPWSTR := NULL_STR;
dwX : DWORD := 0;
dwY : DWORD := 0;
dwXsize : DWORD := 0;
dwYsize : DWORD := 0;
dwXCountChars : DWORD := 0;
dwYCountChars : DWORD := 0;
dwFillAttribute : DWORD := 0;
dwFlags : DWORD := 0;
wShowWindow : WORD := 0;
cbReserved2 : WORD := 0;
lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr;
hStdInput : HANDLE := System.Null_Address;
hStdOutput : HANDLE := System.Null_Address;
hStdError : HANDLE := System.Null_Address;
end record;
-- pragma Pack (Startup_Info);
type Startup_Info_Access is access all Startup_Info;
type PROCESS_INFORMATION is record
hProcess : HANDLE := NO_FILE;
hThread : HANDLE := NO_FILE;
dwProcessId : DWORD;
dwThreadId : DWORD;
end record;
type Process_Information_Access is access all PROCESS_INFORMATION;
function Get_Current_Process return HANDLE;
pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess");
function Get_Exit_Code_Process (Proc : in HANDLE;
Code : in PDWORD) return BOOL;
pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess");
function Create_Process (Name : in LPCTSTR;
Command : in System.Address;
Process_Attributes : in LPSECURITY_ATTRIBUTES;
Thread_Attributes : in LPSECURITY_ATTRIBUTES;
Inherit_Handlers : in Boolean;
Creation_Flags : in DWORD;
Environment : in LPTSTR;
Directory : in LPCTSTR;
Startup_Info : in Startup_Info_Access;
Process_Info : in Process_Information_Access) return Integer;
pragma Import (Stdcall, Create_Process, "CreateProcessW");
-- Terminate the windows process and all its threads.
function Terminate_Process (Proc : in HANDLE;
Code : in DWORD) return Integer;
pragma Import (Stdcall, Terminate_Process, "TerminateProcess");
function Sys_Stat (Path : in LPWSTR;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, "_stat64");
function Sys_Fstat (Fs : in File_Type;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Fstat, "_fstat64");
private
-- kernel32 is used on Windows32 as well as Windows64.
pragma Linker_Options ("-lkernel32");
end Util.Systems.Os;
|
Add LPCSTR type
|
Add LPCSTR type
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f34cf20c9ec90e3795312979235d88a56331a94b
|
regtests/util-mail-tests.adb
|
regtests/util-mail-tests.adb
|
-----------------------------------------------------------------------
-- util-mail-tests -- Unit tests for mail
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Mail.Tests is
package Caller is new Util.Test_Caller (Test, "Strings");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Mail.Parse_Address",
Test_Parse_Address'Access);
end Add_Tests;
procedure Test_Parse_Address (T : in out Test) is
use Ada.Strings.Unbounded;
procedure Check (Value : in String;
Name : in String;
Email : in String);
procedure Check (Value : in String;
Name : in String;
Email : in String) is
A : constant Email_Address := Parse_Address (Value);
begin
Util.Tests.Assert_Equals (T, Name, To_String (A.Name),
"Invalid name for: " & Value);
Util.Tests.Assert_Equals (T, Email, To_String (A.Address),
"Invalid email for: " & Value);
end Check;
begin
Check ("Luke Jedi <[email protected]> ", "Luke Jedi", "[email protected]");
Check (" <[email protected]> ", "Anakin", "[email protected]");
Check (" [email protected] ", "Vador", "[email protected]");
end Test_Parse_Address;
end Util.Mail.Tests;
|
-----------------------------------------------------------------------
-- util-mail-tests -- Unit tests for mail
-- Copyright (C) 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 Util.Test_Caller;
package body Util.Mail.Tests is
package Caller is new Util.Test_Caller (Test, "Mail");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Mail.Parse_Address",
Test_Parse_Address'Access);
end Add_Tests;
procedure Test_Parse_Address (T : in out Test) is
use Ada.Strings.Unbounded;
procedure Check (Value : in String;
Name : in String;
Email : in String;
First_Name : in String;
Last_Name : in String);
procedure Check (Value : in String;
Name : in String;
Email : in String;
First_Name : in String;
Last_Name : in String) is
A : constant Email_Address := Parse_Address (Value);
begin
Util.Tests.Assert_Equals (T, Name, To_String (A.Name),
"Invalid name for: " & Value);
Util.Tests.Assert_Equals (T, Email, To_String (A.Address),
"Invalid email for: " & Value);
Util.Tests.Assert_Equals (T, First_Name, Get_First_Name (A),
"Invalid first_name for: " & Value);
Util.Tests.Assert_Equals (T, Last_Name, Get_Last_Name (A),
"Invalid last_name for: " & Value);
end Check;
begin
Check ("Luke Jedi <[email protected]> ", "Luke Jedi", "[email protected]",
"Luke", "Jedi");
Check (" <[email protected]> ", "Anakin", "[email protected]",
"", "Anakin");
Check (" [email protected] ", "Vador", "[email protected]",
"", "Vador");
Check ("<[email protected]> ", "Ada.Lovelace", "[email protected]",
"Ada", "Lovelace");
end Test_Parse_Address;
end Util.Mail.Tests;
|
Add more test for Util.Mail package
|
Add more test for Util.Mail package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f3ff1a68fdc16add1f8d75beb64551192c6314e0
|
src/port_specification-transform.ads
|
src/port_specification-transform.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Definitions; use Definitions;
package Port_Specification.Transform is
-- Given:
-- variant
-- standard arch
-- opsys (operating system)
-- osrelease (string)
-- osmajor (string)
-- osversion (string)
-- and the current option settings (if variant is not "standard"):
-- Apply all the changes dictated by option helpers and the IGNORE calculation
procedure apply_directives
(specs : in out Portspecs;
variant : String;
arch_standard : supported_arch;
osmajor : String);
-- For non-standard variants, set options defaults as directed by VOPTS
-- For standard variant, set options default by OPT_ON values
procedure set_option_defaults
(specs : in out Portspecs;
variant : String;
opsys : supported_opsys;
arch_standard : supported_arch;
osrelease : String);
-- Update current value of given option
procedure define_option_setting (specs : in out Portspecs; option : String; value : Boolean);
procedure set_option_to_default_values (specs : in out Portspecs);
procedure set_outstanding_ignore
(specs : in out Portspecs;
variant : String;
opsys : supported_opsys;
arch_standard : supported_arch;
osrelease : String;
osmajor : String);
procedure shift_extra_patches
(specs : Portspecs;
extract_dir : String);
private
BUILD : constant String := "build";
BUILDRUN : constant String := "buildrun";
RUN : constant String := "run";
PYTHON27 : constant String := "python27:single:standard";
PYTHON38 : constant String := "python38:single:standard";
PYTHON39 : constant String := "python39:single:standard";
TCL85 : constant String := "tcl85:complete:standard";
TCL86 : constant String := "tcl86:complete:standard";
TK85 : constant String := "tk85:primary:standard";
TK86 : constant String := "tk86:primary:standard";
RUBY26 : constant String := "ruby26:primary:standard";
RUBY27 : constant String := "ruby27:primary:standard";
RUBY30 : constant String := "ruby30:primary:standard";
NINJA : constant String := "ninja:single:standard";
GNOMELIB : constant String := "glib:single:standard";
-- Returns true if all '0' .. '9', and also single '.' if it's not in first or last place.
function release_format (candidate : String) return Boolean;
-- Given X, X.Y or X.YY, returns X*100, X*100+Y or X*100+YY
function centurian_release (release : String) return Natural;
-- Implement less-than and greater-than OS Major comparision
function LTE (gen_release, spec_release : String) return Boolean;
function GTE (gen_release, spec_release : String) return Boolean;
procedure apply_cpe_module
(specs : in out Portspecs;
arch_standard : supported_arch;
osmajor : String);
procedure apply_scons_module (specs : in out Portspecs);
procedure apply_gmake_module (specs : in out Portspecs);
procedure apply_libtool_module (specs : in out Portspecs);
procedure apply_libiconv_module (specs : in out Portspecs);
procedure apply_info_presence (specs : in out Portspecs);
procedure apply_pkgconfig_module (specs : in out Portspecs);
procedure apply_gprbuild_module (specs : in out Portspecs);
procedure apply_ncurses_module (specs : in out Portspecs);
procedure apply_bdb_module (specs : in out Portspecs);
procedure apply_perl_module (specs : in out Portspecs);
procedure apply_bison_module (specs : in out Portspecs);
procedure apply_makeinfo_module (specs : in out Portspecs);
procedure apply_readline_module (specs : in out Portspecs);
procedure apply_ssl_module (specs : in out Portspecs);
procedure apply_python_module (specs : in out Portspecs);
procedure apply_lua_module (specs : in out Portspecs);
procedure apply_tcl_module (specs : in out Portspecs);
procedure apply_cargo_module (specs : in out Portspecs);
procedure apply_fonts_module (specs : in out Portspecs);
procedure apply_cmake_module (specs : in out Portspecs);
procedure apply_imake_module (specs : in out Portspecs);
procedure apply_meson_module (specs : in out Portspecs);
procedure apply_ninja_module (specs : in out Portspecs);
procedure apply_mysql_module (specs : in out Portspecs);
procedure apply_pgsql_module (specs : in out Portspecs);
procedure apply_sqlite_module (specs : in out Portspecs);
procedure apply_gtkdoc_module (specs : in out Portspecs);
procedure apply_display_module (specs : in out Portspecs);
procedure apply_schemas_module (specs : in out Portspecs);
procedure apply_firebird_module (specs : in out Portspecs);
procedure apply_autoconf_module (specs : in out Portspecs);
procedure apply_execinfo_module (specs : in out Portspecs);
procedure apply_cran_module (specs : in out Portspecs);
procedure apply_zlib_module (specs : in out Portspecs);
procedure apply_mesa_module (specs : in out Portspecs);
procedure apply_jpeg_module (specs : in out Portspecs);
procedure apply_ruby_module (specs : in out Portspecs);
procedure apply_php_module (specs : in out Portspecs);
procedure apply_png_module (specs : in out Portspecs);
procedure apply_gem_module (specs : in out Portspecs);
procedure apply_gcc_run_module (specs : in out Portspecs;
variant : String;
module : String;
gccsubpackage : String);
procedure add_exrun_cclibs (specs : in out Portspecs; variant : String);
procedure apply_desktop_utils_module (specs : in out Portspecs);
procedure apply_gnome_icons_module (specs : in out Portspecs);
procedure apply_mime_info_module (specs : in out Portspecs);
procedure apply_gettext_runtime_module (specs : in out Portspecs);
procedure apply_gettext_tools_module (specs : in out Portspecs);
procedure apply_extraction_deps (specs : in out Portspecs);
procedure apply_opsys_dependencies (specs : in out Portspecs);
procedure apply_gnome_components_dependencies (specs : in out Portspecs);
procedure apply_xorg_components_dependencies (specs : in out Portspecs);
procedure apply_sdl_components_dependencies (specs : in out Portspecs);
procedure apply_php_extension_dependencies (specs : in out Portspecs);
procedure apply_default_version_transformations (specs : in out Portspecs);
procedure apply_curly_bracket_conversions (specs : in out Portspecs);
procedure apply_cbc_string_crate (crate : in out string_crate.Vector);
procedure convert_exrun_versions (specs : in out Portspecs);
function argument_present (specs : Portspecs; module, argument : String) return Boolean;
function no_arguments_present (specs : Portspecs; module : String) return Boolean;
procedure add_build_depends (specs : in out Portspecs; dependency : String);
procedure add_buildrun_depends (specs : in out Portspecs; dependency : String);
procedure add_run_depends (specs : in out Portspecs; dependency : String);
procedure add_exrun_depends (specs : in out Portspecs; dependency, subpackage : String);
-- Convert e.g. python_default to py3X depending on current defaults.
-- True for all defaults as they get formed
function transform_defaults (dep, pyx, plx, lux, rbx : String) return String;
-- Returns XXXX:server:standard or XXXX:client:standard depending on server value
-- and mysql configuration setting
function determine_mysql_package (server : Boolean) return String;
-- Returns XXXX based on pgsql configuration setting
function determine_pgsql_namebase return String;
end Port_Specification.Transform;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Definitions; use Definitions;
package Port_Specification.Transform is
-- Given:
-- variant
-- standard arch
-- opsys (operating system)
-- osrelease (string)
-- osmajor (string)
-- osversion (string)
-- and the current option settings (if variant is not "standard"):
-- Apply all the changes dictated by option helpers and the IGNORE calculation
procedure apply_directives
(specs : in out Portspecs;
variant : String;
arch_standard : supported_arch;
osmajor : String);
-- For non-standard variants, set options defaults as directed by VOPTS
-- For standard variant, set options default by OPT_ON values
procedure set_option_defaults
(specs : in out Portspecs;
variant : String;
opsys : supported_opsys;
arch_standard : supported_arch;
osrelease : String);
-- Update current value of given option
procedure define_option_setting (specs : in out Portspecs; option : String; value : Boolean);
procedure set_option_to_default_values (specs : in out Portspecs);
procedure set_outstanding_ignore
(specs : in out Portspecs;
variant : String;
opsys : supported_opsys;
arch_standard : supported_arch;
osrelease : String;
osmajor : String);
procedure shift_extra_patches
(specs : Portspecs;
extract_dir : String);
private
BUILD : constant String := "build";
BUILDRUN : constant String := "buildrun";
RUN : constant String := "run";
PYTHON27 : constant String := "python27:single:standard";
PYTHON38 : constant String := "python38:single:standard";
PYTHON39 : constant String := "python39:single:standard";
TCL85 : constant String := "tcl85:complete:standard";
TCL86 : constant String := "tcl86:complete:standard";
TK85 : constant String := "tk85:primary:standard";
TK86 : constant String := "tk86:primary:standard";
RUBY26 : constant String := "ruby26:primary:standard";
RUBY27 : constant String := "ruby27:primary:standard";
RUBY30 : constant String := "ruby30:primary:standard";
NINJA : constant String := "ninja:single:standard";
GNOMELIB : constant String := "glib:primary:standard";
-- Returns true if all '0' .. '9', and also single '.' if it's not in first or last place.
function release_format (candidate : String) return Boolean;
-- Given X, X.Y or X.YY, returns X*100, X*100+Y or X*100+YY
function centurian_release (release : String) return Natural;
-- Implement less-than and greater-than OS Major comparision
function LTE (gen_release, spec_release : String) return Boolean;
function GTE (gen_release, spec_release : String) return Boolean;
procedure apply_cpe_module
(specs : in out Portspecs;
arch_standard : supported_arch;
osmajor : String);
procedure apply_scons_module (specs : in out Portspecs);
procedure apply_gmake_module (specs : in out Portspecs);
procedure apply_libtool_module (specs : in out Portspecs);
procedure apply_libiconv_module (specs : in out Portspecs);
procedure apply_info_presence (specs : in out Portspecs);
procedure apply_pkgconfig_module (specs : in out Portspecs);
procedure apply_gprbuild_module (specs : in out Portspecs);
procedure apply_ncurses_module (specs : in out Portspecs);
procedure apply_bdb_module (specs : in out Portspecs);
procedure apply_perl_module (specs : in out Portspecs);
procedure apply_bison_module (specs : in out Portspecs);
procedure apply_makeinfo_module (specs : in out Portspecs);
procedure apply_readline_module (specs : in out Portspecs);
procedure apply_ssl_module (specs : in out Portspecs);
procedure apply_python_module (specs : in out Portspecs);
procedure apply_lua_module (specs : in out Portspecs);
procedure apply_tcl_module (specs : in out Portspecs);
procedure apply_cargo_module (specs : in out Portspecs);
procedure apply_fonts_module (specs : in out Portspecs);
procedure apply_cmake_module (specs : in out Portspecs);
procedure apply_imake_module (specs : in out Portspecs);
procedure apply_meson_module (specs : in out Portspecs);
procedure apply_ninja_module (specs : in out Portspecs);
procedure apply_mysql_module (specs : in out Portspecs);
procedure apply_pgsql_module (specs : in out Portspecs);
procedure apply_sqlite_module (specs : in out Portspecs);
procedure apply_gtkdoc_module (specs : in out Portspecs);
procedure apply_display_module (specs : in out Portspecs);
procedure apply_schemas_module (specs : in out Portspecs);
procedure apply_firebird_module (specs : in out Portspecs);
procedure apply_autoconf_module (specs : in out Portspecs);
procedure apply_execinfo_module (specs : in out Portspecs);
procedure apply_cran_module (specs : in out Portspecs);
procedure apply_zlib_module (specs : in out Portspecs);
procedure apply_mesa_module (specs : in out Portspecs);
procedure apply_jpeg_module (specs : in out Portspecs);
procedure apply_ruby_module (specs : in out Portspecs);
procedure apply_php_module (specs : in out Portspecs);
procedure apply_png_module (specs : in out Portspecs);
procedure apply_gem_module (specs : in out Portspecs);
procedure apply_gcc_run_module (specs : in out Portspecs;
variant : String;
module : String;
gccsubpackage : String);
procedure add_exrun_cclibs (specs : in out Portspecs; variant : String);
procedure apply_desktop_utils_module (specs : in out Portspecs);
procedure apply_gnome_icons_module (specs : in out Portspecs);
procedure apply_mime_info_module (specs : in out Portspecs);
procedure apply_gettext_runtime_module (specs : in out Portspecs);
procedure apply_gettext_tools_module (specs : in out Portspecs);
procedure apply_extraction_deps (specs : in out Portspecs);
procedure apply_opsys_dependencies (specs : in out Portspecs);
procedure apply_gnome_components_dependencies (specs : in out Portspecs);
procedure apply_xorg_components_dependencies (specs : in out Portspecs);
procedure apply_sdl_components_dependencies (specs : in out Portspecs);
procedure apply_php_extension_dependencies (specs : in out Portspecs);
procedure apply_default_version_transformations (specs : in out Portspecs);
procedure apply_curly_bracket_conversions (specs : in out Portspecs);
procedure apply_cbc_string_crate (crate : in out string_crate.Vector);
procedure convert_exrun_versions (specs : in out Portspecs);
function argument_present (specs : Portspecs; module, argument : String) return Boolean;
function no_arguments_present (specs : Portspecs; module : String) return Boolean;
procedure add_build_depends (specs : in out Portspecs; dependency : String);
procedure add_buildrun_depends (specs : in out Portspecs; dependency : String);
procedure add_run_depends (specs : in out Portspecs; dependency : String);
procedure add_exrun_depends (specs : in out Portspecs; dependency, subpackage : String);
-- Convert e.g. python_default to py3X depending on current defaults.
-- True for all defaults as they get formed
function transform_defaults (dep, pyx, plx, lux, rbx : String) return String;
-- Returns XXXX:server:standard or XXXX:client:standard depending on server value
-- and mysql configuration setting
function determine_mysql_package (server : Boolean) return String;
-- Returns XXXX based on pgsql configuration setting
function determine_pgsql_namebase return String;
end Port_Specification.Transform;
|
adjust glib subpackages (#24)
|
adjust glib subpackages (#24)
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
f2f9ba8939d91d832fc7c266f44011146bd9f9c1
|
src/ado-drivers-dialects.adb
|
src/ado-drivers-dialects.adb
|
-----------------------------------------------------------------------
-- ADO Dialects -- Driver support for basic SQL Generation
-- Copyright (C) 2010, 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ADO.Drivers.Dialects is
-- --------------------
-- Get the quote character to escape an identifier.
-- --------------------
function Get_Identifier_Quote (D : in Dialect) return Character is
pragma Unreferenced (D);
begin
return '`';
end Get_Identifier_Quote;
-- ------------------------------
-- Append the item in the buffer escaping some characters if necessary.
-- The default implementation only escapes the single quote ' by doubling them.
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in String) is
pragma Unreferenced (D);
C : Character;
begin
Append (Buffer, ''');
for I in Item'Range loop
C := Item (I);
if C = ''' then
Append (Buffer, ''');
end if;
Append (Buffer, C);
end loop;
Append (Buffer, ''');
end Escape_Sql;
-- ------------------------------
-- Append the item in the buffer escaping some characters if necessary
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in ADO.Blob_Ref) is
pragma Unreferenced (D);
C : Ada.Streams.Stream_Element;
Blob : constant ADO.Blob_Access := Item.Value;
begin
Append (Buffer, ''');
for I in Blob.Data'Range loop
C := Blob.Data (I);
case C is
when Character'Pos (ASCII.NUL) =>
Append (Buffer, '\');
Append (Buffer, '0');
when Character'Pos (ASCII.CR) =>
Append (Buffer, '\');
Append (Buffer, 'r');
when Character'Pos (ASCII.LF) =>
Append (Buffer, '\');
Append (Buffer, 'n');
when Character'Pos ('\') | Character'Pos (''') | Character'Pos ('"') =>
Append (Buffer, '\');
Append (Buffer, Character'Val (C));
when others =>
Append (Buffer, Character'Val (C));
end case;
end loop;
Append (Buffer, ''');
end Escape_Sql;
end ADO.Drivers.Dialects;
|
-----------------------------------------------------------------------
-- ADO Dialects -- Driver support for basic SQL Generation
-- Copyright (C) 2010, 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ADO.Drivers.Dialects is
-- --------------------
-- Get the quote character to escape an identifier.
-- --------------------
function Get_Identifier_Quote (D : in Dialect) return Character is
pragma Unreferenced (D);
begin
return '`';
end Get_Identifier_Quote;
-- ------------------------------
-- Append the item in the buffer escaping some characters if necessary.
-- The default implementation only escapes the single quote ' by doubling them.
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in String) is
pragma Unreferenced (D);
C : Character;
begin
Append (Buffer, ''');
for I in Item'Range loop
C := Item (I);
if C = ''' then
Append (Buffer, ''');
end if;
Append (Buffer, C);
end loop;
Append (Buffer, ''');
end Escape_Sql;
-- ------------------------------
-- Append the item in the buffer escaping some characters if necessary
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in ADO.Blob_Ref) is
pragma Unreferenced (D);
C : Ada.Streams.Stream_Element;
Blob : constant ADO.Blob_Access := Item.Value;
begin
Append (Buffer, ''');
for I in Blob.Data'Range loop
C := Blob.Data (I);
case C is
when Character'Pos (ASCII.NUL) =>
Append (Buffer, '\');
Append (Buffer, '0');
when Character'Pos (ASCII.CR) =>
Append (Buffer, '\');
Append (Buffer, 'r');
when Character'Pos (ASCII.LF) =>
Append (Buffer, '\');
Append (Buffer, 'n');
when Character'Pos ('\') | Character'Pos (''') | Character'Pos ('"') =>
Append (Buffer, '\');
Append (Buffer, Character'Val (C));
when others =>
Append (Buffer, Character'Val (C));
end case;
end loop;
Append (Buffer, ''');
end Escape_Sql;
-- ------------------------------
-- Append the boolean item in the buffer.
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in Boolean) is
pragma Unreferenced (D);
begin
Append (Buffer, (if Item then '1' else '0'));
end Escape_Sql;
end ADO.Drivers.Dialects;
|
Implement Escape_Sql to format a boolean value (default implementation)
|
Implement Escape_Sql to format a boolean value (default implementation)
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
fde58f05f5a1c969ede3bc81e98c8db9a0159cca
|
src/asf-sessions-factory.adb
|
src/asf-sessions-factory.adb
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2012, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Sessions.Generate_Id (Rand);
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access
:= new Session_Record '(Ada.Finalization.Limited_Controlled with
Ref_Counter => Util.Concurrent.Counters.ONE,
Create_Time => Ada.Calendar.Clock,
Max_Inactive => Factory.Max_Inactive,
others => <>);
begin
Impl.Access_Time := Impl.Create_Time;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Sessions.Insert (Sess);
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
Factory.Sessions.Delete (Sess);
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Factory.Sessions.Find (Id);
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Factory.Sessions.Initialize;
end Initialize;
protected body Session_Cache is
-- ------------------------------
-- Find the session in the session cache.
-- ------------------------------
function Find (Id : in String) return Session is
Pos : constant Session_Maps.Cursor := Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
return Session_Maps.Element (Pos);
else
return Null_Session;
end if;
end Find;
-- ------------------------------
-- Insert the session in the session cache.
-- ------------------------------
procedure Insert (Sess : in Session) is
begin
Sessions.Insert (Sess.Impl.Id.all'Access, Sess);
end Insert;
-- ------------------------------
-- Remove the session from the session cache.
-- ------------------------------
procedure Delete (Sess : in out Session) is
Pos : Session_Maps.Cursor := Sessions.Find (Sess.Impl.Id.all'Access);
begin
if Session_Maps.Has_Element (Pos) then
Session_Maps.Delete (Sessions, Pos);
end if;
Finalize (Sess);
end Delete;
-- ------------------------------
-- Generate a random bitstream.
-- ------------------------------
procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
Size : constant Stream_Element_Offset := Rand'Length / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate_Id;
-- ------------------------------
-- Initialize the random generator.
-- ------------------------------
procedure Initialize is
begin
Id_Random.Reset (Random);
end Initialize;
end Session_Cache;
end ASF.Sessions.Factory;
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2012, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Sessions.Generate_Id (Rand);
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access
:= new Session_Record '(Ada.Finalization.Limited_Controlled with
Ref_Counter => Util.Concurrent.Counters.ONE,
Create_Time => Ada.Calendar.Clock,
Max_Inactive => Factory.Max_Inactive,
others => <>);
begin
Impl.Access_Time := Impl.Create_Time;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Sessions.Insert (Sess);
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
Factory.Sessions.Delete (Sess);
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Factory.Sessions.Find (Id);
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Factory.Sessions.Initialize;
end Initialize;
-- ------------------------------
-- Release all the sessions.
-- ------------------------------
overriding
procedure Finalize (Factory : in out Session_Factory) is
begin
Factory.Sessions.Clear;
end Finalize;
protected body Session_Cache is
-- ------------------------------
-- Find the session in the session cache.
-- ------------------------------
function Find (Id : in String) return Session is
Pos : constant Session_Maps.Cursor := Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
return Session_Maps.Element (Pos);
else
return Null_Session;
end if;
end Find;
-- ------------------------------
-- Insert the session in the session cache.
-- ------------------------------
procedure Insert (Sess : in Session) is
begin
Sessions.Insert (Sess.Impl.Id.all'Access, Sess);
end Insert;
-- ------------------------------
-- Remove the session from the session cache.
-- ------------------------------
procedure Delete (Sess : in out Session) is
Pos : Session_Maps.Cursor := Sessions.Find (Sess.Impl.Id.all'Access);
begin
if Session_Maps.Has_Element (Pos) then
Session_Maps.Delete (Sessions, Pos);
end if;
Finalize (Sess);
end Delete;
-- ------------------------------
-- Generate a random bitstream.
-- ------------------------------
procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
Size : constant Stream_Element_Offset := Rand'Length / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate_Id;
-- ------------------------------
-- Initialize the random generator.
-- ------------------------------
procedure Initialize is
begin
Id_Random.Reset (Random);
end Initialize;
end Session_Cache;
end ASF.Sessions.Factory;
|
Implement the Finalize procedure
|
Implement the Finalize procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
daf8d479eb11b4bdd60d1442bfd2775fabc9c972
|
awa/plugins/awa-setup/src/awa-setup.ads
|
awa/plugins/awa-setup/src/awa-setup.ads
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package AWA.Setup is
pragma Pure;
end AWA.Setup;
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Setup Application ==
-- The <tt>AWA.Setup</tt> package implements a simple setup application
-- that allows to configure the database, the Google and Facebook application
-- identifiers and some other configuration parameters. It is intended to
-- help in the installation process of any AWA-based application.
--
-- It defines a specific web application that is installed in the web container
-- for the duration of the setup. The setup application takes control over all
-- the web requests during the lifetime of the installation. As soon as the
-- installation is finished, the normal application is configured and installed
-- in the web container and the user is automatically redirected to it.
--
-- @include awa-setup-applications.ads
package AWA.Setup is
pragma Pure;
end AWA.Setup;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
356f8066c9f516615ab9fad6683036a913b55d75
|
src/wiki-filters.adb
|
src/wiki-filters.adb
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- 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.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
begin
if Filter.Next /= null then
Filter.Next.Add_Node (Document, Kind);
else
Document.Append (Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Filter.Next /= null then
Filter.Next.Add_Text (Document, Text, Format);
else
Wiki.Documents.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Filter.Next /= null then
Filter.Next.Add_Header (Document, Header, Level);
else
Wiki.Documents.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Next /= null then
Filter.Next.Push_Node (Document, Tag, Attributes);
else
Document.Push_Node (Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag) is
begin
if Filter.Next /= null then
Filter.Next.Pop_Node (Document, Tag);
else
Document.Pop_Node (Tag);
end if;
end Pop_Node;
-- ------------------------------
-- 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.Documents.Document;
Level : in Natural) is
begin
if Filter.Next /= null then
Filter.Next.Add_Blockquote (Document, Level);
else
Document.Add_Blockquote (Level);
end if;
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 (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Filter.Next /= null then
Filter.Next.Add_List_Item (Document, Level, Ordered);
else
Document.Add_List_Item (Level, Ordered);
end if;
end Add_List_Item;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Next /= null then
Filter.Next.Add_Link (Document, Name, Attributes);
else
Document.Add_Link (Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Next /= null then
Filter.Next.Add_Image (Document, Name, Attributes);
else
Document.Add_Image (Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Next /= null then
Filter.Next.Add_Quote (Document, Name, Attributes);
else
Document.Add_Quote (Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
if Filter.Next /= null then
Filter.Next.Add_Preformatted (Document, Text, Format);
else
Document.Add_Preformatted (Text, Format);
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
if Filter.Next /= null then
Filter.Next.Finish (Document);
end if;
end Finish;
-- ------------------------------
-- Add the filter at beginning of the filter chain.
-- ------------------------------
procedure Add_Filter (Chain : in out Filter_Chain;
Filter : in Filter_Type_Access) is
begin
Filter.Next := Chain.Next;
Chain.Next := Filter;
end Add_Filter;
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.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- 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.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
begin
if Filter.Next /= null then
Filter.Next.Add_Node (Document, Kind);
else
Document.Append (Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Filter.Next /= null then
Filter.Next.Add_Text (Document, Text, Format);
else
Wiki.Documents.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Filter.Next /= null then
Filter.Next.Add_Header (Document, Header, Level);
else
Wiki.Documents.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Next /= null then
Filter.Next.Push_Node (Document, Tag, Attributes);
else
Document.Push_Node (Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag) is
begin
if Filter.Next /= null then
Filter.Next.Pop_Node (Document, Tag);
else
Document.Pop_Node (Tag);
end if;
end Pop_Node;
-- ------------------------------
-- 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.Documents.Document;
Level : in Natural) is
begin
if Filter.Next /= null then
Filter.Next.Add_Blockquote (Document, Level);
else
Document.Add_Blockquote (Level);
end if;
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 (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Filter.Next /= null then
Filter.Next.Add_List_Item (Document, Level, Ordered);
else
Document.Add_List_Item (Level, Ordered);
end if;
end Add_List_Item;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Next /= null then
Filter.Next.Add_Link (Document, Name, Attributes);
else
Document.Add_Link (Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Next /= null then
Filter.Next.Add_Image (Document, Name, Attributes);
else
Document.Add_Image (Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Next /= null then
Filter.Next.Add_Quote (Document, Name, Attributes);
else
Document.Add_Quote (Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
if Filter.Next /= null then
Filter.Next.Add_Preformatted (Document, Text, Format);
else
Document.Add_Preformatted (Text, Format);
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
if Filter.Next /= null then
Filter.Next.Finish (Document);
end if;
end Finish;
-- ------------------------------
-- Add the filter at beginning of the filter chain.
-- ------------------------------
procedure Add_Filter (Chain : in out Filter_Chain;
Filter : in Filter_Type_Access) is
begin
Filter.Next := Chain.Next;
Chain.Next := Filter;
end Add_Filter;
-- ------------------------------
-- Internal operation to copy the filter chain.
-- ------------------------------
procedure Set_Chain (Chain : in out Filter_Chain;
From : in Filter_Chain'Class) is
begin
Chain.Next := From.Next;
end Set_Chain;
end Wiki.Filters;
|
Implement the Set_Chain procedure
|
Implement the Set_Chain procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
58c131d9ff26150d05acf8b473f180dfe5c6f8e5
|
src/wiki-filters.adb
|
src/wiki-filters.adb
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Add_Node (Document, Kind);
else
Wiki.Nodes.Append (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Filter_Type;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Document.Add_Header (Header, Level);
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Filter_Type) is
begin
Document.Document.Add_Line_Break;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Filter_Type) is
begin
Document.Document.Add_Paragraph;
end Add_Paragraph;
-- ------------------------------
-- 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 Filter_Type;
Level : in Natural) is
begin
Document.Document.Add_Blockquote (Level);
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 Filter_Type;
Level : in Positive;
Ordered : in Boolean) is
begin
Document.Document.Add_List_Item (Level, Ordered);
end Add_List_Item;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Filter_Type) is
begin
Document.Document.Add_Horizontal_Rule;
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Filter_Type;
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
begin
Document.Document.Add_Link (Name, Link, Language, Title);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Filter_Type;
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
begin
Document.Document.Add_Image (Link, Alt, Position, Description);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Filter_Type;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Quote (Quote, Link, Language);
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
Document.Document.Add_Text (Text, Format);
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Preformatted (Text, Format);
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
begin
Document.Document.Start_Element (Name, Attributes);
end Start_Element;
overriding
procedure End_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Document.End_Element (Name);
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Filter_Type) is
begin
Document.Document.Finish;
end Finish;
-- ------------------------------
-- Set the document reader.
-- ------------------------------
procedure Set_Document (Filter : in out Filter_Type;
Document : in Wiki.Documents.Document_Reader_Access) is
begin
Filter.Document := Document;
end Set_Document;
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.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Add_Node (Document, Kind);
else
Wiki.Nodes.Append (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Add_Text (Document, Text, Format);
else
Wiki.Nodes.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Filter_Type;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Document.Add_Header (Header, Level);
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Filter_Type) is
begin
Document.Document.Add_Line_Break;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Filter_Type) is
begin
Document.Document.Add_Paragraph;
end Add_Paragraph;
-- ------------------------------
-- 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 Filter_Type;
Level : in Natural) is
begin
Document.Document.Add_Blockquote (Level);
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 Filter_Type;
Level : in Positive;
Ordered : in Boolean) is
begin
Document.Document.Add_List_Item (Level, Ordered);
end Add_List_Item;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Filter_Type) is
begin
Document.Document.Add_Horizontal_Rule;
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Filter_Type;
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
begin
Document.Document.Add_Link (Name, Link, Language, Title);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Filter_Type;
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
begin
Document.Document.Add_Image (Link, Alt, Position, Description);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Filter_Type;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Quote (Quote, Link, Language);
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
Document.Document.Add_Text (Text, Format);
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Preformatted (Text, Format);
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
begin
Document.Document.Start_Element (Name, Attributes);
end Start_Element;
overriding
procedure End_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Document.End_Element (Name);
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Filter_Type) is
begin
Document.Document.Finish;
end Finish;
-- ------------------------------
-- Set the document reader.
-- ------------------------------
procedure Set_Document (Filter : in out Filter_Type;
Document : in Wiki.Documents.Document_Reader_Access) is
begin
Filter.Document := Document;
end Set_Document;
end Wiki.Filters;
|
Implement the Add_Text procedure
|
Implement the Add_Text procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
53070f4dcf07bd380026e8b0fcfb4d963ec750ea
|
src/wiki-filters.adb
|
src/wiki-filters.adb
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Node (Document, Kind);
else
Wiki.Nodes.Append (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Text (Document, Text, Format);
else
Wiki.Nodes.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Header (Document, Header, Level);
else
Wiki.Nodes.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Push_Node (Document, Tag, Attributes);
else
Wiki.Nodes.Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Pop_Node (Document, Tag);
else
Wiki.Nodes.Pop_Node (Document, Tag);
end if;
end Pop_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Blockquote (Document, Level);
else
Wiki.Nodes.Add_Blockquote (Document, Level);
end if;
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 (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Filter.Next /= null then
Filter.Next.Add_List_Item (Document, Level, Ordered);
else
Wiki.Nodes.Add_List_Item (Document, Level, Ordered);
end if;
end Add_List_Item;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Link (Document, Name, Attributes);
else
Wiki.Nodes.Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Image (Document, Name, Attributes);
else
Wiki.Nodes.Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Quote (Document, Name, Attributes);
else
Wiki.Nodes.Add_Quote (Document, Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Preformatted (Document, Text, Format);
else
Wiki.Nodes.Add_Preformatted (Document, Text, Format);
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document) is
begin
if Filter.Next /= null then
Filter.Next.Finish (Document);
end if;
end Finish;
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.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Node (Document, Kind);
else
Wiki.Nodes.Append (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- 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.Format_Map) is
begin
if Filter.Next /= null then
Filter.Next.Add_Text (Document, Text, Format);
else
Wiki.Nodes.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Header (Document, Header, Level);
else
Wiki.Nodes.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Push_Node (Document, Tag, Attributes);
else
Wiki.Nodes.Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Pop_Node (Document, Tag);
else
Wiki.Nodes.Pop_Node (Document, Tag);
end if;
end Pop_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Blockquote (Document, Level);
else
Wiki.Nodes.Add_Blockquote (Document, Level);
end if;
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 (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Filter.Next /= null then
Filter.Next.Add_List_Item (Document, Level, Ordered);
else
Wiki.Nodes.Add_List_Item (Document, Level, Ordered);
end if;
end Add_List_Item;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Link (Document, Name, Attributes);
else
Wiki.Nodes.Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Image (Document, Name, Attributes);
else
Wiki.Nodes.Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Quote (Document, Name, Attributes);
else
Wiki.Nodes.Add_Quote (Document, Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Preformatted (Document, Text, Format);
else
Wiki.Nodes.Add_Preformatted (Document, Text, To_Wide_Wide_String (Format));
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document) is
begin
if Filter.Next /= null then
Filter.Next.Finish (Document);
end if;
end Finish;
end Wiki.Filters;
|
Use Wiki.Format_Map type
|
Use Wiki.Format_Map type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
5066b78249d7229e7914346d6c2bde9d98bf5461
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with ASF.Applications;
with AWA.Modules;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
package AWA.Workspaces.Modules is
-- The name under which the module is registered.
NAME : constant String := "workspaces";
-- ------------------------------
-- Module workspaces
-- ------------------------------
type Workspace_Module is new AWA.Modules.Module with private;
type Workspace_Module_Access is access all Workspace_Module'Class;
-- Initialize the workspaces module.
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref);
-- Send the invitation to the user.
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class);
private
type Workspace_Module is new AWA.Modules.Module with null record;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with ASF.Applications;
with AWA.Modules;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Users.Services;
package AWA.Workspaces.Modules is
-- The name under which the module is registered.
NAME : constant String := "workspaces";
-- ------------------------------
-- Module workspaces
-- ------------------------------
type Workspace_Module is new AWA.Modules.Module with private;
type Workspace_Module_Access is access all Workspace_Module'Class;
-- Initialize the workspaces module.
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref);
-- Send the invitation to the user.
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class);
private
type Workspace_Module is new AWA.Modules.Module with record
User_Manager : AWA.Users.Services.User_Service_Access;
end record;
end AWA.Workspaces.Modules;
|
Add a User_Manager to the workspace module
|
Add a User_Manager to the workspace module
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0e1dcf3df84fd582e75ce17ec7f642ea13b283e8
|
regtests/util-streams-sockets-tests.adb
|
regtests/util-streams-sockets-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-sockets-tests -- Unit tests for socket streams
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Util.Test_Caller;
with Util.Streams.Texts;
with Util.Tests.Servers;
package body Util.Streams.Sockets.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Sockets");
type Test_Server is new Util.Tests.Servers.Server with record
Count : Natural := 0;
end record;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect",
Test_Socket_Init'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write",
Test_Socket_Read'Access);
end Add_Tests;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class) is
pragma Unreferenced (Stream);
begin
if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then
Into.Count := Into.Count + 1;
end if;
end Process_Line;
-- ------------------------------
-- Test reading and writing on a socket stream.
-- ------------------------------
procedure Test_Socket_Read (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
Server : Test_Server;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Server.Start;
T.Assert (Server.Get_Port > 0, "The server was not started");
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
GNAT.Sockets.Port_Type (Server.Get_Port));
-- Let the server start.
delay 0.1;
-- Get a connection and write 10 lines.
Stream.Connect (Server => Addr);
Writer.Initialize (Output => Stream'Unchecked_Access,
Input => null,
Size => 1024);
for I in 1 .. 10 loop
Writer.Write ("Sending a line on the socket test-"
& Natural'Image (I) & ASCII.CR & ASCII.LF);
Writer.Flush;
end loop;
Writer.Close;
-- Stop the server and verify that 10 lines were received.
Server.Stop;
Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received");
end Test_Socket_Read;
-- ------------------------------
-- Test socket initialization.
-- ------------------------------
procedure Test_Socket_Init (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Fd : GNAT.Sockets.Socket_Type;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
80);
GNAT.Sockets.Create_Socket (Fd);
Stream.Open (Fd);
begin
Stream.Connect (Addr);
T.Assert (False, "No exception was raised");
exception
when Ada.IO_Exceptions.Use_Error =>
null;
end;
end Test_Socket_Init;
end Util.Streams.Sockets.Tests;
|
-----------------------------------------------------------------------
-- util-streams-sockets-tests -- Unit tests for socket streams
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Util.Test_Caller;
with Util.Streams.Texts;
with Util.Tests.Servers;
package body Util.Streams.Sockets.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Sockets");
type Test_Server is new Util.Tests.Servers.Server with record
Count : Natural := 0;
end record;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect",
Test_Socket_Init'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write",
Test_Socket_Read'Access);
end Add_Tests;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
pragma Unreferenced (Stream, Client);
begin
if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then
Into.Count := Into.Count + 1;
end if;
end Process_Line;
-- ------------------------------
-- Test reading and writing on a socket stream.
-- ------------------------------
procedure Test_Socket_Read (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
Server : Test_Server;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Server.Start;
T.Assert (Server.Get_Port > 0, "The server was not started");
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
GNAT.Sockets.Port_Type (Server.Get_Port));
-- Let the server start.
delay 0.1;
-- Get a connection and write 10 lines.
Stream.Connect (Server => Addr);
Writer.Initialize (Output => Stream'Unchecked_Access,
Input => null,
Size => 1024);
for I in 1 .. 10 loop
Writer.Write ("Sending a line on the socket test-"
& Natural'Image (I) & ASCII.CR & ASCII.LF);
Writer.Flush;
end loop;
Writer.Close;
-- Stop the server and verify that 10 lines were received.
Server.Stop;
Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received");
end Test_Socket_Read;
-- ------------------------------
-- Test socket initialization.
-- ------------------------------
procedure Test_Socket_Init (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Fd : GNAT.Sockets.Socket_Type;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
80);
GNAT.Sockets.Create_Socket (Fd);
Stream.Open (Fd);
begin
Stream.Connect (Addr);
T.Assert (False, "No exception was raised");
exception
when Ada.IO_Exceptions.Use_Error =>
null;
end;
end Test_Socket_Init;
end Util.Streams.Sockets.Tests;
|
Update unit test after changes in Process_Line
|
Update unit test after changes in Process_Line
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
05c8538173962d5806bf76180ac887993f18c764
|
src/security-policies.adb
|
src/security-policies.adb
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Util.Serialize.Mappers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Contexts;
package body Security.Policies is
use type Permissions.Permission_Index;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Security.Controllers.Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
-- ------------------------------
-- Default Security Controllers
-- ------------------------------
-- The <b>Auth_Controller</b> grants the permission if there is a principal.
type Auth_Controller is limited new Security.Controllers.Controller with null record;
-- Returns true if the user associated with the security context <b>Context</b> was
-- authentified (ie, it has a principal).
overriding
function Has_Permission (Handler : in Auth_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- The <b>Pass_Through_Controller</b> grants access to anybody.
type Pass_Through_Controller is limited new Security.Controllers.Controller with null record;
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access the URL defined in <b>Permission</b>.
overriding
function Has_Permission (Handler : in Pass_Through_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> was
-- authentified (ie, it has a principal).
-- ------------------------------
overriding
function Has_Permission (Handler : in Auth_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
pragma Unreferenced (Handler, Permission);
use type Security.Principal_Access;
P : constant Security.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
Log.Debug ("Grant permission because a principal exists");
return True;
else
return False;
end if;
end Has_Permission;
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access the URL defined in <b>Permission</b>.
-- ------------------------------
overriding
function Has_Permission (Handler : in Pass_Through_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
pragma Unreferenced (Handler, Context, Permission);
begin
Log.Debug ("Pass through controller grants the permission");
return True;
end Has_Permission;
-- ------------------------------
-- Get the policy index.
-- ------------------------------
function Get_Policy_Index (From : in Policy'Class) return Policy_Index is
begin
return From.Index;
end Get_Policy_Index;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Free (Manager.Permissions);
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
-- If the permission has a controller, release it.
if Manager.Permissions (Index) /= null then
Log.Warn ("Permission {0} is redefined", Name);
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with"
-- clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler
-- bug but we have to use a temporary variable and do some type conversion...
declare
P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access;
begin
Free (P);
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Checks whether the permission defined by the <b>Permission</b> is granted
-- for the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
-- ------------------------------
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
begin
if Permission.Id >= Manager.Last_Index then
return False;
end if;
declare
C : constant Controller_Access := Manager.Permissions (Permission.Id);
begin
if C = null then
return False;
else
return C.Has_Permission (Context, Permission);
end if;
end;
end Has_Permission;
-- ------------------------------
-- Returns True if the security controller is defined for the given permission index.
-- ------------------------------
function Has_Controller (Manager : in Policy_Manager;
Index : in Permissions.Permission_Index) return Boolean is
begin
return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null;
end Has_Controller;
-- ------------------------------
-- Create the policy contexts to be associated with the security context.
-- ------------------------------
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access is
begin
return new Policy_Context_Array (1 .. Manager.Max_Policies);
end Create_Policy_Contexts;
-- ----
type Policy_Fields is (FIELD_GRANT_PERMISSION, FIELD_AUTH_PERMISSION);
procedure Set_Member (P : in out Policy_Manager'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (P : in out Policy_Manager'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
Name : constant String := Util.Beans.Objects.To_String (Value);
begin
case Field is
when FIELD_GRANT_PERMISSION =>
P.Add_Permission (Name, new Pass_Through_Controller);
when FIELD_AUTH_PERMISSION =>
P.Add_Permission (Name, new Auth_Controller);
end case;
end Set_Member;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Manager'Class,
Element_Type_Access => Policy_Manager_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
--------------------------
-- Prepare the XML parser to read the policy configuration.
-- ------------------------------
procedure Prepare_Config (Manager : in out Policy_Manager;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Reader.Add_Mapping ("module", Policy_Mapping'Access);
Policy_Mapper.Set_Context (Reader, Manager'Unchecked_Access);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
end Prepare_Config;
-- ------------------------------
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
-- ------------------------------
procedure Finish_Config (Manager : in out Policy_Manager;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Finish_Config;
--------------------------
-- Read the policy file
--------------------------
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
Manager.Prepare_Config (Reader);
-- Read the configuration file.
Reader.Parse (File);
Manager.Finish_Config (Reader);
end Read_Policy;
-- ------------------------------
-- Initialize the policy manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Policy'Class,
Policy_Access);
begin
-- Release the security controllers.
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
if Manager.Permissions (I) /= null then
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with"
-- clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler
-- bug but we have to use a temporary variable and do some type conversion...
declare
P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end if;
end loop;
Free (Manager.Permissions);
end if;
-- Release the policy instances.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Free (Manager.Policies (I));
end loop;
end Finalize;
begin
Policy_Mapping.Add_Mapping ("grant-permission/name", FIELD_GRANT_PERMISSION);
Policy_Mapping.Add_Mapping ("auth-permission/name", FIELD_AUTH_PERMISSION);
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Contexts;
package body Security.Policies is
use type Permissions.Permission_Index;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Security.Controllers.Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
-- ------------------------------
-- Default Security Controllers
-- ------------------------------
-- The <b>Auth_Controller</b> grants the permission if there is a principal.
type Auth_Controller is limited new Security.Controllers.Controller with null record;
-- Returns true if the user associated with the security context <b>Context</b> was
-- authentified (ie, it has a principal).
overriding
function Has_Permission (Handler : in Auth_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- The <b>Pass_Through_Controller</b> grants access to anybody.
type Pass_Through_Controller is limited new Security.Controllers.Controller with null record;
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access the URL defined in <b>Permission</b>.
overriding
function Has_Permission (Handler : in Pass_Through_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> was
-- authentified (ie, it has a principal).
-- ------------------------------
overriding
function Has_Permission (Handler : in Auth_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
pragma Unreferenced (Handler, Permission);
use type Security.Principal_Access;
P : constant Security.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
Log.Debug ("Grant permission because a principal exists");
return True;
else
return False;
end if;
end Has_Permission;
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access the URL defined in <b>Permission</b>.
-- ------------------------------
overriding
function Has_Permission (Handler : in Pass_Through_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
pragma Unreferenced (Handler, Context, Permission);
begin
Log.Debug ("Pass through controller grants the permission");
return True;
end Has_Permission;
-- ------------------------------
-- Get the policy index.
-- ------------------------------
function Get_Policy_Index (From : in Policy'Class) return Policy_Index is
begin
return From.Index;
end Get_Policy_Index;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Free (Manager.Permissions);
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
-- If the permission has a controller, release it.
if Manager.Permissions (Index) /= null then
Log.Warn ("Permission {0} is redefined", Name);
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with"
-- clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler
-- bug but we have to use a temporary variable and do some type conversion...
declare
P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access;
begin
Free (P);
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Checks whether the permission defined by the <b>Permission</b> is granted
-- for the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
-- ------------------------------
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
begin
if Permission.Id >= Manager.Last_Index then
return False;
end if;
declare
C : constant Controller_Access := Manager.Permissions (Permission.Id);
begin
if C = null then
return False;
else
return C.Has_Permission (Context, Permission);
end if;
end;
end Has_Permission;
-- ------------------------------
-- Returns True if the security controller is defined for the given permission index.
-- ------------------------------
function Has_Controller (Manager : in Policy_Manager;
Index : in Permissions.Permission_Index) return Boolean is
begin
return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null;
end Has_Controller;
-- ------------------------------
-- Create the policy contexts to be associated with the security context.
-- ------------------------------
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access is
begin
return new Policy_Context_Array (1 .. Manager.Max_Policies);
end Create_Policy_Contexts;
-- ----
type Policy_Fields is (FIELD_GRANT_PERMISSION, FIELD_AUTH_PERMISSION);
procedure Set_Member (P : in out Policy_Manager'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (P : in out Policy_Manager'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
Name : constant String := Util.Beans.Objects.To_String (Value);
begin
case Field is
when FIELD_GRANT_PERMISSION =>
P.Add_Permission (Name, new Pass_Through_Controller);
when FIELD_AUTH_PERMISSION =>
P.Add_Permission (Name, new Auth_Controller);
end case;
end Set_Member;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Manager'Class,
Element_Type_Access => Policy_Manager_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
--------------------------
-- Prepare the XML parser to read the policy configuration.
-- ------------------------------
procedure Prepare_Config (Manager : in out Policy_Manager;
Mapper : in out Util.Serialize.Mappers.Processing) is
begin
Mapper.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Mapper.Add_Mapping ("module", Policy_Mapping'Access);
Policy_Mapper.Set_Context (Mapper, Manager'Unchecked_Access);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Mapper);
end loop;
end Prepare_Config;
-- ------------------------------
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
-- ------------------------------
procedure Finish_Config (Manager : in out Policy_Manager;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Finish_Config;
--------------------------
-- Read the policy file
--------------------------
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
Mapper : Util.Serialize.Mappers.Processing;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
Manager.Prepare_Config (Mapper);
-- Read the configuration file.
Reader.Parse (File, Mapper);
Manager.Finish_Config (Reader);
end Read_Policy;
-- ------------------------------
-- Initialize the policy manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Policy'Class,
Policy_Access);
begin
-- Release the security controllers.
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
if Manager.Permissions (I) /= null then
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with"
-- clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler
-- bug but we have to use a temporary variable and do some type conversion...
declare
P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end if;
end loop;
Free (Manager.Permissions);
end if;
-- Release the policy instances.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Free (Manager.Policies (I));
end loop;
end Finalize;
begin
Policy_Mapping.Add_Mapping ("grant-permission/name", FIELD_GRANT_PERMISSION);
Policy_Mapping.Add_Mapping ("auth-permission/name", FIELD_AUTH_PERMISSION);
end Security.Policies;
|
Update Prepare_Config to get a Mappers.Processing type as paramete Update Read_Policy for the new parser/mapper implementation
|
Update Prepare_Config to get a Mappers.Processing type as paramete
Update Read_Policy for the new parser/mapper implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
ba5b229e439860919d7e9fe8c3413e532d25e265
|
awa/plugins/awa-wikis/regtests/awa-wikis-tests.adb
|
awa/plugins/awa-wikis/regtests/awa-wikis-tests.adb
|
-----------------------------------------------------------------------
-- awa-wikis-tests -- Unit tests for wikis module
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with Servlet.Streams;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
package body AWA.Wikis.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Wikis.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load_List (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save",
Test_Create_Wiki'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (missing)",
Test_Missing_Page'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the wiki as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String) is
function Get_Link (Title : in String) return String;
Wiki : constant String := To_String (T.Wiki_Ident);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
function Get_Link (Title : in String) return String is
Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title);
end Get_Link;
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent",
"wiki-list-recent.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/wikis/tags/" & Wiki,
"wiki-list-tagged.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki tag page is invalid");
if Page'Length > 0 then
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/" & Page,
"wiki-page-" & Page & ".html");
ASF.Tests.Assert_Contains (T, "The wiki page content", Reply,
"Wiki page " & Page & " is invalid");
declare
Info : constant String := Get_Link ("Info");
History : constant String := Get_Link ("History");
begin
Util.Tests.Assert_Matches (T, "/asfunit/wikis/info/[0-9]+/[0-9]+$", Info,
"Invalid wiki info link in the response");
Util.Tests.Assert_Matches (T, "/asfunit/wikis/history/[0-9]+/[0-9]+$", History,
"Invalid wiki history link in the response");
-- Get the information page.
ASF.Tests.Do_Get (Request, Reply, Info (Info'First + 8 .. Info'Last),
"wiki-info-" & Page & ".html");
ASF.Tests.Assert_Contains (T, "wiki-word-list", Reply,
"Wiki info page " & Page & " is invalid");
-- Get the history page.
ASF.Tests.Do_Get (Request, Reply, History (History'First + 8 .. History'Last),
"wiki-history-" & Page & ".html");
ASF.Tests.Assert_Contains (T, "wiki-page-version", Reply,
"Wiki history page " & Page & " is invalid");
end;
end if;
end Verify_Anonymous;
-- ------------------------------
-- Verify that the wiki lists contain the given page.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Page : in String) is
Wiki : constant String := To_String (T.Wiki_Ident);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent",
"wiki-list-recent.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list recent page does not reference the page");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/popular",
"wiki-list-popular.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list popular page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list popular page does not reference the page");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name",
"wiki-list-name.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list name page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list name page does not reference the page");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name/grid",
"wiki-list-name-grid.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list name/grid page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list name/grid page does not reference the page");
end Verify_List_Contains;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("", "");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Wiki (T : in out Test) is
procedure Create_Page (Name : in String; Title : in String);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
procedure Create_Page (Name : in String; Title : in String) is
begin
Request.Set_Parameter ("page-wiki-id", To_String (T.Wiki_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("page-title", Title);
Request.Set_Parameter ("text", "# Main title" & ASCII.LF
& "* The wiki page content." & ASCII.LF
& "* Second item." & ASCII.LF);
Request.Set_Parameter ("name", Name);
Request.Set_Parameter ("comment", "Created wiki page " & Name);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("page-is-public", "1");
Request.Set_Parameter ("wiki-format", "FORMAT_MARKDOWN");
ASF.Tests.Do_Post (Request, Reply, "/wikis/create.html", "create-wiki.html");
T.Page_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/"
& To_String (T.Wiki_Ident) & "/");
Util.Tests.Assert_Equals (T, Name, To_String (T.Page_Ident),
"Invalid redirect after wiki page creation");
-- Remove the 'wikiPage' bean from the request so that we get a new instance
-- for the next call.
Request.Remove_Attribute ("wikiPage");
end Create_Page;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Wiki Space Title");
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/wikis/setup.html", "setup-wiki.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after wiki space creation");
declare
Ident : constant String
:= Helpers.Extract_Redirect (Reply, "/asfunit/wikis/list/");
Pos : constant Natural
:= Util.Strings.Index (Ident, '/');
begin
Util.Tests.Assert_Matches (T, "^[0-9]+/recent/grid$", Ident,
"Invalid wiki space identifier in the response");
T.Wiki_Ident := To_Unbounded_String (Ident (Ident'First .. Pos - 1));
end;
Create_Page ("WikiPageTestName", "Wiki page title1");
T.Verify_List_Contains (To_String (T.Page_Ident));
Create_Page ("WikiSecondPageName", "Wiki page title2");
T.Verify_List_Contains (To_String (T.Page_Ident));
Create_Page ("WikiThirdPageName", "Wiki page title3");
T.Verify_Anonymous ("WikiPageTestName", "Wiki page title1");
T.Verify_Anonymous ("WikiSecondPageName", "Wiki page title2");
T.Verify_Anonymous ("WikiThirdPageName", "Wiki page title3");
end Test_Create_Wiki;
-- ------------------------------
-- Test getting a wiki page which does not exist.
-- ------------------------------
procedure Test_Missing_Page (T : in out Test) is
Wiki : constant String := To_String (T.Wiki_Ident);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/MissingPage",
"wiki-page-missing.html");
ASF.Tests.Assert_Matches (T, ".title.Wiki page does not exist./title.", Reply,
"Wiki page 'MissingPage' is invalid",
ASF.Responses.SC_NOT_FOUND);
ASF.Tests.Assert_Matches (T, ".h2.MissingPage./h2.", Reply,
"Wiki page 'MissingPage' header is invalid",
ASF.Responses.SC_NOT_FOUND);
end Test_Missing_Page;
end AWA.Wikis.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-tests -- Unit tests for wikis module
-- Copyright (C) 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with Servlet.Streams;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
package body AWA.Wikis.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Wikis.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load_List (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save",
Test_Create_Wiki'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (missing)",
Test_Missing_Page'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the wiki as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String) is
pragma Unreferenced (Title);
function Get_Link (Title : in String) return String;
Wiki : constant String := To_String (T.Wiki_Ident);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
function Get_Link (Title : in String) return String is
Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title);
end Get_Link;
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent",
"wiki-list-recent.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/wikis/tags/" & Wiki,
"wiki-list-tagged.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki tag page is invalid");
if Page'Length > 0 then
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/" & Page,
"wiki-page-" & Page & ".html");
ASF.Tests.Assert_Contains (T, "The wiki page content", Reply,
"Wiki page " & Page & " is invalid");
declare
Info : constant String := Get_Link ("Info");
History : constant String := Get_Link ("History");
begin
Util.Tests.Assert_Matches (T, "/asfunit/wikis/info/[0-9]+/[0-9]+$", Info,
"Invalid wiki info link in the response");
Util.Tests.Assert_Matches (T, "/asfunit/wikis/history/[0-9]+/[0-9]+$", History,
"Invalid wiki history link in the response");
-- Get the information page.
ASF.Tests.Do_Get (Request, Reply, Info (Info'First + 8 .. Info'Last),
"wiki-info-" & Page & ".html");
ASF.Tests.Assert_Contains (T, "wiki-word-list", Reply,
"Wiki info page " & Page & " is invalid");
-- Get the history page.
ASF.Tests.Do_Get (Request, Reply, History (History'First + 8 .. History'Last),
"wiki-history-" & Page & ".html");
ASF.Tests.Assert_Contains (T, "wiki-page-version", Reply,
"Wiki history page " & Page & " is invalid");
end;
end if;
end Verify_Anonymous;
-- ------------------------------
-- Verify that the wiki lists contain the given page.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Page : in String) is
Wiki : constant String := To_String (T.Wiki_Ident);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent",
"wiki-list-recent.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list recent page does not reference the page");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/popular",
"wiki-list-popular.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list popular page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list popular page does not reference the page");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name",
"wiki-list-name.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list name page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list name page does not reference the page");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name/grid",
"wiki-list-name-grid.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list name/grid page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list name/grid page does not reference the page");
end Verify_List_Contains;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("", "");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Wiki (T : in out Test) is
procedure Create_Page (Name : in String; Title : in String);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
procedure Create_Page (Name : in String; Title : in String) is
begin
Request.Set_Parameter ("page-wiki-id", To_String (T.Wiki_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("page-title", Title);
Request.Set_Parameter ("text", "# Main title" & ASCII.LF
& "* The wiki page content." & ASCII.LF
& "* Second item." & ASCII.LF);
Request.Set_Parameter ("name", Name);
Request.Set_Parameter ("comment", "Created wiki page " & Name);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("page-is-public", "1");
Request.Set_Parameter ("wiki-format", "FORMAT_MARKDOWN");
ASF.Tests.Do_Post (Request, Reply, "/wikis/create.html", "create-wiki.html");
T.Page_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/"
& To_String (T.Wiki_Ident) & "/");
Util.Tests.Assert_Equals (T, Name, To_String (T.Page_Ident),
"Invalid redirect after wiki page creation");
-- Remove the 'wikiPage' bean from the request so that we get a new instance
-- for the next call.
Request.Remove_Attribute ("wikiPage");
end Create_Page;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Wiki Space Title");
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/wikis/setup.html", "setup-wiki.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after wiki space creation");
declare
Ident : constant String
:= Helpers.Extract_Redirect (Reply, "/asfunit/wikis/list/");
Pos : constant Natural
:= Util.Strings.Index (Ident, '/');
begin
Util.Tests.Assert_Matches (T, "^[0-9]+/recent/grid$", Ident,
"Invalid wiki space identifier in the response");
T.Wiki_Ident := To_Unbounded_String (Ident (Ident'First .. Pos - 1));
end;
Create_Page ("WikiPageTestName", "Wiki page title1");
T.Verify_List_Contains (To_String (T.Page_Ident));
Create_Page ("WikiSecondPageName", "Wiki page title2");
T.Verify_List_Contains (To_String (T.Page_Ident));
Create_Page ("WikiThirdPageName", "Wiki page title3");
T.Verify_Anonymous ("WikiPageTestName", "Wiki page title1");
T.Verify_Anonymous ("WikiSecondPageName", "Wiki page title2");
T.Verify_Anonymous ("WikiThirdPageName", "Wiki page title3");
end Test_Create_Wiki;
-- ------------------------------
-- Test getting a wiki page which does not exist.
-- ------------------------------
procedure Test_Missing_Page (T : in out Test) is
Wiki : constant String := To_String (T.Wiki_Ident);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/MissingPage",
"wiki-page-missing.html");
ASF.Tests.Assert_Matches (T, ".title.Wiki page does not exist./title.", Reply,
"Wiki page 'MissingPage' is invalid",
ASF.Responses.SC_NOT_FOUND);
ASF.Tests.Assert_Matches (T, ".h2.MissingPage./h2.", Reply,
"Wiki page 'MissingPage' header is invalid",
ASF.Responses.SC_NOT_FOUND);
end Test_Missing_Page;
end AWA.Wikis.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0f668d5858a337a5a8fdbc352fe3f12f95e0ce7a
|
awa/src/awa-applications.ads
|
awa/src/awa-applications.ads
|
-----------------------------------------------------------------------
-- awa-applications -- Ada Web Application
-- Copyright (C) 2009 - 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ADO.Queries;
with ADO.Sessions.Factory;
with AWA.Modules;
with AWA.Events;
with AWA.Events.Services;
with AWA.Audits.Services;
-- == Initialization ==
-- The AWA application is represented by the `Application` type which should
-- be extended for the final application to provide the modules and specific
-- components of the final application.
--
-- The initialization of an AWA application is made in several steps
-- represented by different procedures of the main `Application` type.
-- The whole initialization is handled by the `Initialize` procedure
-- which gets a first set of configuration properties and a factory
-- to build specific component.
--
-- The `Initialize` procedure will perform the following steps:
--
-- * It uses the factory to allocate the ASF lifecycle handler, the navigation
-- handler, the security manager, the OAuth manager, the exception
-- handlers.
-- * It calls the `Initialize_Components` procedure to let the
-- application register all the ASF components. These components must
-- be registered before any configuration file is read.
-- * It calls the `Initialize_Config`
-- * It calls the `Initialize_Servlets` procedure to allow the application
-- to register all the servlet instances used by the application.
-- * It calls the `Initialize_Filters` procedure to allow the application
-- to register all the servlet filter instances. The application servlets
-- and filters must be registered before reading the global configuration file.
-- * It loads the global application configuration by reading the `awa.xml`
-- file. By reading this configuration, some global configuration is
-- established on the servlets, filters.
-- * It calls the `Initialize_Modules` procedure so that all the application
-- modules can be registered, configured and initialized. Each module
-- brings its own component, servlet and filter. They are configured
-- by their own XML configuration file.
-- * It loads the module application configuration by reading the XML
-- files described by the `app.config.plugins` configuration. This last
-- step allows the application to setup and update the configuration
-- of all modules that have been registered.
--
-- == Configuration ==
-- The following global configuration parameter are defined:
--
-- @include-config awa.xml
--
package AWA.Applications is
-- Directories where the configuration files are searched.
package P_Module_Dir is
new ASF.Applications.Main.Configs.Parameter ("app.modules.dir",
"#{fn:composePath(app_search_dirs,'config')}");
-- A list of configuration files separated by ';'. These files are
-- searched in 'app.modules.dir' and loaded in the order specified before
-- the application modules.
package P_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml");
-- A list of configuration files separated by ';'. These files are
-- searched in 'app.modules.dir' and loaded in the order specified after
-- all the application modules are initialized.
package P_Plugin_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config.plugins", "");
-- The database connection string to connect to the database.
package P_Database is
new ASF.Applications.Main.Configs.Parameter ("database",
"mysql://localhost:3306/db");
-- The application contextPath configuration that gives the base URL
-- of the application.
package P_Context_Path is
new ASF.Applications.Main.Configs.Parameter ("contextPath",
"");
-- Module manager
--
-- The `Module_Manager` represents the root of the logic manager
type Application is new ASF.Applications.Main.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Initialize the application configuration properties.
-- Properties defined in `Conf` are expanded by using the EL
-- expression resolver.
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config);
-- Initialize the servlets provided by the application.
-- This procedure is called by `Initialize`.
-- It should register the application servlets.
overriding
procedure Initialize_Servlets (App : in out Application);
-- Initialize the filters provided by the application.
-- This procedure is called by `Initialize`.
-- It should register the application filters.
overriding
procedure Initialize_Filters (App : in out Application);
-- Initialize the ASF components provided by the application.
-- This procedure is called by `Initialize`.
-- It should register the component factories used by the application.
overriding
procedure Initialize_Components (App : in out Application);
-- Read the application configuration file `awa.xml`. This is called
-- after the servlets and filters have been registered in the application
-- but before the module registration.
procedure Load_Configuration (App : in out Application;
Files : in String);
-- Initialize the AWA modules provided by the application.
-- This procedure is called by `Initialize`.
-- It should register the modules used by the application.
procedure Initialize_Modules (App : in out Application);
-- Start the application. This is called by the server container
-- when the server is started.
overriding
procedure Start (App : in out Application);
-- Close the application.
overriding
procedure Close (App : in out Application);
-- Register the module in the application
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "");
-- Set a static query loader to load SQL queries.
procedure Set_Query_Loader (App : in out Application;
Loader : in ADO.Queries.Static_Loader_Access);
-- Get the database connection for reading
function Get_Session (App : Application)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session;
-- Register the module in the application
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "");
-- Find the module with the given name
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access;
-- Send the event in the application event queues.
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class);
-- Execute the `Process` procedure with the event manager used by the
-- application.
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager));
-- Get the current application from the servlet context or service context.
function Current return Application_Access;
private
-- Initialize the parser represented by `Parser` to recognize the configuration
-- that are specific to the plugins that have been registered so far.
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class);
type Application is new ASF.Applications.Main.Application with record
DB_Factory : ADO.Sessions.Factory.Session_Factory;
Modules : aliased AWA.Modules.Module_Registry;
Events : aliased AWA.Events.Services.Event_Manager;
Audits : aliased AWA.Audits.Services.Audit_Manager;
end record;
end AWA.Applications;
|
-----------------------------------------------------------------------
-- awa-applications -- Ada Web Application
-- Copyright (C) 2009 - 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ADO.Queries;
with ADO.Sessions.Factory;
with AWA.Modules;
with AWA.Events;
with AWA.Events.Services;
with AWA.Audits.Services;
-- == Initialization ==
-- The AWA application is represented by the `Application` type which should
-- be extended for the final application to provide the modules and specific
-- components of the final application.
--
-- The initialization of an AWA application is made in several steps
-- represented by different procedures of the main `Application` type.
-- The whole initialization is handled by the `Initialize` procedure
-- which gets a first set of configuration properties and a factory
-- to build specific component.
--
-- The `Initialize` procedure will perform the following steps:
--
-- * It uses the factory to allocate the ASF lifecycle handler, the navigation
-- handler, the security manager, the OAuth manager, the exception
-- handlers.
-- * It calls the `Initialize_Components` procedure to let the
-- application register all the ASF components. These components must
-- be registered before any configuration file is read.
-- * It calls the `Initialize_Config`
-- * It calls the `Initialize_Servlets` procedure to allow the application
-- to register all the servlet instances used by the application.
-- * It calls the `Initialize_Filters` procedure to allow the application
-- to register all the servlet filter instances. The application servlets
-- and filters must be registered before reading the global configuration file.
-- * It loads the global application configuration by reading the `awa.xml`
-- file as well as some application specific files. By reading this
-- configuration, some global configuration is established on the servlets,
-- filters, navigation rules. The list of XML files loaded during this
-- step is controlled by the `app.config` configuration.
-- * It calls the `Initialize_Modules` procedure so that all the application
-- modules can be registered, configured and initialized. Each module
-- brings its own component, servlet and filter. They are configured
-- by their own XML configuration file.
-- * It loads the module application configuration by reading the XML
-- files described by the `app.config.plugins` configuration. This last
-- step allows the application to setup and update the configuration
-- of all modules that have been registered.
--
-- == Configuration ==
-- The following global configuration parameter are defined:
--
-- @include-config awa.xml
--
package AWA.Applications is
-- Directories where the configuration files are searched.
package P_Module_Dir is
new ASF.Applications.Main.Configs.Parameter ("app.modules.dir",
"#{fn:composePath(app_search_dirs,'config')}");
-- A list of configuration files separated by ';'. These files are
-- searched in 'app.modules.dir' and loaded in the order specified before
-- the application modules.
package P_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml");
-- A list of configuration files separated by ';'. These files are
-- searched in 'app.modules.dir' and loaded in the order specified after
-- all the application modules are initialized.
package P_Plugin_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config.plugins", "");
-- The database connection string to connect to the database.
package P_Database is
new ASF.Applications.Main.Configs.Parameter ("database",
"mysql://localhost:3306/db");
-- The application contextPath configuration that gives the base URL
-- of the application.
package P_Context_Path is
new ASF.Applications.Main.Configs.Parameter ("contextPath",
"");
-- Module manager
--
-- The `Module_Manager` represents the root of the logic manager
type Application is new ASF.Applications.Main.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Initialize the application configuration properties.
-- Properties defined in `Conf` are expanded by using the EL
-- expression resolver.
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config);
-- Initialize the servlets provided by the application.
-- This procedure is called by `Initialize`.
-- It should register the application servlets.
overriding
procedure Initialize_Servlets (App : in out Application);
-- Initialize the filters provided by the application.
-- This procedure is called by `Initialize`.
-- It should register the application filters.
overriding
procedure Initialize_Filters (App : in out Application);
-- Initialize the ASF components provided by the application.
-- This procedure is called by `Initialize`.
-- It should register the component factories used by the application.
overriding
procedure Initialize_Components (App : in out Application);
-- Read the application configuration file `awa.xml`. This is called
-- after the servlets and filters have been registered in the application
-- but before the module registration.
procedure Load_Configuration (App : in out Application;
Files : in String);
-- Initialize the AWA modules provided by the application.
-- This procedure is called by `Initialize`.
-- It should register the modules used by the application.
procedure Initialize_Modules (App : in out Application);
-- Start the application. This is called by the server container
-- when the server is started.
overriding
procedure Start (App : in out Application);
-- Close the application.
overriding
procedure Close (App : in out Application);
-- Register the module in the application
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "");
-- Set a static query loader to load SQL queries.
procedure Set_Query_Loader (App : in out Application;
Loader : in ADO.Queries.Static_Loader_Access);
-- Get the database connection for reading
function Get_Session (App : Application)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session;
-- Register the module in the application
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "");
-- Find the module with the given name
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access;
-- Send the event in the application event queues.
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class);
-- Execute the `Process` procedure with the event manager used by the
-- application.
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager));
-- Get the current application from the servlet context or service context.
function Current return Application_Access;
private
-- Initialize the parser represented by `Parser` to recognize the configuration
-- that are specific to the plugins that have been registered so far.
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class);
type Application is new ASF.Applications.Main.Application with record
DB_Factory : ADO.Sessions.Factory.Session_Factory;
Modules : aliased AWA.Modules.Module_Registry;
Events : aliased AWA.Events.Services.Event_Manager;
Audits : aliased AWA.Audits.Services.Audit_Manager;
end record;
end AWA.Applications;
|
Document the app.config setup
|
Document the app.config setup
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7950c46cb48980d31eff9fbf9034ee91e4a55710
|
src/sqlite/sqlite3_h-perfect_hash.ads
|
src/sqlite/sqlite3_h-perfect_hash.ads
|
-- Generated by gperfhash
package Sqlite3_H.Perfect_Hash is
function Hash (S : String) return Natural;
-- Returns true if the string <b>S</b> is a keyword.
function Is_Keyword (S : in String) return Boolean;
type Name_Access is access constant String;
type Keyword_Array is array (Natural range <>) of Name_Access;
Keywords : constant Keyword_Array;
private
K_0 : aliased constant String := "ABORT";
K_1 : aliased constant String := "ACTION";
K_2 : aliased constant String := "ADD";
K_3 : aliased constant String := "AFTER";
K_4 : aliased constant String := "ALL";
K_5 : aliased constant String := "ALTER";
K_6 : aliased constant String := "ANALYZE";
K_7 : aliased constant String := "AND";
K_8 : aliased constant String := "AS";
K_9 : aliased constant String := "ASC";
K_10 : aliased constant String := "ATTACH";
K_11 : aliased constant String := "AUTOINCREMENT";
K_12 : aliased constant String := "BEFORE";
K_13 : aliased constant String := "BEGIN";
K_14 : aliased constant String := "BETWEEN";
K_15 : aliased constant String := "BY";
K_16 : aliased constant String := "CASCADE";
K_17 : aliased constant String := "CASE";
K_18 : aliased constant String := "CAST";
K_19 : aliased constant String := "CHECK";
K_20 : aliased constant String := "COLLATE";
K_21 : aliased constant String := "COLUMN";
K_22 : aliased constant String := "COMMIT";
K_23 : aliased constant String := "CONFLICT";
K_24 : aliased constant String := "CONSTRAINT";
K_25 : aliased constant String := "CREATE";
K_26 : aliased constant String := "CROSS";
K_27 : aliased constant String := "CURRENT_DATE";
K_28 : aliased constant String := "CURRENT_TIME";
K_29 : aliased constant String := "CURRENT_TIMESTAMP";
K_30 : aliased constant String := "DATABASE";
K_31 : aliased constant String := "DEFAULT";
K_32 : aliased constant String := "DEFERRABLE";
K_33 : aliased constant String := "DEFERRED";
K_34 : aliased constant String := "DELETE";
K_35 : aliased constant String := "DESC";
K_36 : aliased constant String := "DETACH";
K_37 : aliased constant String := "DISTINCT";
K_38 : aliased constant String := "DROP";
K_39 : aliased constant String := "EACH";
K_40 : aliased constant String := "ELSE";
K_41 : aliased constant String := "END";
K_42 : aliased constant String := "ESCAPE";
K_43 : aliased constant String := "EXCEPT";
K_44 : aliased constant String := "EXCLUSIVE";
K_45 : aliased constant String := "EXISTS";
K_46 : aliased constant String := "EXPLAIN";
K_47 : aliased constant String := "FAIL";
K_48 : aliased constant String := "FOR";
K_49 : aliased constant String := "FOREIGN";
K_50 : aliased constant String := "FROM";
K_51 : aliased constant String := "FULL";
K_52 : aliased constant String := "GLOB";
K_53 : aliased constant String := "GROUP";
K_54 : aliased constant String := "HAVING";
K_55 : aliased constant String := "IF";
K_56 : aliased constant String := "IGNORE";
K_57 : aliased constant String := "IMMEDIATE";
K_58 : aliased constant String := "IN";
K_59 : aliased constant String := "INDEX";
K_60 : aliased constant String := "INDEXED";
K_61 : aliased constant String := "INITIALLY";
K_62 : aliased constant String := "INNER";
K_63 : aliased constant String := "INSERT";
K_64 : aliased constant String := "INSTEAD";
K_65 : aliased constant String := "INTERSECT";
K_66 : aliased constant String := "INTO";
K_67 : aliased constant String := "IS";
K_68 : aliased constant String := "ISNULL";
K_69 : aliased constant String := "JOIN";
K_70 : aliased constant String := "KEY";
K_71 : aliased constant String := "LEFT";
K_72 : aliased constant String := "LIKE";
K_73 : aliased constant String := "LIMIT";
K_74 : aliased constant String := "MATCH";
K_75 : aliased constant String := "NATURAL";
K_76 : aliased constant String := "NO";
K_77 : aliased constant String := "NOT";
K_78 : aliased constant String := "NOTNULL";
K_79 : aliased constant String := "NULL";
K_80 : aliased constant String := "OF";
K_81 : aliased constant String := "OFFSET";
K_82 : aliased constant String := "ON";
K_83 : aliased constant String := "OR";
K_84 : aliased constant String := "ORDER";
K_85 : aliased constant String := "OUTER";
K_86 : aliased constant String := "PLAN";
K_87 : aliased constant String := "PRAGMA";
K_88 : aliased constant String := "PRIMARY";
K_89 : aliased constant String := "QUERY";
K_90 : aliased constant String := "RAISE";
K_91 : aliased constant String := "REFERENCES";
K_92 : aliased constant String := "REGEXP";
K_93 : aliased constant String := "REINDEX";
K_94 : aliased constant String := "RELEASE";
K_95 : aliased constant String := "RENAME";
K_96 : aliased constant String := "REPLACE";
K_97 : aliased constant String := "RESTRICT";
K_98 : aliased constant String := "RIGHT";
K_99 : aliased constant String := "ROLLBACK";
K_100 : aliased constant String := "ROW";
K_101 : aliased constant String := "SAVEPOINT";
K_102 : aliased constant String := "SELECT";
K_103 : aliased constant String := "SET";
K_104 : aliased constant String := "TABLE";
K_105 : aliased constant String := "TEMP";
K_106 : aliased constant String := "TEMPORARY";
K_107 : aliased constant String := "THEN";
K_108 : aliased constant String := "TO";
K_109 : aliased constant String := "TRANSACTION";
K_110 : aliased constant String := "TRIGGER";
K_111 : aliased constant String := "UNION";
K_112 : aliased constant String := "UNIQUE";
K_113 : aliased constant String := "UPDATE";
K_114 : aliased constant String := "USING";
K_115 : aliased constant String := "VACUUM";
K_116 : aliased constant String := "VALUES";
K_117 : aliased constant String := "VIEW";
K_118 : aliased constant String := "VIRTUAL";
K_119 : aliased constant String := "WHEN";
K_120 : aliased constant String := "WHERE";
Keywords : constant Keyword_Array := (
K_0'Access, K_1'Access, K_2'Access, K_3'Access,
K_4'Access, K_5'Access, K_6'Access, K_7'Access,
K_8'Access, K_9'Access, K_10'Access, K_11'Access,
K_12'Access, K_13'Access, K_14'Access, K_15'Access,
K_16'Access, K_17'Access, K_18'Access, K_19'Access,
K_20'Access, K_21'Access, K_22'Access, K_23'Access,
K_24'Access, K_25'Access, K_26'Access, K_27'Access,
K_28'Access, K_29'Access, K_30'Access, K_31'Access,
K_32'Access, K_33'Access, K_34'Access, K_35'Access,
K_36'Access, K_37'Access, K_38'Access, K_39'Access,
K_40'Access, K_41'Access, K_42'Access, K_43'Access,
K_44'Access, K_45'Access, K_46'Access, K_47'Access,
K_48'Access, K_49'Access, K_50'Access, K_51'Access,
K_52'Access, K_53'Access, K_54'Access, K_55'Access,
K_56'Access, K_57'Access, K_58'Access, K_59'Access,
K_60'Access, K_61'Access, K_62'Access, K_63'Access,
K_64'Access, K_65'Access, K_66'Access, K_67'Access,
K_68'Access, K_69'Access, K_70'Access, K_71'Access,
K_72'Access, K_73'Access, K_74'Access, K_75'Access,
K_76'Access, K_77'Access, K_78'Access, K_79'Access,
K_80'Access, K_81'Access, K_82'Access, K_83'Access,
K_84'Access, K_85'Access, K_86'Access, K_87'Access,
K_88'Access, K_89'Access, K_90'Access, K_91'Access,
K_92'Access, K_93'Access, K_94'Access, K_95'Access,
K_96'Access, K_97'Access, K_98'Access, K_99'Access,
K_100'Access, K_101'Access, K_102'Access, K_103'Access,
K_104'Access, K_105'Access, K_106'Access, K_107'Access,
K_108'Access, K_109'Access, K_110'Access, K_111'Access,
K_112'Access, K_113'Access, K_114'Access, K_115'Access,
K_116'Access, K_117'Access, K_118'Access, K_119'Access,
K_120'Access);
end Sqlite3_H.Perfect_Hash;
|
-- Generated by gperfhash
package Sqlite3_H.Perfect_Hash is
pragma Preelaborate;
function Hash (S : String) return Natural;
-- Returns true if the string <b>S</b> is a keyword.
function Is_Keyword (S : in String) return Boolean;
type Name_Access is access constant String;
type Keyword_Array is array (Natural range <>) of Name_Access;
Keywords : constant Keyword_Array;
private
K_0 : aliased constant String := "ABORT";
K_1 : aliased constant String := "ACTION";
K_2 : aliased constant String := "ADD";
K_3 : aliased constant String := "AFTER";
K_4 : aliased constant String := "ALL";
K_5 : aliased constant String := "ALTER";
K_6 : aliased constant String := "ANALYZE";
K_7 : aliased constant String := "AND";
K_8 : aliased constant String := "AS";
K_9 : aliased constant String := "ASC";
K_10 : aliased constant String := "ATTACH";
K_11 : aliased constant String := "AUTOINCREMENT";
K_12 : aliased constant String := "BEFORE";
K_13 : aliased constant String := "BEGIN";
K_14 : aliased constant String := "BETWEEN";
K_15 : aliased constant String := "BY";
K_16 : aliased constant String := "CASCADE";
K_17 : aliased constant String := "CASE";
K_18 : aliased constant String := "CAST";
K_19 : aliased constant String := "CHECK";
K_20 : aliased constant String := "COLLATE";
K_21 : aliased constant String := "COLUMN";
K_22 : aliased constant String := "COMMIT";
K_23 : aliased constant String := "CONFLICT";
K_24 : aliased constant String := "CONSTRAINT";
K_25 : aliased constant String := "CREATE";
K_26 : aliased constant String := "CROSS";
K_27 : aliased constant String := "CURRENT_DATE";
K_28 : aliased constant String := "CURRENT_TIME";
K_29 : aliased constant String := "CURRENT_TIMESTAMP";
K_30 : aliased constant String := "DATABASE";
K_31 : aliased constant String := "DEFAULT";
K_32 : aliased constant String := "DEFERRABLE";
K_33 : aliased constant String := "DEFERRED";
K_34 : aliased constant String := "DELETE";
K_35 : aliased constant String := "DESC";
K_36 : aliased constant String := "DETACH";
K_37 : aliased constant String := "DISTINCT";
K_38 : aliased constant String := "DROP";
K_39 : aliased constant String := "EACH";
K_40 : aliased constant String := "ELSE";
K_41 : aliased constant String := "END";
K_42 : aliased constant String := "ESCAPE";
K_43 : aliased constant String := "EXCEPT";
K_44 : aliased constant String := "EXCLUSIVE";
K_45 : aliased constant String := "EXISTS";
K_46 : aliased constant String := "EXPLAIN";
K_47 : aliased constant String := "FAIL";
K_48 : aliased constant String := "FOR";
K_49 : aliased constant String := "FOREIGN";
K_50 : aliased constant String := "FROM";
K_51 : aliased constant String := "FULL";
K_52 : aliased constant String := "GLOB";
K_53 : aliased constant String := "GROUP";
K_54 : aliased constant String := "HAVING";
K_55 : aliased constant String := "IF";
K_56 : aliased constant String := "IGNORE";
K_57 : aliased constant String := "IMMEDIATE";
K_58 : aliased constant String := "IN";
K_59 : aliased constant String := "INDEX";
K_60 : aliased constant String := "INDEXED";
K_61 : aliased constant String := "INITIALLY";
K_62 : aliased constant String := "INNER";
K_63 : aliased constant String := "INSERT";
K_64 : aliased constant String := "INSTEAD";
K_65 : aliased constant String := "INTERSECT";
K_66 : aliased constant String := "INTO";
K_67 : aliased constant String := "IS";
K_68 : aliased constant String := "ISNULL";
K_69 : aliased constant String := "JOIN";
K_70 : aliased constant String := "KEY";
K_71 : aliased constant String := "LEFT";
K_72 : aliased constant String := "LIKE";
K_73 : aliased constant String := "LIMIT";
K_74 : aliased constant String := "MATCH";
K_75 : aliased constant String := "NATURAL";
K_76 : aliased constant String := "NO";
K_77 : aliased constant String := "NOT";
K_78 : aliased constant String := "NOTNULL";
K_79 : aliased constant String := "NULL";
K_80 : aliased constant String := "OF";
K_81 : aliased constant String := "OFFSET";
K_82 : aliased constant String := "ON";
K_83 : aliased constant String := "OR";
K_84 : aliased constant String := "ORDER";
K_85 : aliased constant String := "OUTER";
K_86 : aliased constant String := "PLAN";
K_87 : aliased constant String := "PRAGMA";
K_88 : aliased constant String := "PRIMARY";
K_89 : aliased constant String := "QUERY";
K_90 : aliased constant String := "RAISE";
K_91 : aliased constant String := "REFERENCES";
K_92 : aliased constant String := "REGEXP";
K_93 : aliased constant String := "REINDEX";
K_94 : aliased constant String := "RELEASE";
K_95 : aliased constant String := "RENAME";
K_96 : aliased constant String := "REPLACE";
K_97 : aliased constant String := "RESTRICT";
K_98 : aliased constant String := "RIGHT";
K_99 : aliased constant String := "ROLLBACK";
K_100 : aliased constant String := "ROW";
K_101 : aliased constant String := "SAVEPOINT";
K_102 : aliased constant String := "SELECT";
K_103 : aliased constant String := "SET";
K_104 : aliased constant String := "TABLE";
K_105 : aliased constant String := "TEMP";
K_106 : aliased constant String := "TEMPORARY";
K_107 : aliased constant String := "THEN";
K_108 : aliased constant String := "TO";
K_109 : aliased constant String := "TRANSACTION";
K_110 : aliased constant String := "TRIGGER";
K_111 : aliased constant String := "UNION";
K_112 : aliased constant String := "UNIQUE";
K_113 : aliased constant String := "UPDATE";
K_114 : aliased constant String := "USING";
K_115 : aliased constant String := "VACUUM";
K_116 : aliased constant String := "VALUES";
K_117 : aliased constant String := "VIEW";
K_118 : aliased constant String := "VIRTUAL";
K_119 : aliased constant String := "WHEN";
K_120 : aliased constant String := "WHERE";
Keywords : constant Keyword_Array := (
K_0'Access, K_1'Access, K_2'Access, K_3'Access,
K_4'Access, K_5'Access, K_6'Access, K_7'Access,
K_8'Access, K_9'Access, K_10'Access, K_11'Access,
K_12'Access, K_13'Access, K_14'Access, K_15'Access,
K_16'Access, K_17'Access, K_18'Access, K_19'Access,
K_20'Access, K_21'Access, K_22'Access, K_23'Access,
K_24'Access, K_25'Access, K_26'Access, K_27'Access,
K_28'Access, K_29'Access, K_30'Access, K_31'Access,
K_32'Access, K_33'Access, K_34'Access, K_35'Access,
K_36'Access, K_37'Access, K_38'Access, K_39'Access,
K_40'Access, K_41'Access, K_42'Access, K_43'Access,
K_44'Access, K_45'Access, K_46'Access, K_47'Access,
K_48'Access, K_49'Access, K_50'Access, K_51'Access,
K_52'Access, K_53'Access, K_54'Access, K_55'Access,
K_56'Access, K_57'Access, K_58'Access, K_59'Access,
K_60'Access, K_61'Access, K_62'Access, K_63'Access,
K_64'Access, K_65'Access, K_66'Access, K_67'Access,
K_68'Access, K_69'Access, K_70'Access, K_71'Access,
K_72'Access, K_73'Access, K_74'Access, K_75'Access,
K_76'Access, K_77'Access, K_78'Access, K_79'Access,
K_80'Access, K_81'Access, K_82'Access, K_83'Access,
K_84'Access, K_85'Access, K_86'Access, K_87'Access,
K_88'Access, K_89'Access, K_90'Access, K_91'Access,
K_92'Access, K_93'Access, K_94'Access, K_95'Access,
K_96'Access, K_97'Access, K_98'Access, K_99'Access,
K_100'Access, K_101'Access, K_102'Access, K_103'Access,
K_104'Access, K_105'Access, K_106'Access, K_107'Access,
K_108'Access, K_109'Access, K_110'Access, K_111'Access,
K_112'Access, K_113'Access, K_114'Access, K_115'Access,
K_116'Access, K_117'Access, K_118'Access, K_119'Access,
K_120'Access);
end Sqlite3_H.Perfect_Hash;
|
Make the package Preelaborate
|
Make the package Preelaborate
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
a44bbddfe98126f9b49231e04eefc41fdb46e387
|
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
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
5d6f4a435b6776053e4bc4bb91381b51fc156616
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012, 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.Containers;
with ADO;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Utils.To_Object (From.Folder_Id);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
Found : Boolean;
begin
if Name = "folderId" then
From.Folder_Id := ADO.Utils.To_Identifier (Value);
Manager.Load_Folder (Folder, From.Folder_Id);
From.Set_Folder (Folder);
elsif Name = "id" then
Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value));
elsif Name = "name" then
Folder := Models.Storage_Folder_Ref (From.Get_Folder);
Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found);
if not Found then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
From.Set_Folder (Folder);
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Name : constant String := Bean.Get_Name;
begin
if Name'Length = 0 then
Bean.Set_Name (Part.Get_Name);
end if;
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Bean);
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Publish the file.
-- ------------------------------
overriding
procedure Publish (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id");
Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status");
begin
Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Publish;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Upload_Bean_Access := new Upload_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Upload_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if ADO.Objects.Is_Null (From) then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
-- ------------------------------
-- Load the folder instance.
-- ------------------------------
procedure Load_Folder (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type Ada.Containers.Count_Type;
Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager;
begin
Load_Folders (Storage);
if Storage.Folder_List.List.Length > 0 then
Manager.Load_Folder (Storage.Folder_Bean.all,
Storage.Folder_List.List.Element (0).Id);
end if;
Storage.Flags (INIT_FOLDER) := True;
end Load_Folder;
-- ------------------------------
-- Load the list of folders.
-- ------------------------------
procedure Load_Folders (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query);
Storage.Flags (INIT_FOLDER_LIST) := True;
end Load_Folders;
-- ------------------------------
-- Load the list of files associated with the current folder.
-- ------------------------------
procedure Load_Files (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
if not Storage.Init_Flags (INIT_FOLDER) then
Load_Folder (Storage);
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Storage.Folder_Bean.Is_Null then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id);
end if;
AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query);
Storage.Flags (INIT_FILE_LIST) := True;
end Load_Files;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Storage_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
begin
if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then
Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Flags (INIT_FOLDER) := True;
end if;
end Set_Value;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "files" then
if not List.Init_Flags (INIT_FILE_LIST) then
Load_Files (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folders" then
if not List.Init_Flags (INIT_FOLDER_LIST) then
Load_Folders (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folder" then
if not List.Init_Flags (INIT_FOLDER) then
Load_Folder (List);
end if;
if List.Folder_Bean.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Load the files and folder information.
-- ------------------------------
overriding
procedure Load (List : in out Storage_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Storage_List_Bean'Class (List).Load_Folders;
Storage_List_Bean'Class (List).Load_Files;
end Load;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
begin
Object.Module := Module;
Object.Folder_Bean := Object.Folder'Access;
Object.Folder_List_Bean := Object.Folder_List'Access;
Object.Files_List_Bean := Object.Files_List'Access;
Object.Flags := Object.Init_Flags'Access;
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012, 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.Containers;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Utils.To_Object (From.Folder_Id);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
Found : Boolean;
begin
if Name = "folderId" then
From.Folder_Id := ADO.Utils.To_Identifier (Value);
Manager.Load_Folder (Folder, From.Folder_Id);
From.Set_Folder (Folder);
elsif Name = "id" then
Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value));
elsif Name = "name" then
Folder := Models.Storage_Folder_Ref (From.Get_Folder);
Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found);
if not Found then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
From.Set_Folder (Folder);
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Name : constant String := Bean.Get_Name;
begin
if Name'Length = 0 then
Bean.Set_Name (Part.Get_Name);
end if;
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Bean);
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Publish the file.
-- ------------------------------
overriding
procedure Publish (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id");
Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status");
begin
Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Publish;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Upload_Bean_Access := new Upload_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Upload_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if ADO.Objects.Is_Null (From) then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
-- ------------------------------
-- Load the folder instance.
-- ------------------------------
procedure Load_Folder (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type Ada.Containers.Count_Type;
Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager;
begin
Load_Folders (Storage);
if Storage.Folder_List.List.Length > 0 then
Manager.Load_Folder (Storage.Folder_Bean.all,
Storage.Folder_List.List.Element (0).Id);
end if;
Storage.Flags (INIT_FOLDER) := True;
end Load_Folder;
-- ------------------------------
-- Load the list of folders.
-- ------------------------------
procedure Load_Folders (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query);
Storage.Flags (INIT_FOLDER_LIST) := True;
end Load_Folders;
-- ------------------------------
-- Load the list of files associated with the current folder.
-- ------------------------------
procedure Load_Files (Storage : in Storage_List_Bean) is
use AWA.Storages.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Storage.Module.Get_Session;
Query : ADO.Queries.Context;
begin
if not Storage.Init_Flags (INIT_FOLDER) then
Load_Folder (Storage);
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Storage.Folder_Bean.Is_Null then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id);
end if;
AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query);
Storage.Flags (INIT_FILE_LIST) := True;
end Load_Files;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Storage_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
begin
if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then
Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Flags (INIT_FOLDER) := True;
end if;
end Set_Value;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "files" then
if not List.Init_Flags (INIT_FILE_LIST) then
Load_Files (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folders" then
if not List.Init_Flags (INIT_FOLDER_LIST) then
Load_Folders (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "folder" then
if not List.Init_Flags (INIT_FOLDER) then
Load_Folder (List);
end if;
if List.Folder_Bean.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (Value => List.Folder_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Load the files and folder information.
-- ------------------------------
overriding
procedure Load (List : in out Storage_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Storage_List_Bean'Class (List).Load_Folders;
Storage_List_Bean'Class (List).Load_Files;
end Load;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
begin
Object.Module := Module;
Object.Folder_Bean := Object.Folder'Access;
Object.Folder_List_Bean := Object.Folder_List'Access;
Object.Files_List_Bean := Object.Files_List'Access;
Object.Flags := Object.Init_Flags'Access;
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1f2fd8529d4ebb35597b2f030d86b6fdf8cf97ff
|
mat/src/events/mat-events-targets.adb
|
mat/src/events/mat-events-targets.adb
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id + 1, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while not Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
end Event_Collector;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id + 1, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while not Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
end Event_Collector;
end MAT.Events.Targets;
|
Implement the Get_Event function
|
Implement the Get_Event function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
6feb340b6ac060d2c0cfc7aa97667e57530433d2
|
mat/src/events/mat-events-targets.ads
|
mat/src/events/mat-events-targets.ads
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
type Event_Type is mod 16;
type Probe_Index_Type is mod 16;
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Time;
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;
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;
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 current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
private
EVENT_BLOCK_SIZE : constant Positive := 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 : Natural := 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;
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 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);
private
Current : Event_Block_Access := null;
Events : Event_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is tagged limited record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
type Event_Type is mod 16;
type Probe_Index_Type is mod 16;
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Time;
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;
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;
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 current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
private
EVENT_BLOCK_SIZE : constant Positive := 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 : Natural := 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;
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 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;
private
Current : Event_Block_Access := null;
Events : Event_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is tagged limited record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
end MAT.Events.Targets;
|
Declare the protected procedure Get_Event to retrieve an event from the event ID
|
Declare the protected procedure Get_Event to retrieve an event from the event ID
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
24be8d00ad712d5962e6289059fa2b9da8d08ee0
|
mat/src/events/mat-events-targets.adb
|
mat/src/events/mat-events-targets.adb
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id + 1, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
end Event_Collector;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id + 1, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
-- ------------------------------
-- 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)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos = Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
end loop;
end Iterate;
end Event_Collector;
end MAT.Events.Targets;
|
Implement the protected procedure Iterate
|
Implement the protected procedure Iterate
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
0c959db11e669002fe3e81f133134a79e61c33af
|
awa/plugins/awa-storages/src/model/awa-storages-beans-factories.adb
|
awa/plugins/awa-storages/src/model/awa-storages-beans-factories.adb
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Parts;
with ASF.Parts.Upload_Method;
with ASF.Events.Faces.Actions;
package body AWA.Storages.Beans.Factories is
package Upload_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Upload_Bean,
Method => Upload,
Name => "upload");
package Save_Part_Binding is
new ASF.Parts.Upload_Method.Bind (Name => "save",
Bean => Upload_Bean,
Method => Save_Part);
Upload_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Upload_Binding.Proxy'Access,
2 => Save_Part_Binding.Proxy'Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Upload_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Upload_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Upload_Bean_Access := new Upload_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Upload_Bean;
package Folder_Save_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Folder_Bean,
Method => Save,
Name => "save");
Folder_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Folder_Save_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Folder_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Folder_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Folder_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Folder_Bean_Access := new Folder_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Folder_Bean;
end AWA.Storages.Beans.Factories;
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Parts;
with ASF.Parts.Upload_Method;
with ASF.Events.Faces.Actions;
package body AWA.Storages.Beans.Factories is
package Upload_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Upload_Bean,
Method => Upload,
Name => "upload");
package Delete_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Upload_Bean,
Method => Delete,
Name => "delete");
package Save_Part_Binding is
new ASF.Parts.Upload_Method.Bind (Name => "save",
Bean => Upload_Bean,
Method => Save_Part);
Upload_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Upload_Binding.Proxy'Access,
2 => Save_Part_Binding.Proxy'Access,
3 => Delete_Binding.Proxy'Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Upload_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Upload_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Upload_Bean_Access := new Upload_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Upload_Bean;
package Folder_Save_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Folder_Bean,
Method => Save,
Name => "save");
Folder_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Folder_Save_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Folder_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Folder_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Upload_Bean bean instance.
-- ------------------------------
function Create_Folder_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Folder_Bean_Access := new Folder_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Folder_Bean;
end AWA.Storages.Beans.Factories;
|
Define the delete action on the Ada bean
|
Define the delete action on the Ada bean
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
ebd502ac3add5c06a4f8b70f2cd3e66141208e40
|
src/asf-views-nodes-core.ads
|
src/asf-views-nodes-core.ads
|
-----------------------------------------------------------------------
-- nodes-core -- Core nodes
-- 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.
-----------------------------------------------------------------------
-- The <b>ASF.Views.Nodes.Core</b> package defines some pre-defined
-- core tag nodes which are mapped in the following namespaces:
--
-- xmlns:c="http://java.sun.com/jstl/core"
-- xmlns:ui="http://java.sun.com/jsf/facelets"
-- xmlns:fn="http://java.sun.com/jsp/jstl/functions"
--
-- The following JSTL core elements are defined:
-- <c:set var="name" value="#{expr}"/>
-- <c:if test="#{expr}"> ...</c:if>
-- <c:choose><c:when test="#{expr}"></c:when><c:otherwise/</c:choose>
--
--
with ASF.Factory;
with EL.Functions;
package ASF.Views.Nodes.Core is
FN_URI : constant String := "http://java.sun.com/jsp/jstl/functions";
-- Tag factory for nodes defined in this package.
function Definition return ASF.Factory.Factory_Bindings_Access;
-- Register a set of functions in the namespace
-- xmlns:fn="http://java.sun.com/jsp/jstl/functions"
-- Functions:
-- capitalize, toUpperCase, toLowerCase
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
-- ------------------------------
-- Set Tag
-- ------------------------------
-- The <c:set var="name" value="#{expr}"/> variable creation.
-- The variable is created in the faces context.
type Set_Tag_Node is new Tag_Node with private;
type Set_Tag_Node_Access is access all Set_Tag_Node'Class;
-- Create the Set Tag
function Create_Set_Tag_Node (Binding : in Binding_Access;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
overriding
procedure Build_Components (Node : access Set_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class);
-- ------------------------------
-- If Tag
-- ------------------------------
-- The <c:if test="#{expr}"> ...</c:if> condition.
-- If the condition evaluates to true when the component tree is built,
-- the children of this node are evaluated. Otherwise the entire
-- sub-tree is not present in the component tree.
type If_Tag_Node is new Tag_Node with private;
type If_Tag_Node_Access is access all If_Tag_Node'Class;
-- Create the If Tag
function Create_If_Tag_Node (Binding : in Binding_Access;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
overriding
procedure Build_Components (Node : access If_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class);
-- ------------------------------
-- Choose Tag
-- ------------------------------
-- The <c:choose> ...</c:choose> choice.
-- Evaluate a set of choices (<c:when>) until one of them is found.
-- When no choice is found, evaluate the <c:otherwise> node.
type Choose_Tag_Node is new Tag_Node with private;
type Choose_Tag_Node_Access is access all Choose_Tag_Node'Class;
-- Freeze the tag node tree and perform any initialization steps
-- necessary to build the components efficiently.
-- Prepare the evaluation of choices by identifying the <c:when> and
-- <c:otherwise> conditions.
overriding
procedure Freeze (Node : access Choose_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.
overriding
procedure Build_Components (Node : access Choose_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class);
-- Create the <c:choose> tag node
function Create_Choose_Tag_Node (Binding : in Binding_Access;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- ------------------------------
-- When Tag
-- ------------------------------
-- The <c:when test="#{expr}"> ...</c:when> choice.
-- If the condition evaluates to true when the component tree is built,
-- the children of this node are evaluated. Otherwise the entire
-- sub-tree is not present in the component tree.
type When_Tag_Node is new If_Tag_Node with private;
type When_Tag_Node_Access is access all When_Tag_Node'Class;
-- Check whether the node condition is selected.
function Is_Selected (Node : When_Tag_Node;
Context : Facelet_Context'Class) return Boolean;
-- Create the When Tag
function Create_When_Tag_Node (Binding : in Binding_Access;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- ------------------------------
-- Otherwise Tag
-- ------------------------------
-- The <c:otherwise> ...</c:otherwise> choice.
-- When all the choice conditions were false, the component tree is built,
-- the children of this node are evaluated.
type Otherwise_Tag_Node is new Tag_Node with null record;
type Otherwise_Tag_Node_Access is access all Otherwise_Tag_Node'Class;
-- Create the Otherwise Tag
function Create_Otherwise_Tag_Node (Binding : in Binding_Access;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- Java Facelet provides a <c:repeat> tag. It must not be implemented
-- because it was proven this was not a good method for iterating over a list.
private
type Set_Tag_Node is new Tag_Node with record
Var : Tag_Attribute_Access;
Value : Tag_Attribute_Access;
end record;
type If_Tag_Node is new Tag_Node with record
Condition : Tag_Attribute_Access;
Var : Tag_Attribute_Access;
end record;
type When_Tag_Node is new If_Tag_Node with record
Next_Choice : When_Tag_Node_Access;
end record;
type Choose_Tag_Node is new Tag_Node with record
Choices : When_Tag_Node_Access;
Otherwise : Tag_Node_Access;
end record;
end ASF.Views.Nodes.Core;
|
-----------------------------------------------------------------------
-- nodes-core -- Core nodes
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Views.Nodes.Core</b> package defines some pre-defined
-- core tag nodes which are mapped in the following namespaces:
--
-- xmlns:c="http://java.sun.com/jstl/core"
-- xmlns:ui="http://java.sun.com/jsf/facelets"
-- xmlns:fn="http://java.sun.com/jsp/jstl/functions"
--
-- The following JSTL core elements are defined:
-- <c:set var="name" value="#{expr}"/>
-- <c:if test="#{expr}"> ...</c:if>
-- <c:choose><c:when test="#{expr}"></c:when><c:otherwise/</c:choose>
--
--
with ASF.Factory;
with EL.Functions;
package ASF.Views.Nodes.Core is
FN_URI : constant String := "http://java.sun.com/jsp/jstl/functions";
-- Register the facelets component factory.
procedure Register (Factory : in out ASF.Factory.Component_Factory);
-- Register a set of functions in the namespace
-- xmlns:fn="http://java.sun.com/jsp/jstl/functions"
-- Functions:
-- capitalize, toUpperCase, toLowerCase
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
-- ------------------------------
-- Set Tag
-- ------------------------------
-- The <c:set var="name" value="#{expr}"/> variable creation.
-- The variable is created in the faces context.
type Set_Tag_Node is new Tag_Node with private;
type Set_Tag_Node_Access is access all Set_Tag_Node'Class;
-- Create the Set Tag
function Create_Set_Tag_Node (Binding : in Binding_Type;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
overriding
procedure Build_Components (Node : access Set_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class);
-- ------------------------------
-- If Tag
-- ------------------------------
-- The <c:if test="#{expr}"> ...</c:if> condition.
-- If the condition evaluates to true when the component tree is built,
-- the children of this node are evaluated. Otherwise the entire
-- sub-tree is not present in the component tree.
type If_Tag_Node is new Tag_Node with private;
type If_Tag_Node_Access is access all If_Tag_Node'Class;
-- Create the If Tag
function Create_If_Tag_Node (Binding : in Binding_Type;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
overriding
procedure Build_Components (Node : access If_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class);
-- ------------------------------
-- Choose Tag
-- ------------------------------
-- The <c:choose> ...</c:choose> choice.
-- Evaluate a set of choices (<c:when>) until one of them is found.
-- When no choice is found, evaluate the <c:otherwise> node.
type Choose_Tag_Node is new Tag_Node with private;
type Choose_Tag_Node_Access is access all Choose_Tag_Node'Class;
-- Freeze the tag node tree and perform any initialization steps
-- necessary to build the components efficiently.
-- Prepare the evaluation of choices by identifying the <c:when> and
-- <c:otherwise> conditions.
overriding
procedure Freeze (Node : access Choose_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.
overriding
procedure Build_Components (Node : access Choose_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class);
-- Create the <c:choose> tag node
function Create_Choose_Tag_Node (Binding : in Binding_Type;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- ------------------------------
-- When Tag
-- ------------------------------
-- The <c:when test="#{expr}"> ...</c:when> choice.
-- If the condition evaluates to true when the component tree is built,
-- the children of this node are evaluated. Otherwise the entire
-- sub-tree is not present in the component tree.
type When_Tag_Node is new If_Tag_Node with private;
type When_Tag_Node_Access is access all When_Tag_Node'Class;
-- Check whether the node condition is selected.
function Is_Selected (Node : When_Tag_Node;
Context : Facelet_Context'Class) return Boolean;
-- Create the When Tag
function Create_When_Tag_Node (Binding : in Binding_Type;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- ------------------------------
-- Otherwise Tag
-- ------------------------------
-- The <c:otherwise> ...</c:otherwise> choice.
-- When all the choice conditions were false, the component tree is built,
-- the children of this node are evaluated.
type Otherwise_Tag_Node is new Tag_Node with null record;
type Otherwise_Tag_Node_Access is access all Otherwise_Tag_Node'Class;
-- Create the Otherwise Tag
function Create_Otherwise_Tag_Node (Binding : in Binding_Type;
Line : in Line_Info;
Parent : in Tag_Node_Access;
Attributes : in Tag_Attribute_Array_Access)
return Tag_Node_Access;
-- Java Facelet provides a <c:repeat> tag. It must not be implemented
-- because it was proven this was not a good method for iterating over a list.
private
type Set_Tag_Node is new Tag_Node with record
Var : Tag_Attribute_Access;
Value : Tag_Attribute_Access;
end record;
type If_Tag_Node is new Tag_Node with record
Condition : Tag_Attribute_Access;
Var : Tag_Attribute_Access;
end record;
type When_Tag_Node is new If_Tag_Node with record
Next_Choice : When_Tag_Node_Access;
end record;
type Choose_Tag_Node is new Tag_Node with record
Choices : When_Tag_Node_Access;
Otherwise : Tag_Node_Access;
end record;
end ASF.Views.Nodes.Core;
|
Use Binding_Type instead of Binding_Access
|
Use Binding_Type instead of Binding_Access
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
59ae715e8c150fea6756ecd79fe35f51b450c1f0
|
src/gen-commands-plugins.adb
|
src/gen-commands-plugins.adb
|
-----------------------------------------------------------------------
-- gen-commands-plugins -- Plugin creation and management commands for dynamo
-- Copyright (C) 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with Gen.Model.Projects;
with GNAT.Command_Line;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Plugins is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
function Get_Directory_Name (Name : in String;
Name_Dir : in Ada.Strings.Unbounded.Unbounded_String)
return String;
function Get_Directory_Name (Name : in String;
Name_Dir : in Ada.Strings.Unbounded.Unbounded_String)
return String is
begin
if Ada.Strings.Unbounded.Length (Name_Dir) = 0 then
return Name;
else
return Ada.Strings.Unbounded.To_String (Name_Dir);
end if;
end Get_Directory_Name;
Result_Dir : constant String := Generator.Get_Result_Directory;
Name_Dir : Ada.Strings.Unbounded.Unbounded_String;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: d:") is
when ASCII.NUL => exit;
when 'd' =>
Name_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Parameter);
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "gpl3" then
Generator.Set_Project_Property ("license", "gpl3");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
declare
Name : constant String := Get_Argument;
Kind : constant String := Get_Argument;
Dir : constant String := Generator.Get_Plugin_Directory;
Path : constant String := Util.Files.Compose (Dir, Get_Directory_Name (Name, Name_Dir));
begin
if Name'Length = 0 then
Generator.Error ("Missing plugin name");
Gen.Commands.Usage;
return;
end if;
if Kind /= "ada" and Kind /= "web" then
Generator.Error ("Invalid plugin type (must be 'ada' or 'web')");
return;
end if;
if Ada.Directories.Exists (Path) then
Generator.Error ("Plugin {0} exists already", Name);
return;
end if;
if not Ada.Directories.Exists (Dir) then
Ada.Directories.Create_Directory (Dir);
end if;
Ada.Directories.Create_Directory (Path);
Generator.Set_Result_Directory (Path);
-- Create the plugin project instance and generate its dynamo.xml file.
-- The new plugin is added to the current project so that it will be referenced.
declare
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition);
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is
Plugin : Gen.Model.Projects.Project_Definition_Access;
File : constant String := Util.Files.Compose (Path, "dynamo.xml");
begin
Project.Create_Project (Name => Name,
Path => File,
Project => Plugin);
Project.Add_Module (Plugin);
Plugin.Props.Set ("license", Project.Props.Get ("license", "none"));
Plugin.Props.Set ("author", Project.Props.Get ("author", ""));
Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", ""));
Plugin.Save (File);
end Create_Plugin;
begin
Generator.Update_Project (Create_Plugin'Access);
end;
-- Generate the new plugin content.
Generator.Set_Force_Save (False);
Generator.Set_Global ("pluginName", Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE,
"create-plugin-" & Kind);
-- And save the project dynamo.xml file which now refers to the new plugin.
Generator.Set_Result_Directory (Result_Dir);
Generator.Save_Project;
exception
when Ada.Directories.Name_Error | Ada.Directories.Use_Error =>
Generator.Error ("Cannot create directory {0}", Path);
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-plugin: Create a new plugin for the current project");
Put_Line ("Usage: create-plugin [-l apache|gpl|gpl3|mit|bsd3|proprietary] "
& "[-d DIR] NAME [ada | web]");
New_Line;
Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME.");
Put_Line (" The plugin license is controlled by the -l option.");
Put_Line (" The plugin type is specified as the last argument which can be one of:");
New_Line;
Put_Line (" ada the plugin contains Ada code and a GNAT project is created");
Put_Line (" web the plugin contains XHTML, CSS, Javascript files only");
New_Line;
Put_Line (" The -d option allows to control the plugin directory name. The plugin NAME");
Put_Line (" is used by default. The plugin is created in the directory:");
Put_Line (" plugins/NAME or plugins/DIR");
New_Line;
Put_Line (" For the Ada plugin, the command generates the following files"
& " in the plugin directory:");
Put_Line (" src/<project>-<plugin>.ads");
Put_Line (" src/<project>-<plugin>-<module>.ads");
Put_Line (" src/<project>-<plugin>-<module>.adb");
end Help;
end Gen.Commands.Plugins;
|
-----------------------------------------------------------------------
-- gen-commands-plugins -- Plugin creation and management commands for dynamo
-- Copyright (C) 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with Gen.Model.Projects;
with GNAT.Command_Line;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Plugins is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, Args);
use GNAT.Command_Line;
function Get_Directory_Name (Name : in String;
Name_Dir : in Ada.Strings.Unbounded.Unbounded_String)
return String;
function Get_Directory_Name (Name : in String;
Name_Dir : in Ada.Strings.Unbounded.Unbounded_String)
return String is
begin
if Ada.Strings.Unbounded.Length (Name_Dir) = 0 then
return Name;
else
return Ada.Strings.Unbounded.To_String (Name_Dir);
end if;
end Get_Directory_Name;
Result_Dir : constant String := Generator.Get_Result_Directory;
Name_Dir : Ada.Strings.Unbounded.Unbounded_String;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: d:") is
when ASCII.NUL => exit;
when 'd' =>
Name_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Parameter);
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "gpl3" then
Generator.Set_Project_Property ("license", "gpl3");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
declare
Name : constant String := Get_Argument;
Kind : constant String := Get_Argument;
Dir : constant String := Generator.Get_Plugin_Directory;
Path : constant String := Util.Files.Compose (Dir, Get_Directory_Name (Name, Name_Dir));
begin
if Name'Length = 0 then
Generator.Error ("Missing plugin name");
Gen.Commands.Usage;
return;
end if;
if Kind /= "ada" and Kind /= "web" then
Generator.Error ("Invalid plugin type (must be 'ada' or 'web')");
return;
end if;
if Ada.Directories.Exists (Path) then
Generator.Error ("Plugin {0} exists already", Name);
return;
end if;
if not Ada.Directories.Exists (Dir) then
Ada.Directories.Create_Directory (Dir);
end if;
Ada.Directories.Create_Directory (Path);
Generator.Set_Result_Directory (Path);
-- Create the plugin project instance and generate its dynamo.xml file.
-- The new plugin is added to the current project so that it will be referenced.
declare
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition);
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is
Plugin : Gen.Model.Projects.Project_Definition_Access;
File : constant String := Util.Files.Compose (Path, "dynamo.xml");
begin
Project.Create_Project (Name => Name,
Path => File,
Project => Plugin);
Project.Add_Module (Plugin);
Plugin.Props.Set ("license", Project.Props.Get ("license", "none"));
Plugin.Props.Set ("author", Project.Props.Get ("author", ""));
Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", ""));
Plugin.Save (File);
end Create_Plugin;
begin
Generator.Update_Project (Create_Plugin'Access);
end;
-- Generate the new plugin content.
Generator.Set_Force_Save (False);
Generator.Set_Global ("pluginName", Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE,
"create-plugin-" & Kind);
-- And save the project dynamo.xml file which now refers to the new plugin.
Generator.Set_Result_Directory (Result_Dir);
Generator.Save_Project;
exception
when Ada.Directories.Name_Error | Ada.Directories.Use_Error =>
Generator.Error ("Cannot create directory {0}", Path);
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-plugin: Create a new plugin for the current project");
Put_Line ("Usage: create-plugin [-l apache|gpl|gpl3|mit|bsd3|proprietary] "
& "[-d DIR] NAME [ada | web]");
New_Line;
Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME.");
Put_Line (" The plugin license is controlled by the -l option.");
Put_Line (" The plugin type is specified as the last argument which can be one of:");
New_Line;
Put_Line (" ada the plugin contains Ada code and a GNAT project is created");
Put_Line (" web the plugin contains XHTML, CSS, Javascript files only");
New_Line;
Put_Line (" The -d option allows to control the plugin directory name. The plugin NAME");
Put_Line (" is used by default. The plugin is created in the directory:");
Put_Line (" plugins/NAME or plugins/DIR");
New_Line;
Put_Line (" For the Ada plugin, the command generates the following files"
& " in the plugin directory:");
Put_Line (" src/<project>-<plugin>.ads");
Put_Line (" src/<project>-<plugin>-<module>.ads");
Put_Line (" src/<project>-<plugin>-<module>.adb");
end Help;
end Gen.Commands.Plugins;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
7ee2f27adf0dc298e06d9431b8dfd0e77fd36203
|
regtests/util-dates-formats-tests.ads
|
regtests/util-dates-formats-tests.ads
|
-----------------------------------------------------------------------
-- util-dates-formats-tests - Test for date formats
-- Copyright (C) 2011, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Dates.Formats.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Format (T : in out Test);
-- Test the Get_Day_Start operation.
procedure Test_Get_Day_Start (T : in out Test);
-- Test the Get_Week_Start operation.
procedure Test_Get_Week_Start (T : in out Test);
-- Test the Get_Month_Start operation.
procedure Test_Get_Month_Start (T : in out Test);
-- Test the Get_Day_End operation.
procedure Test_Get_Day_End (T : in out Test);
-- Test the Get_Week_End operation.
procedure Test_Get_Week_End (T : in out Test);
-- Test the Get_Month_End operation.
procedure Test_Get_Month_End (T : in out Test);
-- Test the Split operation.
procedure Test_Split (T : in out Test);
-- Test the Append_Date operation
procedure Test_Append_Date (T : in out Test);
-- Test the ISO8601 operations.
procedure Test_ISO8601 (T : in out Test);
end Util.Dates.Formats.Tests;
|
-----------------------------------------------------------------------
-- util-dates-formats-tests - Test for date formats
-- Copyright (C) 2011, 2013, 2014, 2015, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Dates.Formats.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Format (T : in out Test);
-- Test parsing a date using several formats and different locales.
procedure Test_Parse (T : in out Test);
-- Test the Get_Day_Start operation.
procedure Test_Get_Day_Start (T : in out Test);
-- Test the Get_Week_Start operation.
procedure Test_Get_Week_Start (T : in out Test);
-- Test the Get_Month_Start operation.
procedure Test_Get_Month_Start (T : in out Test);
-- Test the Get_Day_End operation.
procedure Test_Get_Day_End (T : in out Test);
-- Test the Get_Week_End operation.
procedure Test_Get_Week_End (T : in out Test);
-- Test the Get_Month_End operation.
procedure Test_Get_Month_End (T : in out Test);
-- Test the Split operation.
procedure Test_Split (T : in out Test);
-- Test the Append_Date operation
procedure Test_Append_Date (T : in out Test);
-- Test the ISO8601 operations.
procedure Test_ISO8601 (T : in out Test);
end Util.Dates.Formats.Tests;
|
Declare the Test_Parse procedure to test the date parsing
|
Declare the Test_Parse procedure to test the date parsing
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8a05c599c389f378048cdddd2065f7745a262734
|
src/base/files/util-files-rolling.ads
|
src/base/files/util-files-rolling.ads
|
-----------------------------------------------------------------------
-- util-files-rolling -- Rolling file manager
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Directories;
with Util.Strings.Vectors;
-- == Rolling file manager ==
-- The `Util.Files.Rolling` package provides a simple support to roll a file
-- based on some rolling policy. Such rolling is traditionally used for file
-- logs to move files to another place when they reach some size limit or when
-- some date conditions are met (such as a day change). The file manager uses
-- a file path and a pattern. The file path is used to define the default
-- or initial file. The pattern is used when rolling occurs to decide how
-- to reorganize files.
--
-- The file manager defines a triggering policy represented by `Policy_Type`.
-- It controls when the file rolling must be made.
--
-- * `No_Policy`: no policy, the rolling must be triggered manually.
-- * `Size_Policy`: size policy, the rolling is triggered when the file
-- reaches a given size.
-- * `Time_Policy`: time policy, the rolling is made when the date/time pattern
-- no longer applies to the active file.
--
-- To control how the rolling is made, the `Strategy_Type` defines the behavior
-- of the rolling.
--
-- * `Rollover_Strategy`:
-- * `Direct_Strategy`:
--
-- To use the file manager, the first step is to create an instance and configure
-- the default file, pattern, choose the triggering policy and strategy:
--
-- Manager : Util.Files.Rolling.File_Manager;
--
-- Manager.Initialize ("dynamo.log", "dynamo-%i.log",
-- Policy => (Size_Policy, 100_000),
-- Strategy => (Rollover_Strategy, 1, 10));
--
-- After the initialization, the current file is retrieved by using the
-- `Get_Current_Path` function and you should call `Is_Rollover_Necessary`
-- before writing content on the file. When it returns `True`, it means you
-- should call the `Rollover` procedure that will perform roll over according
-- to the rolling strategy.
--
package Util.Files.Rolling is
type Policy_Kind is (No_Policy, Size_Policy, Time_Policy);
type Policy_Type (Kind : Policy_Kind) is record
case Kind is
when No_Policy =>
null;
when Size_Policy =>
Size : Ada.Directories.File_Size := 100_000_000;
when Time_Policy =>
Interval : Natural := 1;
end case;
end record;
type Strategy_Kind is (Ascending_Strategy,
Descending_Strategy,
Direct_Strategy);
type Strategy_Type (Kind : Strategy_Kind) is record
case Kind is
when Ascending_Strategy | Descending_Strategy =>
Min_Index : Natural;
Max_Index : Natural;
when Direct_Strategy =>
Max_Files : Natural;
end case;
end record;
-- Format the file pattern with the date and index to produce a file path.
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Index : in Natural) return String;
type File_Manager is tagged limited private;
-- Initialize the file manager to roll the file refered by `Path` by using
-- the pattern defined in `Pattern`.
procedure Initialize (Manager : in out File_Manager;
Path : in String;
Pattern : in String;
Policy : in Policy_Type;
Strategy : in Strategy_Type);
-- Get the current path (it may or may not exist).
function Get_Current_Path (Manager : in File_Manager) return String;
-- Check if a rollover is necessary based on the rolling strategy.
function Is_Rollover_Necessary (Manager : in File_Manager) return Boolean;
-- Perform a rollover according to the strategy that was configured.
procedure Rollover (Manager : in out File_Manager);
procedure Rollover_Ascending (Manager : in out File_Manager);
procedure Rollover_Descending (Manager : in out File_Manager);
procedure Rollover_Direct (Manager : in out File_Manager);
-- Get the regex pattern to identify a file that must be purged.
-- The default is to extract the file pattern part of the file manager pattern.
function Get_Purge_Pattern (Manager : in File_Manager) return String;
private
-- Find the files that are elligible to purge in the given directory.
procedure Elligible_Files (Manager : in out File_Manager;
Path : in String;
Names : in out Util.Strings.Vectors.Vector;
First_Index : out Natural;
Last_Index : out Natural);
procedure Rename (Manager : in File_Manager;
Old : in String);
procedure Purge (Manager : in out File_Manager;
Path : in String);
type File_Manager is tagged limited record
Policy : Policy_Kind := No_Policy;
Strategy : Strategy_Kind := Ascending_Strategy;
File_Path : Unbounded_String;
Pattern : Unbounded_String;
Interval : Natural;
Cur_Index : Natural := 1;
Min_Index : Natural;
Max_Index : Natural;
Max_Files : Natural := 1;
Deadline : Ada.Calendar.Time;
Max_Size : Ada.Directories.File_Size := Ada.Directories.File_Size'Last;
end record;
end Util.Files.Rolling;
|
-----------------------------------------------------------------------
-- util-files-rolling -- Rolling file manager
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Directories;
with Util.Strings.Vectors;
-- == Rolling file manager ==
-- The `Util.Files.Rolling` package provides a simple support to roll a file
-- based on some rolling policy. Such rolling is traditionally used for file
-- logs to move files to another place when they reach some size limit or when
-- some date conditions are met (such as a day change). The file manager uses
-- a file path and a pattern. The file path is used to define the default
-- or initial file. The pattern is used when rolling occurs to decide how
-- to reorganize files.
--
-- The file manager defines a triggering policy represented by `Policy_Type`.
-- It controls when the file rolling must be made.
--
-- * `No_Policy`: no policy, the rolling must be triggered manually.
-- * `Size_Policy`: size policy, the rolling is triggered when the file
-- reaches a given size.
-- * `Time_Policy`: time policy, the rolling is made when the date/time pattern
-- no longer applies to the active file.
--
-- To control how the rolling is made, the `Strategy_Type` defines the behavior
-- of the rolling.
--
-- * `Rollover_Strategy`:
-- * `Direct_Strategy`:
--
-- To use the file manager, the first step is to create an instance and configure
-- the default file, pattern, choose the triggering policy and strategy:
--
-- Manager : Util.Files.Rolling.File_Manager;
--
-- Manager.Initialize ("dynamo.log", "dynamo-%i.log",
-- Policy => (Size_Policy, 100_000),
-- Strategy => (Rollover_Strategy, 1, 10));
--
-- After the initialization, the current file is retrieved by using the
-- `Get_Current_Path` function and you should call `Is_Rollover_Necessary`
-- before writing content on the file. When it returns `True`, it means you
-- should call the `Rollover` procedure that will perform roll over according
-- to the rolling strategy.
--
package Util.Files.Rolling is
type Policy_Kind is (No_Policy, Size_Policy, Time_Policy);
type Policy_Type (Kind : Policy_Kind) is record
case Kind is
when No_Policy =>
null;
when Size_Policy =>
Size : Ada.Directories.File_Size := 100_000_000;
when Time_Policy =>
Interval : Natural := 1;
end case;
end record;
type Strategy_Kind is (Ascending_Strategy,
Descending_Strategy,
Direct_Strategy);
type Strategy_Type (Kind : Strategy_Kind) is record
case Kind is
when Ascending_Strategy | Descending_Strategy =>
Min_Index : Natural;
Max_Index : Natural;
when Direct_Strategy =>
Max_Files : Natural;
end case;
end record;
-- Format the file pattern with the date and index to produce a file path.
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Index : in Natural) return String;
type File_Manager is tagged limited private;
-- Initialize the file manager to roll the file refered by `Path` by using
-- the pattern defined in `Pattern`.
procedure Initialize (Manager : in out File_Manager;
Path : in String;
Pattern : in String;
Policy : in Policy_Type;
Strategy : in Strategy_Type);
-- Get the current path (it may or may not exist).
function Get_Current_Path (Manager : in File_Manager) return String;
-- Check if a rollover is necessary based on the rolling strategy.
function Is_Rollover_Necessary (Manager : in File_Manager) return Boolean;
-- Perform a rollover according to the strategy that was configured.
procedure Rollover (Manager : in out File_Manager);
procedure Rollover_Ascending (Manager : in out File_Manager);
procedure Rollover_Descending (Manager : in out File_Manager);
procedure Rollover_Direct (Manager : in out File_Manager);
-- Get the regex pattern to identify a file that must be purged.
-- The default is to extract the file pattern part of the file manager pattern.
function Get_Purge_Pattern (Manager : in File_Manager) return String;
private
-- Find the files that are elligible to purge in the given directory.
procedure Elligible_Files (Manager : in out File_Manager;
Path : in String;
Names : in out Util.Strings.Vectors.Vector;
First_Index : out Natural;
Last_Index : out Natural);
procedure Rename (Manager : in File_Manager;
Old : in String);
type File_Manager is tagged limited record
Policy : Policy_Kind := No_Policy;
Strategy : Strategy_Kind := Ascending_Strategy;
File_Path : Unbounded_String;
Pattern : Unbounded_String;
Interval : Natural;
Cur_Index : Natural := 1;
Min_Index : Natural;
Max_Index : Natural;
Max_Files : Natural := 1;
Deadline : Ada.Calendar.Time;
Max_Size : Ada.Directories.File_Size := Ada.Directories.File_Size'Last;
end record;
end Util.Files.Rolling;
|
Remove unused Purge procedure
|
Remove unused Purge procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
00db14c6480667a101109222e97a408061a81ec7
|
mat/src/memory/mat-memory-targets.adb
|
mat/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
protected body Memory_Allocator is
-- ------------------------------
-- 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
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
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
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
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
Old_Slot : Allocation;
Pos : Allocation_Cursor;
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
begin
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
begin
if Old_Addr /= 0 then
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;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
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;
-- ------------------------------
-- Find from the memory map the memory slots whose address intersects
-- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if
-- it does not already contains the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Into);
end Find;
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;
-- ------------------------------
-- 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;
-- ------------------------------
-- Find from the memory map the memory slots whose address intersects
-- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if
-- it does not already contains the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- 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
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
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
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
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
Old_Slot : Allocation;
Pos : Allocation_Cursor;
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
begin
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
begin
if Old_Addr /= 0 then
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;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
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;
-- ------------------------------
-- Find from the memory map the memory slots whose address intersects
-- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if
-- it does not already contains the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Into);
end Find;
end Memory_Allocator;
end MAT.Memory.Targets;
|
Implement the Find procedure on the Target_Memory object
|
Implement the Find procedure on the Target_Memory object
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
17d67029b1289dc037e0d23a4c7b6d339b8bdaee
|
src/gen-commands-docs.adb
|
src/gen-commands-docs.adb
|
-----------------------------------------------------------------------
-- gen-commands-docs -- Extract and generate documentation for the project
-- Copyright (C) 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Ada.Text_IO;
with Gen.Artifacts.Docs;
with Gen.Model.Packages;
package body Gen.Commands.Docs is
use GNAT.Command_Line;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, Args);
Doc : Gen.Artifacts.Docs.Artifact;
M : Gen.Model.Packages.Model_Definition;
Arg1 : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Fmt : Gen.Artifacts.Docs.Doc_Format := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE;
begin
Generator.Read_Project ("dynamo.xml", False);
if Arg1'Length = 0 then
Generator.Error ("Missing target directory");
return;
elsif Arg1 (Arg1'First) /= '-' then
if Arg2'Length /= 0 then
Generator.Error ("Invalid markup option " & Arg1);
return;
end if;
-- Setup the target directory where the distribution is created.
Generator.Set_Result_Directory (Arg1);
else
if Arg1 = "-markdown" then
Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN;
elsif Arg1 = "-google" then
Fmt := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE;
else
Generator.Error ("Invalid markup option " & Arg1);
return;
end if;
if Arg2'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Arg2);
end if;
Doc.Set_Format (Fmt);
Doc.Prepare (M, Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc [-markdown|-google] target-dir");
New_Line;
Put_Line (" Extract the documentation from the project source files and generate the");
Put_Line (" project documentation. The following files are scanned:");
Put_Line (" - Ada specifications (src/*.ads)");
Put_Line (" - XML configuration files (config/*.xml)");
Put_Line (" - XML database model files (db/*.xml)");
end Help;
end Gen.Commands.Docs;
|
-----------------------------------------------------------------------
-- gen-commands-docs -- Extract and generate documentation for the project
-- Copyright (C) 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Ada.Text_IO;
with Gen.Artifacts.Docs;
with Gen.Model.Packages;
package body Gen.Commands.Docs is
use GNAT.Command_Line;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, Args);
Doc : Gen.Artifacts.Docs.Artifact;
M : Gen.Model.Packages.Model_Definition;
Arg1 : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Footer : Boolean := True;
Fmt : Gen.Artifacts.Docs.Doc_Format := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE;
begin
Generator.Read_Project ("dynamo.xml", False);
if Arg1'Length = 0 then
Generator.Error ("Missing target directory");
return;
elsif Arg1 (Arg1'First) /= '-' then
if Arg2'Length /= 0 then
Generator.Error ("Invalid markup option " & Arg1);
return;
end if;
-- Setup the target directory where the distribution is created.
Generator.Set_Result_Directory (Arg1);
else
if Arg1 = "-markdown" then
Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN;
elsif Arg1 = "-google" then
Fmt := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE;
elsif Arg1 = "-pandoc" then
Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN;
Footer := False;
else
Generator.Error ("Invalid markup option " & Arg1);
return;
end if;
if Arg2'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Arg2);
end if;
Doc.Set_Format (Fmt, Footer);
Doc.Prepare (M, Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc [-markdown|-google|-pandoc] target-dir");
New_Line;
Put_Line (" Extract the documentation from the project source files and generate the");
Put_Line (" project documentation. The following files are scanned:");
Put_Line (" - Ada specifications (src/*.ads)");
Put_Line (" - XML configuration files (config/*.xml)");
Put_Line (" - XML database model files (db/*.xml)");
end Help;
end Gen.Commands.Docs;
|
Add the -pandoc option to generate documentation without footer link
|
Add the -pandoc option to generate documentation without footer link
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
dc36a1512b93204157f2c7e4b21e2ad1eb89e3de
|
src/natools-s_expressions-encodings.adb
|
src/natools-s_expressions-encodings.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2013, 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.S_Expressions.Encodings is
--------------------------
-- Hexadecimal Decoding --
--------------------------
function Is_Hex_Digit (Value : in Octet) return Boolean is
begin
case Value is
when Digit_0 .. Digit_9 => return True;
when Lower_A .. Lower_F => return True;
when Upper_A .. Upper_F => return True;
when others => return False;
end case;
end Is_Hex_Digit;
function Decode_Hex (Value : in Octet) return Octet is
begin
case Value is
when Digit_0 .. Digit_9 => return Value - Digit_0;
when Lower_A .. Lower_F => return Value - Lower_A + 10;
when Upper_A .. Upper_F => return Value - Upper_A + 10;
when others => raise Constraint_Error;
end case;
end Decode_Hex;
function Decode_Hex (High, Low : in Octet) return Octet is
begin
return Decode_Hex (High) * 16 + Decode_Hex (Low);
end Decode_Hex;
function Decode_Hex (Data : in Atom) return Atom is
Length : Count := 0;
begin
for I in Data'Range loop
if Is_Hex_Digit (Data (I)) then
Length := Length + 1;
end if;
end loop;
Length := (Length + 1) / 2;
return Result : Atom (0 .. Length - 1) do
declare
O : Offset := Result'First;
High : Octet := 0;
Has_High : Boolean := False;
begin
for I in Data'Range loop
if Is_Hex_Digit (Data (I)) then
if Has_High then
Result (O) := Decode_Hex (High, Data (I));
O := O + 1;
High := 0;
Has_High := False;
else
High := Data (I);
Has_High := True;
end if;
end if;
end loop;
if Has_High then
Result (O) := Decode_Hex (High, Digit_0);
O := O + 1;
end if;
pragma Assert (O - 1 = Result'Last);
end;
end return;
end Decode_Hex;
--------------------------
-- Hexadecimal Encoding --
--------------------------
function Encode_Hex (Value : in Octet; Casing : in Hex_Casing)
return Octet is
begin
case Value is
when 0 .. 9 =>
return Digit_0 + Value;
when 10 .. 15 =>
case Casing is
when Upper => return Upper_A + Value - 10;
when Lower => return Lower_A + Value - 10;
end case;
when others =>
raise Constraint_Error;
end case;
end Encode_Hex;
procedure Encode_Hex
(Value : in Octet;
Casing : in Hex_Casing;
High, Low : out Octet) is
begin
High := Encode_Hex (Value / 2**4 mod 2**4, Casing);
Low := Encode_Hex (Value mod 2**4, Casing);
end Encode_Hex;
function Encode_Hex (Data : in Atom; Casing : in Hex_Casing) return Atom is
Result : Atom (0 .. Data'Length * 2 - 1);
Cursor : Offset := Result'First;
begin
for I in Data'Range loop
Encode_Hex (Data (I), Casing, Result (Cursor), Result (Cursor + 1));
Cursor := Cursor + 2;
end loop;
pragma Assert (Cursor = Result'Last + 1);
return Result;
end Encode_Hex;
----------------------
-- Base-64 Decoding --
----------------------
function Is_Base64_Digit (Value : in Octet) return Boolean is
begin
return Value in Digit_0 .. Digit_9
or Value in Lower_A .. Lower_Z
or Value in Upper_A .. Upper_Z
or Value = Plus
or Value = Slash;
end Is_Base64_Digit;
function Decode_Base64 (Value : in Octet) return Octet is
begin
case Value is
when Upper_A .. Upper_Z => return Value - Upper_A + 0;
when Lower_A .. Lower_Z => return Value - Lower_A + 26;
when Digit_0 .. Digit_9 => return Value - Digit_0 + 52;
when Plus => return 62;
when Slash => return 63;
when others => raise Constraint_Error;
end case;
end Decode_Base64;
function Decode_Base64 (A, B : in Octet) return Atom is
VA : constant Octet := Decode_Base64 (A);
VB : constant Octet := Decode_Base64 (B);
begin
return (0 => VA * 2**2 + VB / 2**4);
end Decode_Base64;
function Decode_Base64 (A, B, C : in Octet) return Atom is
VA : constant Octet := Decode_Base64 (A);
VB : constant Octet := Decode_Base64 (B);
VC : constant Octet := Decode_Base64 (C);
begin
return (0 => VA * 2**2 + VB / 2**4,
1 => VB * 2**4 + VC / 2**2);
end Decode_Base64;
function Decode_Base64 (A, B, C, D : in Octet) return Atom is
VA : constant Octet := Decode_Base64 (A);
VB : constant Octet := Decode_Base64 (B);
VC : constant Octet := Decode_Base64 (C);
VD : constant Octet := Decode_Base64 (D);
begin
return (0 => VA * 2**2 + VB / 2**4,
1 => VB * 2**4 + VC / 2**2,
2 => VC * 2**6 + VD);
end Decode_Base64;
function Decode_Base64 (Data : in Atom) return Atom is
Length : Count := 0;
begin
for I in Data'Range loop
if Is_Base64_Digit (Data (I)) then
Length := Length + 1;
end if;
end loop;
declare
Chunks : constant Count := Length / 4;
Remains : constant Count := Length mod 4;
begin
if Remains >= 2 then
Length := Chunks * 3 + Remains - 1;
else
Length := Chunks * 3;
end if;
end;
return Result : Atom (0 .. Length - 1) do
declare
O : Count := Result'First;
Buffer : Atom (0 .. 3);
Accumulated : Count := 0;
begin
for I in Data'Range loop
if Is_Base64_Digit (Data (I)) then
Buffer (Accumulated) := Data (I);
Accumulated := Accumulated + 1;
if Accumulated = 4 then
Result (O .. O + 2) := Decode_Base64 (Buffer (0),
Buffer (1),
Buffer (2),
Buffer (3));
O := O + 3;
Accumulated := 0;
end if;
end if;
end loop;
if Accumulated = 2 then
Result (O .. O) := Decode_Base64 (Buffer (0), Buffer (1));
O := O + 1;
elsif Accumulated = 3 then
Result (O .. O + 1) := Decode_Base64 (Buffer (0),
Buffer (1),
Buffer (2));
O := O + 2;
end if;
pragma Assert (O = Length);
end;
end return;
end Decode_Base64;
----------------------
-- Base-64 Encoding --
----------------------
function Encode_Base64 (Value : in Octet) return Octet is
begin
case Value is
when 0 .. 25 =>
return Upper_A + Value;
when 26 .. 51 =>
return Lower_A + Value - 26;
when 52 .. 61 =>
return Digit_0 + Value - 52;
when 62 =>
return Plus;
when 63 =>
return Slash;
when others =>
raise Constraint_Error;
end case;
end Encode_Base64;
procedure Encode_Base64 (Output : out Atom; A : in Octet) is
begin
Output (Output'First + 0) := Encode_Base64 (A / 2**2 mod 2**6);
Output (Output'First + 1) := Encode_Base64 (A * 2**4 mod 2**6);
Output (Output'First + 2) := Base64_Filler;
Output (Output'First + 3) := Base64_Filler;
end Encode_Base64;
procedure Encode_Base64 (Output : out Atom; A, B : in Octet) is
begin
Output (Output'First + 0) := Encode_Base64 (A / 2**2 mod 2**6);
Output (Output'First + 1) := Encode_Base64 ((A * 2**4 + B / 2**4)
mod 2**6);
Output (Output'First + 2) := Encode_Base64 (B * 2**2 mod 2**6);
Output (Output'First + 3) := Base64_Filler;
end Encode_Base64;
procedure Encode_Base64 (Output : out Atom; A, B, C : in Octet) is
begin
Output (Output'First + 0) := Encode_Base64 (A / 2**2 mod 2**6);
Output (Output'First + 1) := Encode_Base64 ((A * 2**4 + B / 2**4)
mod 2**6);
Output (Output'First + 2) := Encode_Base64 ((B * 2**2 + C / 2**6)
mod 2**6);
Output (Output'First + 3) := Encode_Base64 (C mod 2**6);
end Encode_Base64;
function Encode_Base64 (Data : in Atom) return Atom is
Chunks : constant Count := (Data'Length + 2) / 3;
Result : Atom (0 .. Chunks * 4 - 1);
Cursor : Offset := Result'First;
I : Offset := Data'First;
begin
while I in Data'Range loop
if I + 2 in Data'Range then
Encode_Base64
(Result (Cursor .. Cursor + 3),
Data (I),
Data (I + 1),
Data (I + 2));
I := I + 3;
elsif I + 1 in Data'Range then
Encode_Base64
(Result (Cursor .. Cursor + 3),
Data (I),
Data (I + 1));
I := I + 2;
else
Encode_Base64
(Result (Cursor .. Cursor + 3),
Data (I));
I := I + 1;
end if;
Cursor := Cursor + 4;
end loop;
return Result;
end Encode_Base64;
---------------------------------
-- Base-64 with other charsets --
---------------------------------
function Decode_Base64 (Data : in Atom; Digit_62, Digit_63 : in Octet)
return Atom
is
Recoded : Atom := Data;
begin
for I in Recoded'Range loop
if Recoded (I) = Digit_62 then
Recoded (I) := Plus;
elsif Recoded (I) = Digit_63 then
Recoded (I) := Slash;
end if;
end loop;
return Decode_Base64 (Recoded);
end Decode_Base64;
function Encode_Base64 (Data : in Atom; Digit_62, Digit_63 : in Octet)
return Atom
is
Result : Atom := Encode_Base64 (Data);
Last : Count := Result'Last;
begin
for I in Result'Range loop
if Result (I) = Plus then
Result (I) := Digit_62;
elsif Result (I) = Slash then
Result (I) := Digit_63;
elsif Result (I) = Base64_Filler then
for J in I + 1 .. Result'Last loop
pragma Assert (Result (J) = Base64_Filler);
end loop;
Last := I - 1;
exit;
end if;
end loop;
return Result (Result'First .. Last);
end Encode_Base64;
function Encode_Base64
(Data : in Atom;
Digit_62, Digit_63, Padding : in Octet)
return Atom
is
Result : Atom := Encode_Base64 (Data);
begin
for I in Result'Range loop
if Result (I) = Plus then
Result (I) := Digit_62;
elsif Result (I) = Slash then
Result (I) := Digit_63;
elsif Result (I) = Base64_Filler then
Result (I) := Padding;
end if;
end loop;
return Result;
end Encode_Base64;
end Natools.S_Expressions.Encodings;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013, 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.S_Expressions.Encodings is
--------------------------
-- Hexadecimal Decoding --
--------------------------
function Is_Hex_Digit (Value : in Octet) return Boolean is
begin
case Value is
when Digit_0 .. Digit_9 => return True;
when Lower_A .. Lower_F => return True;
when Upper_A .. Upper_F => return True;
when others => return False;
end case;
end Is_Hex_Digit;
function Decode_Hex (Value : in Octet) return Octet is
begin
case Value is
when Digit_0 .. Digit_9 => return Value - Digit_0;
when Lower_A .. Lower_F => return Value - Lower_A + 10;
when Upper_A .. Upper_F => return Value - Upper_A + 10;
when others => raise Constraint_Error;
end case;
end Decode_Hex;
function Decode_Hex (High, Low : in Octet) return Octet is
begin
return Decode_Hex (High) * 16 + Decode_Hex (Low);
end Decode_Hex;
function Decode_Hex (Data : in Atom) return Atom is
Length : Count := 0;
begin
for I in Data'Range loop
if Is_Hex_Digit (Data (I)) then
Length := Length + 1;
end if;
end loop;
Length := (Length + 1) / 2;
return Result : Atom (0 .. Length - 1) do
declare
O : Offset := Result'First;
High : Octet := 0;
Has_High : Boolean := False;
begin
for I in Data'Range loop
if Is_Hex_Digit (Data (I)) then
if Has_High then
Result (O) := Decode_Hex (High, Data (I));
O := O + 1;
High := 0;
Has_High := False;
else
High := Data (I);
Has_High := True;
end if;
end if;
end loop;
if Has_High then
Result (O) := Decode_Hex (High, Digit_0);
O := O + 1;
end if;
pragma Assert (O - 1 = Result'Last);
end;
end return;
end Decode_Hex;
--------------------------
-- Hexadecimal Encoding --
--------------------------
function Encode_Hex (Value : in Octet; Casing : in Hex_Casing)
return Octet is
begin
case Value is
when 0 .. 9 =>
return Digit_0 + Value;
when 10 .. 15 =>
case Casing is
when Upper => return Upper_A + Value - 10;
when Lower => return Lower_A + Value - 10;
end case;
when others =>
raise Constraint_Error;
end case;
end Encode_Hex;
procedure Encode_Hex
(Value : in Octet;
Casing : in Hex_Casing;
High, Low : out Octet) is
begin
High := Encode_Hex (Value / 2**4 mod 2**4, Casing);
Low := Encode_Hex (Value mod 2**4, Casing);
end Encode_Hex;
function Encode_Hex (Data : in Atom; Casing : in Hex_Casing) return Atom is
Result : Atom (0 .. Data'Length * 2 - 1);
Cursor : Offset := Result'First;
begin
for I in Data'Range loop
Encode_Hex (Data (I), Casing, Result (Cursor), Result (Cursor + 1));
Cursor := Cursor + 2;
end loop;
pragma Assert (Cursor = Result'Last + 1);
return Result;
end Encode_Hex;
----------------------
-- Base-64 Decoding --
----------------------
function Is_Base64_Digit (Value : in Octet) return Boolean is
begin
return Value in Digit_0 .. Digit_9
or Value in Lower_A .. Lower_Z
or Value in Upper_A .. Upper_Z
or Value = Plus
or Value = Slash;
end Is_Base64_Digit;
function Decode_Base64 (Value : in Octet) return Octet is
begin
case Value is
when Upper_A .. Upper_Z => return Value - Upper_A + 0;
when Lower_A .. Lower_Z => return Value - Lower_A + 26;
when Digit_0 .. Digit_9 => return Value - Digit_0 + 52;
when Plus => return 62;
when Slash => return 63;
when others => raise Constraint_Error;
end case;
end Decode_Base64;
function Decode_Base64 (A, B : in Octet) return Atom is
VA : constant Octet := Decode_Base64 (A);
VB : constant Octet := Decode_Base64 (B);
begin
return (0 => VA * 2**2 + VB / 2**4);
end Decode_Base64;
function Decode_Base64 (A, B, C : in Octet) return Atom is
VA : constant Octet := Decode_Base64 (A);
VB : constant Octet := Decode_Base64 (B);
VC : constant Octet := Decode_Base64 (C);
begin
return (0 => VA * 2**2 + VB / 2**4,
1 => VB * 2**4 + VC / 2**2);
end Decode_Base64;
function Decode_Base64 (A, B, C, D : in Octet) return Atom is
VA : constant Octet := Decode_Base64 (A);
VB : constant Octet := Decode_Base64 (B);
VC : constant Octet := Decode_Base64 (C);
VD : constant Octet := Decode_Base64 (D);
begin
return (0 => VA * 2**2 + VB / 2**4,
1 => VB * 2**4 + VC / 2**2,
2 => VC * 2**6 + VD);
end Decode_Base64;
function Decode_Base64 (Data : in Atom) return Atom is
Length : Count := 0;
begin
for I in Data'Range loop
if Is_Base64_Digit (Data (I)) then
Length := Length + 1;
end if;
end loop;
declare
Chunks : constant Count := Length / 4;
Remains : constant Count := Length mod 4;
begin
if Remains >= 2 then
Length := Chunks * 3 + Remains - 1;
else
Length := Chunks * 3;
end if;
end;
return Result : Atom (0 .. Length - 1) do
declare
O : Count := Result'First;
Buffer : Atom (0 .. 3);
Accumulated : Count := 0;
begin
for I in Data'Range loop
if Is_Base64_Digit (Data (I)) then
Buffer (Accumulated) := Data (I);
Accumulated := Accumulated + 1;
if Accumulated = 4 then
Result (O .. O + 2) := Decode_Base64 (Buffer (0),
Buffer (1),
Buffer (2),
Buffer (3));
O := O + 3;
Accumulated := 0;
end if;
end if;
end loop;
if Accumulated = 2 then
Result (O .. O) := Decode_Base64 (Buffer (0), Buffer (1));
O := O + 1;
elsif Accumulated = 3 then
Result (O .. O + 1) := Decode_Base64 (Buffer (0),
Buffer (1),
Buffer (2));
O := O + 2;
end if;
pragma Assert (O = Length);
end;
end return;
end Decode_Base64;
----------------------
-- Base-64 Encoding --
----------------------
function Encode_Base64 (Value : in Octet) return Octet is
begin
case Value is
when 0 .. 25 =>
return Upper_A + Value;
when 26 .. 51 =>
return Lower_A + Value - 26;
when 52 .. 61 =>
return Digit_0 + Value - 52;
when 62 =>
return Plus;
when 63 =>
return Slash;
when others =>
raise Constraint_Error;
end case;
end Encode_Base64;
procedure Encode_Base64 (Output : out Atom; A : in Octet) is
begin
Output (Output'First + 0) := Encode_Base64 (A / 2**2 mod 2**6);
Output (Output'First + 1) := Encode_Base64 (A * 2**4 mod 2**6);
Output (Output'First + 2) := Base64_Filler;
Output (Output'First + 3) := Base64_Filler;
end Encode_Base64;
procedure Encode_Base64 (Output : out Atom; A, B : in Octet) is
begin
Output (Output'First + 0) := Encode_Base64 (A / 2**2 mod 2**6);
Output (Output'First + 1) := Encode_Base64 ((A * 2**4 + B / 2**4)
mod 2**6);
Output (Output'First + 2) := Encode_Base64 (B * 2**2 mod 2**6);
Output (Output'First + 3) := Base64_Filler;
end Encode_Base64;
procedure Encode_Base64 (Output : out Atom; A, B, C : in Octet) is
begin
Output (Output'First + 0) := Encode_Base64 (A / 2**2 mod 2**6);
Output (Output'First + 1) := Encode_Base64 ((A * 2**4 + B / 2**4)
mod 2**6);
Output (Output'First + 2) := Encode_Base64 ((B * 2**2 + C / 2**6)
mod 2**6);
Output (Output'First + 3) := Encode_Base64 (C mod 2**6);
end Encode_Base64;
function Encode_Base64 (Data : in Atom) return Atom is
Chunks : constant Count := (Data'Length + 2) / 3;
Result : Atom (0 .. Chunks * 4 - 1);
Cursor : Offset := Result'First;
I : Offset := Data'First;
begin
while I in Data'Range loop
if I + 2 in Data'Range then
Encode_Base64
(Result (Cursor .. Cursor + 3),
Data (I),
Data (I + 1),
Data (I + 2));
I := I + 3;
elsif I + 1 in Data'Range then
Encode_Base64
(Result (Cursor .. Cursor + 3),
Data (I),
Data (I + 1));
I := I + 2;
else
Encode_Base64
(Result (Cursor .. Cursor + 3),
Data (I));
I := I + 1;
end if;
Cursor := Cursor + 4;
end loop;
return Result;
end Encode_Base64;
---------------------------------
-- Base-64 with other charsets --
---------------------------------
function Decode_Base64 (Data : in Atom; Digit_62, Digit_63 : in Octet)
return Atom
is
Recoded : Atom := Data;
begin
for I in Recoded'Range loop
if Recoded (I) = Digit_62 then
Recoded (I) := Plus;
elsif Recoded (I) = Digit_63 then
Recoded (I) := Slash;
end if;
end loop;
return Decode_Base64 (Recoded);
end Decode_Base64;
function Encode_Base64 (Data : in Atom; Digit_62, Digit_63 : in Octet)
return Atom
is
Result : Atom := Encode_Base64 (Data);
Last : Count := Result'Last;
begin
for I in Result'Range loop
if Result (I) = Plus then
Result (I) := Digit_62;
elsif Result (I) = Slash then
Result (I) := Digit_63;
elsif Result (I) = Base64_Filler then
pragma Assert (Result (I + 1 .. Result'Last)
= (I + 1 .. Result'Last => Base64_Filler));
Last := I - 1;
exit;
end if;
end loop;
return Result (Result'First .. Last);
end Encode_Base64;
function Encode_Base64
(Data : in Atom;
Digit_62, Digit_63, Padding : in Octet)
return Atom
is
Result : Atom := Encode_Base64 (Data);
begin
for I in Result'Range loop
if Result (I) = Plus then
Result (I) := Digit_62;
elsif Result (I) = Slash then
Result (I) := Digit_63;
elsif Result (I) = Base64_Filler then
Result (I) := Padding;
end if;
end loop;
return Result;
end Encode_Base64;
end Natools.S_Expressions.Encodings;
|
replace assert-in-loop by asserting a slice comparison
|
s_expressions-encodings: replace assert-in-loop by asserting a slice comparison
|
Ada
|
isc
|
faelys/natools
|
897b3bf0a5e94c3e74932cdb18c98e6586e02eac
|
src/orka/implementation/orka-timers.adb
|
src/orka/implementation/orka-timers.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
package body Orka.Timers is
function Create_Timer return Timer is
begin
return Timer'(others => <>);
end Create_Timer;
use GL.Types;
function Get_Duration (Value : UInt64) return Duration is
Seconds : constant UInt64 := Value / 1e9;
Nanoseconds : constant UInt64 := Value - Seconds * 1e9;
begin
return Duration (Seconds) + Duration (Nanoseconds) / 1e9;
end Get_Duration;
procedure Start (Object : in out Timer) is
use GL.Objects.Queries;
begin
if Object.State = Waiting and then Object.Query_Stop.Result_Available then
declare
Stop_Time : constant UInt64 := Object.Query_Stop.Result;
Start_Time : constant UInt64 := Object.Query_Start.Result;
begin
if Stop_Time > Start_Time then
Object.GPU_Duration := Get_Duration (Stop_Time - Start_Time);
end if;
end;
Object.State := Idle;
end if;
if Object.State = Idle then
Object.CPU_Start := Get_Current_Time;
Object.Query_Start.Record_Current_Time;
Object.State := Busy;
end if;
end Start;
procedure Stop (Object : in out Timer) is
use GL.Objects.Queries;
begin
if Object.State = Busy then
declare
Current_Time : Long := Get_Current_Time;
begin
if Current_Time > Object.CPU_Start then
Object.CPU_Duration := Get_Duration (UInt64 (Current_Time - Object.CPU_Start));
end if;
end;
Object.Query_Stop.Record_Current_Time;
Object.State := Waiting;
end if;
end Stop;
function CPU_Duration (Object : Timer) return Duration is (Object.CPU_Duration);
function GPU_Duration (Object : Timer) return Duration is (Object.GPU_Duration);
end Orka.Timers;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
package body Orka.Timers is
function Create_Timer return Timer is
begin
return Timer'(others => <>);
end Create_Timer;
use GL.Types;
function Get_Duration (Value : UInt64) return Duration is
Seconds : constant UInt64 := Value / 1e9;
Nanoseconds : constant UInt64 := Value - Seconds * 1e9;
begin
return Duration (Seconds) + Duration (Nanoseconds) / 1e9;
end Get_Duration;
procedure Start (Object : in out Timer) is
use GL.Objects.Queries;
begin
if Object.State = Waiting and then Object.Query_Stop.Result_Available then
declare
Stop_Time : constant UInt64 := Object.Query_Stop.Result;
Start_Time : constant UInt64 := Object.Query_Start.Result;
begin
if Stop_Time > Start_Time then
Object.GPU_Duration := Get_Duration (Stop_Time - Start_Time);
end if;
end;
Object.State := Idle;
end if;
if Object.State = Idle then
Object.CPU_Start := Get_Current_Time;
Object.Query_Start.Record_Current_Time;
Object.State := Busy;
end if;
end Start;
procedure Stop (Object : in out Timer) is
use GL.Objects.Queries;
begin
if Object.State = Busy then
declare
Current_Time : constant Long := Get_Current_Time;
begin
if Current_Time > Object.CPU_Start then
Object.CPU_Duration := Get_Duration (UInt64 (Current_Time - Object.CPU_Start));
end if;
end;
Object.Query_Stop.Record_Current_Time;
Object.State := Waiting;
end if;
end Stop;
function CPU_Duration (Object : Timer) return Duration is (Object.CPU_Duration);
function GPU_Duration (Object : Timer) return Duration is (Object.GPU_Duration);
end Orka.Timers;
|
Make some variables constant
|
orka: Make some variables constant
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
90e1f9a5692927b533da78b6154f77b7aa4795bc
|
src/el-variables.adb
|
src/el-variables.adb
|
-----------------------------------------------------------------------
-- EL.Variables -- Variable mapper
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body EL.Variables is
-- ------------------------------
-- Get the Value_Expression that corresponds to the given variable name.
-- ------------------------------
function Get_Variable (Mapper : in Variable_Mapper'Class;
Name : in Unbounded_String)
return EL.Expressions.Value_Expression is
begin
return EL.Expressions.Create_Expression (Mapper.Get_Variable (Name));
end Get_Variable;
-- ------------------------------
-- Set the variable to the given value expression.
-- ------------------------------
procedure Set_Variable (Mapper : in out Variable_Mapper'Class;
Name : in Unbounded_String;
Value : in EL.Expressions.Value_Expression) is
begin
Mapper.Set_Variable (Name, EL.Expressions.Expression (Value));
end Set_Variable;
end EL.Variables;
|
-----------------------------------------------------------------------
-- EL.Variables -- Variable mapper
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body EL.Variables is
-- ------------------------------
-- Get the Value_Expression that corresponds to the given variable name.
-- ------------------------------
function Get_Variable (Mapper : in Variable_Mapper'Class;
Name : in Unbounded_String)
return EL.Expressions.Value_Expression is
VE : constant EL.Expressions.Expression := Mapper.Get_Variable (Name);
begin
return EL.Expressions.Create_Expression (VE);
end Get_Variable;
-- ------------------------------
-- Set the variable to the given value expression.
-- ------------------------------
procedure Set_Variable (Mapper : in out Variable_Mapper'Class;
Name : in Unbounded_String;
Value : in EL.Expressions.Value_Expression) is
begin
Mapper.Set_Variable (Name, EL.Expressions.Expression (Value));
end Set_Variable;
end EL.Variables;
|
Fix compilation with gcc 4.7
|
Fix compilation with gcc 4.7
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
0946a63597ad29451c9a6244813ce485513b6710
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- with EL.Functions;
limited with Security.Controllers;
limited with Security.Contexts;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Abstract_Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Role_Type) return Boolean is abstract;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Abstract_Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Abstract_Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_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 Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Abstract_Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Role_Type) return Boolean is abstract;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Abstract_Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Abstract_Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_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 Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
Document the permission and principal
|
Document the permission and principal
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
bfbb9e6db98a082266561d4225ae80842580adad
|
src/util-properties-json.adb
|
src/util-properties-json.adb
|
-----------------------------------------------------------------------
-- util-properties-json -- read json files into properties
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.JSON;
with Util.Stacks;
with Util.Beans.Objects;
package body Util.Properties.JSON is
type Natural_Access is access all Natural;
package Length_Stack is new Util.Stacks (Element_Type => Natural,
Element_Type_Access => Natural_Access);
type Parser is new Util.Serialize.IO.JSON.Parser with record
Base_Name : Ada.Strings.Unbounded.Unbounded_String;
Lengths : Length_Stack.Stack;
Separator : Ada.Strings.Unbounded.Unbounded_String;
Separator_Length : Natural;
end record;
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String);
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String) is
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Append (Handler.Base_Name, Name);
Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator);
Length_Stack.Push (Handler.Lengths);
Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length;
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name);
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Delete (Handler.Base_Name,
Len - Name'Length - Handler.Separator_Length + 1, Len);
end if;
end Finish_Object;
-- -----------------------
-- Parse the JSON content and put the flattened content in the property manager.
-- -----------------------
procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class;
Content : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with null record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Parse_String (Content);
end Parse_JSON;
-- -----------------------
-- Read the JSON file into the property manager.
-- The JSON content is flatten into Flatten the JSON content and add the properties.
-- -----------------------
procedure Read_JSON (Manager : in out Util.Properties.Manager'Class;
Path : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with null record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Parse (Path);
end Read_JSON;
end Util.Properties.JSON;
|
-----------------------------------------------------------------------
-- util-properties-json -- read json files into properties
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.JSON;
with Util.Stacks;
with Util.Beans.Objects;
package body Util.Properties.JSON is
type Natural_Access is access all Natural;
package Length_Stack is new Util.Stacks (Element_Type => Natural,
Element_Type_Access => Natural_Access);
type Parser is new Util.Serialize.IO.JSON.Parser with record
Base_Name : Ada.Strings.Unbounded.Unbounded_String;
Lengths : Length_Stack.Stack;
Separator : Ada.Strings.Unbounded.Unbounded_String;
Separator_Length : Natural;
end record;
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String);
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String) is
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Append (Handler.Base_Name, Name);
Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator);
Length_Stack.Push (Handler.Lengths);
Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length;
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name);
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Delete (Handler.Base_Name,
Len - Name'Length - Handler.Separator_Length + 1, Len);
end if;
end Finish_Object;
-- -----------------------
-- Parse the JSON content and put the flattened content in the property manager.
-- -----------------------
procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class;
Content : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with null record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Parse_String (Content);
if P.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Parse_JSON;
-- -----------------------
-- Read the JSON file into the property manager.
-- The JSON content is flatten into Flatten the JSON content and add the properties.
-- -----------------------
procedure Read_JSON (Manager : in out Util.Properties.Manager'Class;
Path : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with null record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Parse (Path);
if P.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Read_JSON;
end Util.Properties.JSON;
|
Raise a Parse_Error exception if there is an error while parsing the JSON content
|
Raise a Parse_Error exception if there is an error while parsing the JSON content
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e73c08a55c0773889273199062e9ac179e253d81
|
src/wiki-parsers-html.adb
|
src/wiki-parsers-html.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Wiki.Helpers;
with Wiki.Parsers.Html.Entities;
package body Wiki.Parsers.Html is
-- Parse an HTML attribute
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String);
-- Parse a HTML/XML comment to strip it.
procedure Parse_Comment (P : in out Parser);
-- Parse a simple DOCTYPE declaration and ignore it.
procedure Parse_Doctype (P : in out Parser);
procedure Collect_Attributes (P : in out Parser);
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
Token : Wide_Wide_Character;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Wiki.Helpers.Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML/XML comment to strip it.
-- ------------------------------
procedure Parse_Comment (P : in out Parser) is
C : Wide_Wide_Character;
begin
Peek (P, C);
while not P.Is_Eof loop
Peek (P, C);
if C = '-' then
declare
Count : Natural := 1;
begin
Peek (P, C);
while not P.Is_Eof and C = '-' loop
Peek (P, C);
Count := Count + 1;
end loop;
exit when C = '>' and Count >= 2;
end;
end if;
end loop;
end Parse_Comment;
-- ------------------------------
-- Parse a simple DOCTYPE declaration and ignore it.
-- ------------------------------
procedure Parse_Doctype (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = '>';
end loop;
end Parse_Doctype;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
begin
Peek (P, C);
if C = '!' then
Peek (P, C);
if C = '-' then
Parse_Comment (P);
else
Parse_Doctype (P);
end if;
return;
end if;
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Name);
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Name, P.Attributes);
End_Element (P, Name);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Name, P.Attributes);
end if;
end Parse_Element;
-- ------------------------------
-- Parse an HTML entity such as and replace it with the corresponding code.
-- ------------------------------
procedure Parse_Entity (P : in out Parser;
Token : in Wide_Wide_Character) is
pragma Unreferenced (Token);
Name : String (1 .. 10);
Len : Natural := 0;
High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last;
Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First;
Pos : Natural;
C : Wide_Wide_Character;
begin
while Len < Name'Last loop
Peek (P, C);
exit when C = ';' or else P.Is_Eof;
Len := Len + 1;
Name (Len) := Ada.Characters.Conversions.To_Character (C);
end loop;
while Low <= High loop
Pos := (Low + High) / 2;
if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then
Parse_Text (P, Entities.Mapping (Pos));
return;
elsif Entities.Keywords (Pos).all < Name (1 .. Len) then
Low := Pos + 1;
else
High := Pos - 1;
end if;
end loop;
-- The HTML entity is not recognized: we must treat it as plain wiki text.
Parse_Text (P, '&');
for I in 1 .. Len loop
Parse_Text (P, Ada.Characters.Conversions.To_Wide_Wide_Character (Name (I)));
end loop;
end Parse_Entity;
end Wiki.Parsers.Html;
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Wiki.Helpers;
with Wiki.Parsers.Html.Entities;
package body Wiki.Parsers.Html is
-- Parse an HTML attribute
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String);
-- Parse a HTML/XML comment to strip it.
procedure Parse_Comment (P : in out Parser);
-- Parse a simple DOCTYPE declaration and ignore it.
procedure Parse_Doctype (P : in out Parser);
procedure Collect_Attributes (P : in out Parser);
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
Token : Wide_Wide_Character;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Wiki.Helpers.Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML/XML comment to strip it.
-- ------------------------------
procedure Parse_Comment (P : in out Parser) is
C : Wide_Wide_Character;
begin
Peek (P, C);
while not P.Is_Eof loop
Peek (P, C);
if C = '-' then
declare
Count : Natural := 1;
begin
Peek (P, C);
while not P.Is_Eof and C = '-' loop
Peek (P, C);
Count := Count + 1;
end loop;
exit when C = '>' and Count >= 2;
end;
end if;
end loop;
end Parse_Comment;
-- ------------------------------
-- Parse a simple DOCTYPE declaration and ignore it.
-- ------------------------------
procedure Parse_Doctype (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = '>';
end loop;
end Parse_Doctype;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
Tag : Wiki.Nodes.Html_Tag_Type;
begin
Peek (P, C);
if C = '!' then
Peek (P, C);
if C = '-' then
Parse_Comment (P);
else
Parse_Doctype (P);
end if;
return;
end if;
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
Tag := Wiki.Nodes.Find_Tag (To_Wide_Wide_String (Name));
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Tag);
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Tag, P.Attributes);
End_Element (P, Tag);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Tag, P.Attributes);
end if;
end Parse_Element;
-- ------------------------------
-- Parse an HTML entity such as and replace it with the corresponding code.
-- ------------------------------
procedure Parse_Entity (P : in out Parser;
Token : in Wide_Wide_Character) is
pragma Unreferenced (Token);
Name : String (1 .. 10);
Len : Natural := 0;
High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last;
Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First;
Pos : Natural;
C : Wide_Wide_Character;
begin
while Len < Name'Last loop
Peek (P, C);
exit when C = ';' or else P.Is_Eof;
Len := Len + 1;
Name (Len) := Ada.Characters.Conversions.To_Character (C);
end loop;
while Low <= High loop
Pos := (Low + High) / 2;
if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then
Parse_Text (P, Entities.Mapping (Pos));
return;
elsif Entities.Keywords (Pos).all < Name (1 .. Len) then
Low := Pos + 1;
else
High := Pos - 1;
end if;
end loop;
-- The HTML entity is not recognized: we must treat it as plain wiki text.
Parse_Text (P, '&');
for I in 1 .. Len loop
Parse_Text (P, Ada.Characters.Conversions.To_Wide_Wide_Character (Name (I)));
end loop;
end Parse_Entity;
end Wiki.Parsers.Html;
|
Use Wiki.Nodes.Find_Tag to find the HTML tag and call the Start_Element/End_Element operation
|
Use Wiki.Nodes.Find_Tag to find the HTML tag and call the Start_Element/End_Element operation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
8769736e6a551bc8d4768c291379ec9179d03a3e
|
mat/src/symbols/mat-symbols-targets.ads
|
mat/src/symbols/mat-symbols-targets.ads
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Bfd.Constants;
with Util.Refs;
with MAT.Types;
with MAT.Consoles;
with MAT.Memory;
package MAT.Symbols.Targets is
-- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or
-- a shared library loaded by the program. The <tt>Region</tt> indicates
-- the text segment address of the program or the loaded library.
type Region_Symbols is new Util.Refs.Ref_Entity with record
Region : MAT.Memory.Region_Info;
Offset : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Region_Symbols_Access is access all Region_Symbols;
-- Load the symbol table for the associated region.
procedure Open (Symbols : in out Region_Symbols;
Path : in String;
Search_Path : in String);
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
type Symbol_Info is limited record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
Symbols : Region_Symbols_Ref;
end record;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Region_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
Path : Ada.Strings.Unbounded.Unbounded_String;
Search_Path : Ada.Strings.Unbounded.Unbounded_String;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr);
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map);
-- Demangle the symbol.
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
-- Find the symbol in the symbol table and return the start and end address.
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Name : in String;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr);
-- Find the symbol region in the symbol table which contains the given address
-- and return the start and end address.
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Bfd.Constants;
with Util.Refs;
with MAT.Types;
with MAT.Consoles;
with MAT.Memory;
package MAT.Symbols.Targets is
-- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or
-- a shared library loaded by the program. The <tt>Region</tt> indicates
-- the text segment address of the program or the loaded library.
type Region_Symbols is new Util.Refs.Ref_Entity with record
Region : MAT.Memory.Region_Info;
Offset : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Region_Symbols_Access is access all Region_Symbols;
-- Load the symbol table for the associated region.
procedure Open (Symbols : in out Region_Symbols;
Path : in String;
Search_Path : in String);
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
type Symbol_Info is limited record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
Symbols : Region_Symbols_Ref;
end record;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Region_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
Path : Ada.Strings.Unbounded.Unbounded_String;
Search_Path : Ada.Strings.Unbounded.Unbounded_String;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
Use_Demangle : Boolean := True;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr);
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map);
-- Demangle the symbol.
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
-- Find the symbol in the symbol table and return the start and end address.
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Name : in String;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr);
-- Find the symbol region in the symbol table which contains the given address
-- and return the start and end address.
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
Add Use_Demangle flag to enable/disable demangling
|
Add Use_Demangle flag to enable/disable demangling
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
3fc79236bd6eb0808db73ef7015763d7e3a119fc
|
ravenadm.adb
|
ravenadm.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: License.txt
with Ada.Command_Line;
with Ada.Text_IO;
with Parameters;
with Pilot;
with Unix;
procedure Ravenadm is
package CLI renames Ada.Command_Line;
package TIO renames Ada.Text_IO;
type mandate_type is (unset, help, dev, build, build_everything, force, test,
status, status_everything, configure, locate, purge, changeopts,
checkports, portsnap, repository);
type dev_mandate is (unset, dump, makefile, distinfo, buildsheet, template, genindex);
procedure scan_first_command_word;
function scan_dev_command_word return dev_mandate;
function get_arg (arg_number : Positive) return String;
mandate : mandate_type := unset;
low_rights : Boolean := False;
procedure scan_first_command_word
is
first : constant String := CLI.Argument (1);
begin
if first = "help" then
mandate := help;
elsif first = "dev" then
mandate := dev;
elsif first = "build" then
mandate := build;
elsif first = "build-everything" then
mandate := build_everything;
elsif first = "force" then
mandate := force;
elsif first = "test" then
mandate := test;
elsif first = "status" then
mandate := status;
elsif first = "status-everything" then
mandate := status_everything;
elsif first = "configure" then
mandate := configure;
elsif first = "locate" then
mandate := locate;
elsif first = "purge-distfiles" then
mandate := purge;
elsif first = "set-options" then
mandate := changeopts;
elsif first = "check-ports" then
mandate := checkports;
elsif first = "update-ports" then
mandate := portsnap;
elsif first = "generate-repository" then
mandate := repository;
end if;
end scan_first_command_word;
function scan_dev_command_word return dev_mandate
is
-- Check argument count before calling
second : constant String := CLI.Argument (2);
begin
if second = "dump" then
return dump;
elsif second = "makefile" then
return makefile;
elsif second = "distinfo" then
return distinfo;
elsif second = "buildsheet" then
return buildsheet;
elsif second = "template" then
return template;
elsif second = "generate-index" then
return genindex;
else
return unset;
end if;
end scan_dev_command_word;
function get_arg (arg_number : Positive) return String is
begin
if CLI.Argument_Count >= arg_number then
return CLI.Argument (arg_number);
else
return "";
end if;
end get_arg;
begin
if CLI.Argument_Count = 0 then
Pilot.display_usage;
return;
end if;
scan_first_command_word;
if mandate = unset then
Pilot.react_to_unknown_first_level_command (CLI.Argument (1));
return;
end if;
--------------------------------------------------------------------------------------------
-- Validation block start
--------------------------------------------------------------------------------------------
if Pilot.already_running then
return;
end if;
if not Parameters.load_configuration then
return;
end if;
case mandate is
when build | build_everything | test | status | status_everything =>
-- All commands involving replicant slaves
if Pilot.launch_clash_detected then
return;
end if;
when others => null;
end case;
case mandate is
when build | build_everything | test =>
if Parameters.configuration.avec_ncurses and then
not Pilot.TERM_defined_in_environment
then
return;
end if;
when others => null;
end case;
case mandate is
when configure | help => null;
when portsnap =>
if not Parameters.all_paths_valid (skip_mk_check => True) then
return;
end if;
when others =>
if not Parameters.all_paths_valid (skip_mk_check => False) then
return;
end if;
end case;
case mandate is
when help | locate => null;
low_rights := True;
when others =>
if Pilot.insufficient_privileges then
return;
end if;
end case;
if Pilot.previous_run_mounts_detected and then
not Pilot.old_mounts_successfully_removed
then
return;
end if;
if Pilot.previous_realfs_work_detected and then
not Pilot.old_realfs_work_successfully_removed
then
return;
end if;
if Pilot.ravenexec_missing then
return;
end if;
case mandate is
when build | force | test | changeopts =>
if not Pilot.store_origins (start_from => 2) then
return;
end if;
when status =>
if CLI.Argument_Count > 1 then
if not Pilot.store_origins (start_from => 2) then
return;
end if;
end if;
when others => null;
end case;
case mandate is
when build | build_everything | force | test | status | status_everything =>
if not Pilot.slave_platform_determined then
return;
end if;
when others => null;
end case;
if not low_rights then
Pilot.create_pidfile;
Unix.ignore_background_tty;
end if;
if mandate /= configure then
Unix.cone_of_silence (deploy => True);
end if;
--------------------------------------------------------------------------------------------
-- Validation block end
--------------------------------------------------------------------------------------------
case mandate is
when status =>
--------------------------------
-- status command
--------------------------------
if CLI.Argument_Count > 1 then
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True)
then
Pilot.display_results_of_dry_run;
end if;
else
null; -- reserved for upgrade_system_everything maybe
end if;
when status_everything =>
--------------------------------
-- status_everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True)
then
Pilot.display_results_of_dry_run;
end if;
when build =>
--------------------------------
-- build command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when build_everything =>
--------------------------------
-- build-everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when force =>
--------------------------------
-- force command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when dev =>
--------------------------------
-- dev command
--------------------------------
if CLI.Argument_Count > 1 then
declare
dev_subcmd : dev_mandate := scan_dev_command_word;
begin
case dev_subcmd is
when unset =>
Pilot.react_to_unknown_second_level_command (CLI.Argument (1),
CLI.Argument (2));
when dump =>
Pilot.dump_ravensource (get_arg (3));
when distinfo =>
Pilot.generate_distinfo;
when buildsheet =>
Pilot.generate_buildsheet (get_arg (3), get_arg (4));
when makefile =>
Pilot.generate_makefile (get_arg (3), get_arg (4));
when template =>
Pilot.print_spec_template (get_arg (3));
when genindex =>
Pilot.generate_ports_index;
end case;
end;
else
Pilot.react_to_unknown_second_level_command (CLI.Argument (1), "");
end if;
when help =>
--------------------------------
-- help command
--------------------------------
null; -- tbw
when test =>
--------------------------------
-- test command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => True) and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
if Pilot.interact_with_single_builder then
Pilot.bulk_run_then_interact_with_final_port;
else
Pilot.perform_bulk_run (testmode => True);
end if;
end if;
when configure =>
--------------------------------
-- configure
--------------------------------
Pilot.launch_configure_menu;
when locate =>
--------------------------------
-- locate
--------------------------------
Pilot.locate (get_arg (2));
when purge =>
--------------------------------
-- purge-distfiles
--------------------------------
Pilot.purge_distfiles;
when changeopts =>
--------------------------------
-- set-options
--------------------------------
Pilot.change_options;
when checkports =>
--------------------------------
-- check-ports
--------------------------------
Pilot.check_ravenports_version;
when portsnap =>
--------------------------------
-- update-ports
--------------------------------
Pilot.update_to_latest_ravenports;
when repository =>
--------------------------------
-- generate-repository
--------------------------------
Pilot.generate_repository;
when unset => null;
end case;
Unix.cone_of_silence (deploy => False);
if not low_rights then
Pilot.destroy_pidfile;
end if;
end Ravenadm;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: License.txt
with Ada.Command_Line;
with Ada.Text_IO;
with Parameters;
with Pilot;
with Unix;
procedure Ravenadm is
package CLI renames Ada.Command_Line;
package TIO renames Ada.Text_IO;
type mandate_type is (unset, help, dev, build, build_everything, force, test, test_everything,
status, status_everything, configure, locate, purge, changeopts,
checkports, portsnap, repository);
type dev_mandate is (unset, dump, makefile, distinfo, buildsheet, template, genindex);
procedure scan_first_command_word;
function scan_dev_command_word return dev_mandate;
function get_arg (arg_number : Positive) return String;
mandate : mandate_type := unset;
low_rights : Boolean := False;
procedure scan_first_command_word
is
first : constant String := CLI.Argument (1);
begin
if first = "help" then
mandate := help;
elsif first = "dev" then
mandate := dev;
elsif first = "build" then
mandate := build;
elsif first = "build-everything" then
mandate := build_everything;
elsif first = "force" then
mandate := force;
elsif first = "test" then
mandate := test;
elsif first = "test-everything" then
mandate := test_everything;
elsif first = "status" then
mandate := status;
elsif first = "status-everything" then
mandate := status_everything;
elsif first = "configure" then
mandate := configure;
elsif first = "locate" then
mandate := locate;
elsif first = "purge-distfiles" then
mandate := purge;
elsif first = "set-options" then
mandate := changeopts;
elsif first = "check-ports" then
mandate := checkports;
elsif first = "update-ports" then
mandate := portsnap;
elsif first = "generate-repository" then
mandate := repository;
end if;
end scan_first_command_word;
function scan_dev_command_word return dev_mandate
is
-- Check argument count before calling
second : constant String := CLI.Argument (2);
begin
if second = "dump" then
return dump;
elsif second = "makefile" then
return makefile;
elsif second = "distinfo" then
return distinfo;
elsif second = "buildsheet" then
return buildsheet;
elsif second = "template" then
return template;
elsif second = "generate-index" then
return genindex;
else
return unset;
end if;
end scan_dev_command_word;
function get_arg (arg_number : Positive) return String is
begin
if CLI.Argument_Count >= arg_number then
return CLI.Argument (arg_number);
else
return "";
end if;
end get_arg;
begin
if CLI.Argument_Count = 0 then
Pilot.display_usage;
return;
end if;
scan_first_command_word;
if mandate = unset then
Pilot.react_to_unknown_first_level_command (CLI.Argument (1));
return;
end if;
--------------------------------------------------------------------------------------------
-- Validation block start
--------------------------------------------------------------------------------------------
if Pilot.already_running then
return;
end if;
if not Parameters.load_configuration then
return;
end if;
case mandate is
when build | build_everything | test | status | status_everything =>
-- All commands involving replicant slaves
if Pilot.launch_clash_detected then
return;
end if;
when others => null;
end case;
case mandate is
when build | build_everything | test =>
if Parameters.configuration.avec_ncurses and then
not Pilot.TERM_defined_in_environment
then
return;
end if;
when others => null;
end case;
case mandate is
when configure | help => null;
when portsnap =>
if not Parameters.all_paths_valid (skip_mk_check => True) then
return;
end if;
when others =>
if not Parameters.all_paths_valid (skip_mk_check => False) then
return;
end if;
end case;
case mandate is
when help | locate => null;
low_rights := True;
when others =>
if Pilot.insufficient_privileges then
return;
end if;
end case;
if Pilot.previous_run_mounts_detected and then
not Pilot.old_mounts_successfully_removed
then
return;
end if;
if Pilot.previous_realfs_work_detected and then
not Pilot.old_realfs_work_successfully_removed
then
return;
end if;
if Pilot.ravenexec_missing then
return;
end if;
case mandate is
when build | force | test | changeopts =>
if not Pilot.store_origins (start_from => 2) then
return;
end if;
when status =>
if CLI.Argument_Count > 1 then
if not Pilot.store_origins (start_from => 2) then
return;
end if;
end if;
when others => null;
end case;
case mandate is
when build | build_everything | force | test | status | status_everything =>
if not Pilot.slave_platform_determined then
return;
end if;
when others => null;
end case;
if not low_rights then
Pilot.create_pidfile;
Unix.ignore_background_tty;
end if;
if mandate /= configure then
Unix.cone_of_silence (deploy => True);
end if;
--------------------------------------------------------------------------------------------
-- Validation block end
--------------------------------------------------------------------------------------------
case mandate is
when status =>
--------------------------------
-- status command
--------------------------------
if CLI.Argument_Count > 1 then
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True)
then
Pilot.display_results_of_dry_run;
end if;
else
null; -- reserved for upgrade_system_everything maybe
end if;
when status_everything =>
--------------------------------
-- status_everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True)
then
Pilot.display_results_of_dry_run;
end if;
when build =>
--------------------------------
-- build command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when build_everything =>
--------------------------------
-- build-everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when test_everything =>
--------------------------------
-- test-everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
Pilot.perform_bulk_run (testmode => True);
end if;
when force =>
--------------------------------
-- force command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when dev =>
--------------------------------
-- dev command
--------------------------------
if CLI.Argument_Count > 1 then
declare
dev_subcmd : dev_mandate := scan_dev_command_word;
begin
case dev_subcmd is
when unset =>
Pilot.react_to_unknown_second_level_command (CLI.Argument (1),
CLI.Argument (2));
when dump =>
Pilot.dump_ravensource (get_arg (3));
when distinfo =>
Pilot.generate_distinfo;
when buildsheet =>
Pilot.generate_buildsheet (get_arg (3), get_arg (4));
when makefile =>
Pilot.generate_makefile (get_arg (3), get_arg (4));
when template =>
Pilot.print_spec_template (get_arg (3));
when genindex =>
Pilot.generate_ports_index;
end case;
end;
else
Pilot.react_to_unknown_second_level_command (CLI.Argument (1), "");
end if;
when help =>
--------------------------------
-- help command
--------------------------------
null; -- tbw
when test =>
--------------------------------
-- test command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => True) and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
if Pilot.interact_with_single_builder then
Pilot.bulk_run_then_interact_with_final_port;
else
Pilot.perform_bulk_run (testmode => True);
end if;
end if;
when configure =>
--------------------------------
-- configure
--------------------------------
Pilot.launch_configure_menu;
when locate =>
--------------------------------
-- locate
--------------------------------
Pilot.locate (get_arg (2));
when purge =>
--------------------------------
-- purge-distfiles
--------------------------------
Pilot.purge_distfiles;
when changeopts =>
--------------------------------
-- set-options
--------------------------------
Pilot.change_options;
when checkports =>
--------------------------------
-- check-ports
--------------------------------
Pilot.check_ravenports_version;
when portsnap =>
--------------------------------
-- update-ports
--------------------------------
Pilot.update_to_latest_ravenports;
when repository =>
--------------------------------
-- generate-repository
--------------------------------
Pilot.generate_repository;
when unset => null;
end case;
Unix.cone_of_silence (deploy => False);
if not low_rights then
Pilot.destroy_pidfile;
end if;
end Ravenadm;
|
Add "test-everything" command
|
Add "test-everything" command
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
c646a13e55b6f498d89b30c1ed1bb0b98875c7a9
|
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 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;
|
-----------------------------------------------------------------------
-- Faces Context Tests - Unit tests for ASF.Contexts.Faces
-- Copyright (C) 2010, 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 Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with ASF.Applications.Main;
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 missing with clause for ASF.Applications.Main to fix GNAT 2017 compilation
|
Add missing with clause for ASF.Applications.Main to fix GNAT 2017 compilation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
8548eca4d803a079f89ee0a0249108b48f800e74
|
src/asf-security.ads
|
src/asf-security.ads
|
-----------------------------------------------------------------------
-- asf-security -- ASF Security
-- 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 EL.Functions;
package ASF.Security is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
end ASF.Security;
|
-----------------------------------------------------------------------
-- asf-security -- ASF Security
-- 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 EL.Functions;
package ASF.Security is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
end ASF.Security;
|
Package ASF.Security moved to Servlet.Security
|
Package ASF.Security moved to Servlet.Security
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
4f6e82df3995063435bc6ac69b381baf3c642309
|
src/atlas-server.adb
|
src/atlas-server.adb
|
-----------------------------------------------------------------------
-- atlas-server -- Application server
-- Copyright (C) 2011, 2012, 2013, 2016, 2017, 2018, 2019, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Commands;
with AWS.Net.SSL;
with Servlet.Server.Web;
with AWA.Commands.Drivers;
with AWA.Commands.Start;
with AWA.Commands.Setup;
with AWA.Commands.Stop;
with AWA.Commands.List;
with AWA.Commands.Info;
with ADO.Drivers;
-- with ADO.Sqlite;
-- with ADO.Mysql;
-- with ADO.Postgresql;
with Atlas.Applications;
procedure Atlas.Server is
package Server_Commands is
new AWA.Commands.Drivers (Driver_Name => "atlas",
Container_Type => Servlet.Server.Web.AWS_Container);
package List_Command is new AWA.Commands.List (Server_Commands);
package Start_Command is new AWA.Commands.Start (Server_Commands);
package Stop_Command is new AWA.Commands.Stop (Server_Commands);
package Info_Command is new AWA.Commands.Info (Server_Commands);
package Setup_Command is new AWA.Commands.Setup (Start_Command);
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server");
App : constant Atlas.Applications.Application_Access
:= new Atlas.Applications.Application;
WS : Servlet.Server.Web.AWS_Container renames Server_Commands.WS;
Context : AWA.Commands.Context_Type;
Arguments : Util.Commands.Dynamic_Argument_List;
begin
-- Initialize the database drivers (all of them or specific ones).
ADO.Drivers.Initialize;
-- ADO.Sqlite.Initialize;
-- ADO.Mysql.Initialize;
-- ADO.Postgresql.Initialize;
WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access);
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OAuth2/OpenID connector to "
& "connect to OAuth2/OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
end if;
Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html",
Atlas.Applications.CONTEXT_PATH);
Server_Commands.Run (Context, Arguments);
exception
when E : others =>
Context.Print (E);
end Atlas.Server;
|
-----------------------------------------------------------------------
-- atlas-server -- Application server
-- Copyright (C) 2011 - 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Commands;
with AWA.Commands.Drivers;
with AWA.Commands.Start;
with AWA.Commands.Setup;
with AWA.Commands.Stop;
with AWA.Commands.List;
with AWA.Commands.Info;
with ADO.Sqlite;
-- with ADO.Mysql;
-- with ADO.Postgresql;
with Atlas.Applications;
with Atlas.Init;
procedure Atlas.Server is
package Server_Commands is
new AWA.Commands.Drivers (Driver_Name => "atlas",
Container_Type => Atlas.Init.Container_Type);
package List_Command is new AWA.Commands.List (Server_Commands);
package Start_Command is new AWA.Commands.Start (Server_Commands);
package Stop_Command is new AWA.Commands.Stop (Server_Commands);
package Info_Command is new AWA.Commands.Info (Server_Commands);
package Setup_Command is new AWA.Commands.Setup (Start_Command);
pragma Unreferenced (List_Command, Start_Command, Stop_Command, Info_Command, Setup_Command);
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server");
App : constant Atlas.Applications.Application_Access
:= new Atlas.Applications.Application;
WS : Atlas.Init.Container_Type renames Server_Commands.WS;
Context : AWA.Commands.Context_Type;
Arguments : Util.Commands.Dynamic_Argument_List;
begin
-- Initialize the database drivers (all of them or specific ones).
-- ADO.Drivers.Initialize;
ADO.Sqlite.Initialize;
-- ADO.Mysql.Initialize;
-- ADO.Postgresql.Initialize;
WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access);
Atlas.Init.Initialize (Log);
Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html",
Atlas.Applications.CONTEXT_PATH);
Server_Commands.Run (Context, Arguments);
exception
when E : others =>
Context.Print (E);
end Atlas.Server;
|
Update to be able to use EWS or AWS server according to build configuration
|
Update to be able to use EWS or AWS server according to build configuration
|
Ada
|
apache-2.0
|
stcarrez/atlas
|
15d4d6e2edc7b6e0a18b7a9369f3dffd5d8b55a0
|
src/security-policies-roles.ads
|
src/security-policies-roles.ads
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
--
-- A role is represented by a name in security configuration files.
package Security.Policies.Roles is
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- 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.
overriding
procedure Set_Reader_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last));
Count : Natural := 0;
Manager : Role_Policy_Access;
end record;
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
--
-- A role is represented by a name in security configuration files. A role based permission
-- is associated with a list of roles. The permission is granted if the user has one of these
-- roles.
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <security-role>
-- <role-name>manager</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt>
-- It defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
package Security.Policies.Roles is
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- 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.
overriding
procedure Set_Reader_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Role_Type_Array (1 .. Integer (Role_Type'Last));
Count : Natural := 0;
Manager : Role_Policy_Access;
end record;
end Security.Policies.Roles;
|
Document the policy roles
|
Document the policy roles
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
a6ae89c36508b01ca56cffab94351d28ba0f5551
|
src/gen-artifacts-distribs-merges.adb
|
src/gen-artifacts-distribs-merges.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-merges -- Web file merge
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Fixed;
with Ada.Streams.Stream_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings;
with Util.Streams.Files;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with EL.Expressions;
with Gen.Utils;
package body Gen.Artifacts.Distribs.Merges is
use Util.Log;
use Ada.Strings.Fixed;
use Util.Beans.Objects;
use Ada.Strings.Unbounded;
procedure Process_Property (Rule : in out Merge_Rule;
Node : in DOM.Core.Node);
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Merges");
-- ------------------------------
-- Extract the <property name='{name}'>{value}</property> to setup the
-- EL context to evaluate the source and target links for the merge.
-- ------------------------------
procedure Process_Property (Rule : in out Merge_Rule;
Node : in DOM.Core.Node) is
use Util.Beans.Objects.Maps;
Name : constant String := Gen.Utils.Get_Attribute (Node, "name");
Value : constant String := Gen.Utils.Get_Data_Content (Node);
Pos : constant Natural := Util.Strings.Index (Name, '.');
begin
if Pos = 0 then
Rule.Variables.Bind (Name, To_Object (Value));
return;
end if;
-- A composed name such as 'jquery.path' must be split so that we store
-- the 'path' value within a 'jquery' Map_Bean object. We handle only
-- one such composition.
declare
Param : constant String := Name (Name'First .. Pos - 1);
Tag : constant Unbounded_String := To_Unbounded_String (Param);
Var : constant EL.Expressions.Expression := Rule.Variables.Get_Variable (Tag);
Val : Object := Rule.Params.Get_Value (Param);
Child : Map_Bean_Access;
begin
if Is_Null (Val) then
Child := new Map_Bean;
Val := To_Object (Child);
Rule.Params.Set_Value (Param, Val);
else
Child := To_Bean (Val);
end if;
Child.Set_Value (Name (Pos + 1 .. Name'Last), To_Object (Value));
if Var.Is_Null then
Rule.Variables.Bind (Param, Val);
end if;
end;
end Process_Property;
procedure Process_Replace (Rule : in out Merge_Rule;
Node : in DOM.Core.Node) is
From : constant String := Gen.Utils.Get_Data_Content (Node, "from");
To : constant String := Gen.Utils.Get_Data_Content (Node, "to");
begin
Rule.Replace.Include (From, To);
end Process_Replace;
procedure Iterate_Properties is
new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Property);
procedure Iterate_Replace is
new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Replace);
-- ------------------------------
-- Create a distribution rule to copy a set of files or directories.
-- ------------------------------
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is
Result : constant Merge_Rule_Access := new Merge_Rule;
begin
Iterate_Properties (Result.all, Node, "property", False);
Iterate_Replace (Result.all, Node, "replace", False);
Result.Context.Set_Variable_Mapper (Result.Variables'Access);
return Result.all'Access;
end Create_Rule;
-- ------------------------------
-- Get a name to qualify the installation rule (used for logs).
-- ------------------------------
overriding
function Get_Install_Name (Rule : in Merge_Rule) return String is
pragma Unreferenced (Rule);
begin
return "merge";
end Get_Install_Name;
overriding
procedure Install (Rule : in Merge_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
use Ada.Streams;
type Mode_Type is (MERGE_NONE, MERGE_LINK, MERGE_SCRIPT);
procedure Error (Message : in String);
function Get_Target_Path (Link : in String) return String;
function Get_Filename (Line : in String) return String;
function Get_Source (Line : in String;
Tag : in String) return String;
procedure Prepare_Merge (Line : in String);
procedure Include (Source : in String);
procedure Process (Line : in String);
Root_Dir : constant String :=
Util.Files.Compose (Context.Get_Result_Directory,
To_String (Rule.Dir));
Source : constant String := Get_Source_Path (Files, False);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : aliased Util.Streams.Files.File_Stream;
Merge : aliased Util.Streams.Files.File_Stream;
Text : Util.Streams.Texts.Print_Stream;
Mode : Mode_Type := MERGE_NONE;
Line_Num : Natural := 0;
procedure Error (Message : in String) is
Line : constant String := Util.Strings.Image (Line_Num);
begin
Context.Error (Source & ":" & Line & ": " & Message);
end Error;
function Get_Target_Path (Link : in String) return String is
Expr : EL.Expressions.Expression;
File : Util.Beans.Objects.Object;
begin
Expr := EL.Expressions.Create_Expression (Link, Rule.Context);
File := Expr.Get_Value (Rule.Context);
return Util.Files.Compose (Root_Dir, To_String (File));
end Get_Target_Path;
function Get_Filename (Line : in String) return String is
Pos : Natural := Index (Line, "link=");
Last : Natural;
begin
if Pos > 0 then
Mode := MERGE_LINK;
else
Pos := Index (Line, "script=");
if Pos > 0 then
Mode := MERGE_SCRIPT;
end if;
if Pos = 0 then
return "";
end if;
end if;
Pos := Index (Line, "=");
Last := Util.Strings.Index (Line, ' ', Pos + 1);
if Last = 0 then
return "";
end if;
return Line (Pos + 1 .. Last - 1);
end Get_Filename;
function Get_Source (Line : in String;
Tag : in String) return String is
Pos : Natural := Index (Line, Tag);
Last : Natural;
begin
if Pos = 0 then
return "";
end if;
Pos := Pos + Tag'Length;
if Pos > Line'Last or else (Line (Pos) /= '"' and Line (Pos) /= ''') then
return "";
end if;
Last := Util.Strings.Index (Line, Line (Pos), Pos + 1);
if Last = 0 then
return "";
end if;
return Line (Pos + 1 .. Last - 1);
end Get_Source;
procedure Prepare_Merge (Line : in String) is
Name : constant String := Get_Filename (Line);
Path : constant String := Get_Target_Path (Name);
begin
if Name'Length = 0 then
Error ("invalid file name");
return;
end if;
case Mode is
when MERGE_LINK =>
Text.Write ("<link media='screen' type='text/css' rel='stylesheet'"
& " href='");
Text.Write (Name);
Text.Write ("'/>" & ASCII.LF);
when MERGE_SCRIPT =>
Text.Write ("<script type='text/javascript' src='");
Text.Write (Name);
Text.Write ("'></script>" & ASCII.LF);
when MERGE_NONE =>
null;
end case;
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info (" create {0}", Path);
end if;
Merge.Create (Mode => Ada.Streams.Stream_IO.Out_File,
Name => Path);
end Prepare_Merge;
Current_Match : Util.Strings.Maps.Cursor;
function Find_Match (Buffer : in Stream_Element_Array) return Stream_Element_Offset is
Iter : Util.Strings.Maps.Cursor := Rule.Replace.First;
First : Stream_Element_Offset := Buffer'Last + 1;
begin
while Util.Strings.Maps.Has_Element (Iter) loop
declare
Value : constant String := Util.Strings.Maps.Key (Iter);
Match : Stream_Element_Array (1 .. Value'Length);
for Match'Address use Value'Address;
Pos : Stream_Element_Offset;
begin
Pos := Buffer'First;
while Pos + Match'Length < Buffer'Last loop
if Buffer (Pos .. Pos + Match'Length - 1) = Match then
if First > Pos then
First := Pos;
Current_Match := Iter;
end if;
exit;
end if;
Pos := Pos + 1;
end loop;
end;
Util.Strings.Maps.Next (Iter);
end loop;
return First;
end Find_Match;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Ada.Streams.Stream_Element_Array,
Name => Util.Streams.Buffered.Buffer_Access);
procedure Include (Source : in String) is
Target : constant String := Get_Target_Path (Source);
Input : Util.Streams.Files.File_Stream;
Size : Stream_Element_Offset;
Last : Stream_Element_Offset;
Pos : Stream_Element_Offset;
Next : Stream_Element_Offset;
Buffer : Util.Streams.Buffered.Buffer_Access;
begin
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info (" include {0}", Target);
end if;
Input.Open (Name => Target, Mode => Ada.Streams.Stream_IO.In_File);
Size := Stream_Element_Offset (Ada.Directories.Size (Target));
Buffer := new Stream_Element_Array (1 .. Size);
Input.Read (Buffer.all, Last);
Input.Close;
Pos := 1;
while Pos < Last loop
Next := Find_Match (Buffer (Pos .. Last));
if Next > Pos then
Merge.Write (Buffer (Pos .. Next - 1));
end if;
exit when Next >= Last;
declare
Value : constant String := Util.Strings.Maps.Key (Current_Match);
Replace : constant String := Util.Strings.Maps.Element (Current_Match);
Content : Stream_Element_Array (1 .. Replace'Length);
for Content'Address use Replace'Address;
begin
Merge.Write (Content);
Pos := Next + Value'Length;
end;
end loop;
Free (Buffer);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Error ("Cannot read: " & Ada.Exceptions.Exception_Message (Ex));
end Include;
procedure Process (Line : in String) is
Pos : Natural;
begin
Line_Num := Line_Num + 1;
case Mode is
when MERGE_NONE =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-START ");
if Pos = 0 then
Text.Write (Line);
Text.Write (ASCII.LF);
return;
end if;
Text.Write (Line (Line'First .. Pos - 1));
Prepare_Merge (Line (Pos + 10 .. Line'Last));
when MERGE_LINK =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-END ");
if Pos > 0 then
Merge.Close;
Mode := MERGE_NONE;
return;
end if;
Include (Get_Source (Line, "href="));
when MERGE_SCRIPT =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-END ");
if Pos > 0 then
Merge.Close;
Mode := MERGE_NONE;
return;
end if;
Text.Write (Line (Line'First .. Pos - 1));
Include (Get_Source (Line, "src="));
end case;
end Process;
begin
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info ("webmerge {0}", Path);
end if;
Ada.Directories.Create_Path (Dir);
Output.Create (Name => Path, Mode => Ada.Streams.Stream_IO.Out_File);
Text.Initialize (Output'Unchecked_Access, 16 * 1024);
Util.Files.Read_File (Source, Process'Access);
Text.Flush;
Output.Close;
end Install;
end Gen.Artifacts.Distribs.Merges;
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-merges -- Web file merge
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Fixed;
with Ada.Streams.Stream_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Files;
with Util.Strings;
with Util.Streams.Files;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with EL.Expressions;
with Gen.Utils;
package body Gen.Artifacts.Distribs.Merges is
use Util.Log;
use Ada.Strings.Fixed;
use Util.Beans.Objects;
use Ada.Strings.Unbounded;
procedure Process_Property (Rule : in out Merge_Rule;
Node : in DOM.Core.Node);
procedure Process_Replace (Rule : in out Merge_Rule;
Node : in DOM.Core.Node);
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Merges");
-- ------------------------------
-- Extract the <property name='{name}'>{value}</property> to setup the
-- EL context to evaluate the source and target links for the merge.
-- ------------------------------
procedure Process_Property (Rule : in out Merge_Rule;
Node : in DOM.Core.Node) is
use Util.Beans.Objects.Maps;
Name : constant String := Gen.Utils.Get_Attribute (Node, "name");
Value : constant String := Gen.Utils.Get_Data_Content (Node);
Pos : constant Natural := Util.Strings.Index (Name, '.');
begin
if Pos = 0 then
Rule.Variables.Bind (Name, To_Object (Value));
return;
end if;
-- A composed name such as 'jquery.path' must be split so that we store
-- the 'path' value within a 'jquery' Map_Bean object. We handle only
-- one such composition.
declare
Param : constant String := Name (Name'First .. Pos - 1);
Tag : constant Unbounded_String := To_Unbounded_String (Param);
Var : constant EL.Expressions.Expression := Rule.Variables.Get_Variable (Tag);
Val : Object := Rule.Params.Get_Value (Param);
Child : Map_Bean_Access;
begin
if Is_Null (Val) then
Child := new Map_Bean;
Val := To_Object (Child);
Rule.Params.Set_Value (Param, Val);
else
Child := To_Bean (Val);
end if;
Child.Set_Value (Name (Pos + 1 .. Name'Last), To_Object (Value));
if Var.Is_Null then
Rule.Variables.Bind (Param, Val);
end if;
end;
end Process_Property;
procedure Process_Replace (Rule : in out Merge_Rule;
Node : in DOM.Core.Node) is
From : constant String := Gen.Utils.Get_Data_Content (Node, "from");
To : constant String := Gen.Utils.Get_Data_Content (Node, "to");
begin
Rule.Replace.Include (From, To);
end Process_Replace;
procedure Iterate_Properties is
new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Property);
procedure Iterate_Replace is
new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Replace);
-- ------------------------------
-- Create a distribution rule to copy a set of files or directories.
-- ------------------------------
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is
Result : constant Merge_Rule_Access := new Merge_Rule;
begin
Iterate_Properties (Result.all, Node, "property", False);
Iterate_Replace (Result.all, Node, "replace", False);
Result.Context.Set_Variable_Mapper (Result.Variables'Access);
return Result.all'Access;
end Create_Rule;
-- ------------------------------
-- Get a name to qualify the installation rule (used for logs).
-- ------------------------------
overriding
function Get_Install_Name (Rule : in Merge_Rule) return String is
pragma Unreferenced (Rule);
begin
return "merge";
end Get_Install_Name;
overriding
procedure Install (Rule : in Merge_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
use Ada.Streams;
type Mode_Type is (MERGE_NONE, MERGE_LINK, MERGE_SCRIPT);
procedure Error (Message : in String);
function Get_Target_Path (Link : in String) return String;
function Get_Filename (Line : in String) return String;
function Get_Source (Line : in String;
Tag : in String) return String;
function Find_Match (Buffer : in Stream_Element_Array) return Stream_Element_Offset;
procedure Prepare_Merge (Line : in String);
procedure Include (Source : in String);
procedure Process (Line : in String);
Root_Dir : constant String :=
Util.Files.Compose (Context.Get_Result_Directory,
To_String (Rule.Dir));
Source : constant String := Get_Source_Path (Files, False);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Build : constant String := Context.Get_Parameter ("dynamo.build");
Output : aliased Util.Streams.Files.File_Stream;
Merge : aliased Util.Streams.Files.File_Stream;
Text : Util.Streams.Texts.Print_Stream;
Mode : Mode_Type := MERGE_NONE;
Line_Num : Natural := 0;
procedure Error (Message : in String) is
Line : constant String := Util.Strings.Image (Line_Num);
begin
Context.Error (Source & ":" & Line & ": " & Message);
end Error;
function Get_Target_Path (Link : in String) return String is
Expr : EL.Expressions.Expression;
File : Util.Beans.Objects.Object;
begin
Expr := EL.Expressions.Create_Expression (Link, Rule.Context);
File := Expr.Get_Value (Rule.Context);
return Util.Files.Compose (Root_Dir, To_String (File));
end Get_Target_Path;
function Get_Filename (Line : in String) return String is
Pos : Natural := Index (Line, "link=");
Last : Natural;
begin
if Pos > 0 then
Mode := MERGE_LINK;
else
Pos := Index (Line, "script=");
if Pos > 0 then
Mode := MERGE_SCRIPT;
end if;
if Pos = 0 then
return "";
end if;
end if;
Pos := Index (Line, "=");
Last := Util.Strings.Index (Line, ' ', Pos + 1);
if Last = 0 then
return "";
end if;
return Line (Pos + 1 .. Last - 1);
end Get_Filename;
function Get_Source (Line : in String;
Tag : in String) return String is
Pos : Natural := Index (Line, Tag);
Last : Natural;
begin
if Pos = 0 then
return "";
end if;
Pos := Pos + Tag'Length;
if Pos > Line'Last or else (Line (Pos) /= '"' and Line (Pos) /= ''') then
return "";
end if;
Last := Util.Strings.Index (Line, Line (Pos), Pos + 1);
if Last = 0 then
return "";
end if;
return Line (Pos + 1 .. Last - 1);
end Get_Source;
procedure Prepare_Merge (Line : in String) is
Name : constant String := Get_Filename (Line);
Path : constant String := Get_Target_Path (Name);
begin
if Name'Length = 0 then
Error ("invalid file name");
return;
end if;
case Mode is
when MERGE_LINK =>
Text.Write ("<link media='screen' type='text/css' rel='stylesheet'"
& " href='");
Text.Write (Name);
Text.Write ("?build=");
Text.Write (Build);
Text.Write ("'/>" & ASCII.LF);
when MERGE_SCRIPT =>
Text.Write ("<script type='text/javascript' src='");
Text.Write (Name);
Text.Write ("?build=");
Text.Write (Build);
Text.Write ("'></script>" & ASCII.LF);
when MERGE_NONE =>
null;
end case;
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info (" create {0}", Path);
end if;
Merge.Create (Mode => Ada.Streams.Stream_IO.Out_File,
Name => Path);
end Prepare_Merge;
Current_Match : Util.Strings.Maps.Cursor;
function Find_Match (Buffer : in Stream_Element_Array) return Stream_Element_Offset is
Iter : Util.Strings.Maps.Cursor := Rule.Replace.First;
First : Stream_Element_Offset := Buffer'Last + 1;
begin
while Util.Strings.Maps.Has_Element (Iter) loop
declare
Value : constant String := Util.Strings.Maps.Key (Iter);
Match : Stream_Element_Array (1 .. Value'Length);
for Match'Address use Value'Address;
Pos : Stream_Element_Offset;
begin
Pos := Buffer'First;
while Pos + Match'Length < Buffer'Last loop
if Buffer (Pos .. Pos + Match'Length - 1) = Match then
if First > Pos then
First := Pos;
Current_Match := Iter;
end if;
exit;
end if;
Pos := Pos + 1;
end loop;
end;
Util.Strings.Maps.Next (Iter);
end loop;
return First;
end Find_Match;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Ada.Streams.Stream_Element_Array,
Name => Util.Streams.Buffered.Buffer_Access);
procedure Include (Source : in String) is
Target : constant String := Get_Target_Path (Source);
Input : Util.Streams.Files.File_Stream;
Size : Stream_Element_Offset;
Last : Stream_Element_Offset;
Pos : Stream_Element_Offset;
Next : Stream_Element_Offset;
Buffer : Util.Streams.Buffered.Buffer_Access;
begin
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info (" include {0}", Target);
end if;
Input.Open (Name => Target, Mode => Ada.Streams.Stream_IO.In_File);
Size := Stream_Element_Offset (Ada.Directories.Size (Target));
Buffer := new Stream_Element_Array (1 .. Size);
Input.Read (Buffer.all, Last);
Input.Close;
Pos := 1;
while Pos < Last loop
Next := Find_Match (Buffer (Pos .. Last));
if Next > Pos then
Merge.Write (Buffer (Pos .. Next - 1));
end if;
exit when Next >= Last;
declare
Value : constant String := Util.Strings.Maps.Key (Current_Match);
Replace : constant String := Util.Strings.Maps.Element (Current_Match);
Content : Stream_Element_Array (1 .. Replace'Length);
for Content'Address use Replace'Address;
begin
Merge.Write (Content);
Pos := Next + Value'Length;
end;
end loop;
Free (Buffer);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Error ("Cannot read: " & Ada.Exceptions.Exception_Message (Ex));
end Include;
procedure Process (Line : in String) is
Pos : Natural;
begin
Line_Num := Line_Num + 1;
case Mode is
when MERGE_NONE =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-START ");
if Pos = 0 then
Text.Write (Line);
Text.Write (ASCII.LF);
return;
end if;
Text.Write (Line (Line'First .. Pos - 1));
Prepare_Merge (Line (Pos + 10 .. Line'Last));
when MERGE_LINK =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-END ");
if Pos > 0 then
Merge.Close;
Mode := MERGE_NONE;
return;
end if;
Include (Get_Source (Line, "href="));
when MERGE_SCRIPT =>
Pos := Index (Line, "<!-- DYNAMO-MERGE-END ");
if Pos > 0 then
Merge.Close;
Mode := MERGE_NONE;
return;
end if;
Text.Write (Line (Line'First .. Pos - 1));
Include (Get_Source (Line, "src="));
end case;
end Process;
begin
if Rule.Level >= Util.Log.INFO_LEVEL then
Log.Info ("webmerge {0}", Path);
end if;
Ada.Directories.Create_Path (Dir);
Output.Create (Name => Path, Mode => Ada.Streams.Stream_IO.Out_File);
Text.Initialize (Output'Unchecked_Access, 16 * 1024);
Util.Files.Read_File (Source, Process'Access);
Text.Flush;
Output.Close;
end Install;
end Gen.Artifacts.Distribs.Merges;
|
Add the ?build=<build> in the generated merged link and script links
|
Add the ?build=<build> in the generated merged link and script links
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
91cae67c717b1bd5b986e1f07d839e3dbe80ec53
|
awa/src/awa-events-queues.ads
|
awa/src/awa-events-queues.ads
|
-----------------------------------------------------------------------
-- awa-events-queues -- AWA Event Queues
-- Copyright (C) 2012, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Util.Refs;
with EL.Beans;
with EL.Contexts;
with AWA.Events.Models;
package AWA.Events.Queues is
type Queue_Ref is tagged private;
-- Queue the event.
procedure Enqueue (Into : in Queue_Ref;
Event : in AWA.Events.Module_Event'Class);
-- Dequeue an event and process it with the <b>Process</b> procedure.
procedure Dequeue (From : in Queue_Ref;
Process : access procedure (Event : in Module_Event'Class));
-- Returns true if the queue is available.
function Has_Queue (Queue : in Queue_Ref'Class) return Boolean;
-- Returns the queue name.
function Get_Name (Queue : in Queue_Ref'Class) return String;
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref;
-- Create the event queue identified by the name <b>Name</b>. The queue factory
-- identified by <b>Kind</b> is called to create the event queue instance.
-- Returns a reference to the queue.
function Create_Queue (Name : in String;
Kind : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class)
return Queue_Ref;
function Null_Queue return Queue_Ref;
private
type Queue is limited interface;
type Queue_Access is access all Queue'Class;
-- Get the queue name.
function Get_Name (From : in Queue) return String is abstract;
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
function Get_Queue (From : in Queue) return AWA.Events.Models.Queue_Ref is abstract;
-- Queue the event.
procedure Enqueue (Into : in out Queue;
Event : in AWA.Events.Module_Event'Class) is abstract;
-- Dequeue an event and process it with the <b>Process</b> procedure.
procedure Dequeue (From : in out Queue;
Process : access procedure (Event : in Module_Event'Class)) is abstract;
-- Release the queue storage.
procedure Finalize (From : in out Queue) is null;
type Queue_Info (Length : Natural) is new Util.Refs.Ref_Entity with record
Queue : Queue_Access := null;
Name : String (1 .. Length);
end record;
type Queue_Info_Access is access all Queue_Info;
-- Finalize the referenced object. This is called before the object is freed.
overriding
procedure Finalize (Object : in out Queue_Info);
package Queue_Refs is
new Util.Refs.Indefinite_References (Queue_Info, Queue_Info_Access);
subtype Queue_Info_Accessor is Queue_Refs.Element_Accessor;
type Queue_Ref is new Queue_Refs.Ref with null record;
end AWA.Events.Queues;
|
-----------------------------------------------------------------------
-- awa-events-queues -- AWA Event Queues
-- Copyright (C) 2012, 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.Listeners;
private with Util.Refs;
with EL.Beans;
with EL.Contexts;
with AWA.Events.Models;
package AWA.Events.Queues is
FIFO_QUEUE_TYPE : constant String := "fifo";
PERSISTENT_QUEUE_TYPE : constant String := "persist";
type Queue_Ref is tagged private;
-- Queue the event.
procedure Enqueue (Into : in Queue_Ref;
Event : in AWA.Events.Module_Event'Class);
-- Dequeue an event and process it with the <b>Process</b> procedure.
procedure Dequeue (From : in Queue_Ref;
Process : access procedure (Event : in Module_Event'Class));
-- Add a listener that will be called each time an event is queued.
procedure Add_Listener (Into : in Queue_Ref;
Listener : in Util.Listeners.Listener_Access);
-- Returns true if the queue is available.
function Has_Queue (Queue : in Queue_Ref'Class) return Boolean;
-- Returns the queue name.
function Get_Name (Queue : in Queue_Ref'Class) return String;
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
function Get_Queue (Queue : in Queue_Ref'Class) return Events.Models.Queue_Ref;
-- Create the event queue identified by the name `Name`. The queue factory
-- identified by `Kind` is called to create the event queue instance.
-- Returns a reference to the queue.
function Create_Queue (Name : in String;
Kind : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class)
return Queue_Ref;
function Null_Queue return Queue_Ref;
private
type Queue is limited interface;
type Queue_Access is access all Queue'Class;
-- Get the queue name.
function Get_Name (From : in Queue) return String is abstract;
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
function Get_Queue (From : in Queue) return Events.Models.Queue_Ref is abstract;
-- Queue the event.
procedure Enqueue (Into : in out Queue;
Event : in AWA.Events.Module_Event'Class) is abstract;
-- Dequeue an event and process it with the `Process` procedure.
procedure Dequeue (From : in out Queue;
Process : access procedure (Event : in Module_Event'Class)) is abstract;
-- Release the queue storage.
procedure Finalize (From : in out Queue) is null;
type Queue_Info (Length : Natural) is new Util.Refs.Ref_Entity with record
Queue : Queue_Access := null;
Listeners : Util.Listeners.List;
Name : String (1 .. Length);
end record;
type Queue_Info_Access is access all Queue_Info;
-- Finalize the referenced object. This is called before the object is freed.
overriding
procedure Finalize (Object : in out Queue_Info);
package Queue_Refs is
new Util.Refs.Indefinite_References (Queue_Info, Queue_Info_Access);
subtype Queue_Info_Accessor is Queue_Refs.Element_Accessor;
type Queue_Ref is new Queue_Refs.Ref with null record;
end AWA.Events.Queues;
|
Add Add_Listener to allow registration of a listener to be notified when the queue is updated
|
Add Add_Listener to allow registration of a listener to be notified when the queue is updated
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7a23e033f49a5a5e33f7fbe5b3a9a2b78fdbf9c8
|
src/sqlite/ado-connections-sqlite.adb
|
src/sqlite/ado-connections-sqlite.adb
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with Util.Processes.Tools;
with Util.Properties;
with ADO.Sessions;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Connections.Sqlite is
use Ada.Strings.Unbounded;
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Rollback;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
Log.Info ("Close connection {0}", Database.Name);
Database.Server := null;
end Close;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
protected body Sqlite_Connections is
procedure Open (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
use Strings;
URI : constant String := Config.Get_URI;
Database : Database_Connection_Access;
Pos : Database_List.Cursor := Database_List.First (List);
DB : SQLite_Database;
begin
-- Look first in the database list.
while Database_List.Has_Element (Pos) loop
DB := Database_List.Element (Pos);
if DB.URI = URI then
Database := new Database_Connection;
Database.URI := DB.URI;
Database.Name := DB.Name;
Database.Server := DB.Server;
Result := Ref.Create (Database.all'Access);
return;
end if;
Database_List.Next (Pos);
end loop;
-- Now we can open a new database connection.
declare
Name : constant String := Config.Get_Database;
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased access Sqlite3;
Flags : int
:= Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
if Config.Is_On (CREATE_NAME) then
Flags := Flags + Sqlite3_H.SQLITE_OPEN_CREATE;
end if;
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot open SQLite database: {0}", Msg);
raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg;
end;
end if;
Database := new Database_Connection;
declare
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Name /= CREATE_NAME then
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
ADO.Statements.Sqlite.Execute (Database.Server, SQL);
end if;
end if;
exception
when SQL_Error =>
null;
end Configure;
begin
Database.Server := Handle;
Database.Name := To_Unbounded_String (Config.Get_Database);
Database.URI := To_Unbounded_String (URI);
Result := Ref.Create (Database.all'Access);
DB.Server := Handle;
DB.Name := Database.Name;
DB.URI := Database.URI;
Database_List.Prepend (Container => List, New_Item => DB);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Iterate (Process => Configure'Access);
end;
end;
end Open;
procedure Clear is
DB : SQLite_Database;
Result : int;
begin
while not Database_List.Is_Empty (List) loop
DB := Database_List.First_Element (List);
Database_List.Delete_First (List);
if DB.Server /= null then
Result := Sqlite3_H.sqlite3_close_v2 (DB.Server);
if Result /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot close database {0}: {1}", To_String (DB.Name), Msg);
end;
end if;
end if;
end loop;
end Clear;
end Sqlite_Connections;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
begin
D.Map.Open (Config, Result);
end Create_Connection;
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
-- ------------------------------
overriding
procedure Create_Database (D : in out Sqlite_Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is
pragma Unreferenced (D, Admin);
Status : Integer;
Database_Path : constant String := Config.Get_Database;
Command : constant String :=
"sqlite3 --batch --init " & Schema_Path & " " & Database_Path;
begin
Log.Info ("Creating SQLite database {0}", Database_Path);
Util.Processes.Tools.Execute (Command, Messages, Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Status = 255 then
Messages.Append ("Command not found: " & Command);
Log.Error ("Command not found: {0}", Command);
else
Messages.Append ("Command " & Command & " failed with exit code "
& Util.Strings.Image (Status));
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Status));
end if;
end Create_Database;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the SQLite driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Sqlite_Driver) is
begin
Log.Debug ("Deleting the sqlite driver");
D.Map.Clear;
end Finalize;
end ADO.Connections.Sqlite;
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with Util.Processes.Tools;
with Util.Properties;
with ADO.Sessions;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Rollback;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
Log.Info ("Close connection {0}", Database.Name);
Database.Server := null;
end Close;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
protected body Sqlite_Connections is
procedure Open (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
use Strings;
URI : constant String := Config.Get_URI;
Database : Database_Connection_Access;
Pos : Database_List.Cursor := Database_List.First (List);
DB : SQLite_Database;
begin
-- Look first in the database list.
while Database_List.Has_Element (Pos) loop
DB := Database_List.Element (Pos);
if DB.URI = URI then
Database := new Database_Connection;
Database.URI := DB.URI;
Database.Name := DB.Name;
Database.Server := DB.Server;
Result := Ref.Create (Database.all'Access);
return;
end if;
Database_List.Next (Pos);
end loop;
-- Now we can open a new database connection.
declare
Name : constant String := Config.Get_Database;
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased access Sqlite3;
Flags : int
:= Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
if Config.Is_On (CREATE_NAME) then
Flags := Flags + Sqlite3_H.SQLITE_OPEN_CREATE;
end if;
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot open SQLite database: {0}", Msg);
raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg;
end;
end if;
Database := new Database_Connection;
declare
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Name /= CREATE_NAME then
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
ADO.Statements.Sqlite.Execute (Database.Server, SQL);
end if;
end if;
exception
when SQL_Error =>
null;
end Configure;
begin
Database.Server := Handle;
Database.Name := To_Unbounded_String (Config.Get_Database);
Database.URI := To_Unbounded_String (URI);
Result := Ref.Create (Database.all'Access);
DB.Server := Handle;
DB.Name := Database.Name;
DB.URI := Database.URI;
Database_List.Prepend (Container => List, New_Item => DB);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Iterate (Process => Configure'Access);
end;
end;
end Open;
procedure Clear is
DB : SQLite_Database;
Result : int;
begin
while not Database_List.Is_Empty (List) loop
DB := Database_List.First_Element (List);
Database_List.Delete_First (List);
if DB.Server /= null then
Result := Sqlite3_H.sqlite3_close_v2 (DB.Server);
if Result /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot close database {0}: {1}", To_String (DB.Name), Msg);
end;
end if;
end if;
end loop;
end Clear;
end Sqlite_Connections;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
begin
D.Map.Open (Config, Result);
end Create_Connection;
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
-- ------------------------------
overriding
procedure Create_Database (D : in out Sqlite_Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is
pragma Unreferenced (D, Admin);
Status : Integer;
Database_Path : constant String := Config.Get_Database;
Command : constant String :=
"sqlite3 --batch --init " & Schema_Path & " " & Database_Path;
begin
Log.Info ("Creating SQLite database {0}", Database_Path);
Util.Processes.Tools.Execute (Command, Messages, Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Status = 255 then
Messages.Append ("Command not found: " & Command);
Log.Error ("Command not found: {0}", Command);
else
Messages.Append ("Command " & Command & " failed with exit code "
& Util.Strings.Image (Status));
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Status));
end if;
end Create_Database;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the SQLite driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Sqlite_Driver) is
begin
Log.Debug ("Deleting the sqlite driver");
D.Map.Clear;
end Finalize;
end ADO.Connections.Sqlite;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
0c351c70ac515ad7979daba42211160893b73ad9
|
src/util-properties.ads
|
src/util-properties.ads
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Ada.Strings.Unbounded.Unbounded_String;
function "+" (S : String) return Value renames To_Unbounded_String;
function "-" (S : Value) return String renames To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
Refactor the Properties implementation (step 5): - Change type Value to refer to the Object - Define To_String operation for Value type - Update operations to use Unbounded_String for some name parameters
|
Refactor the Properties implementation (step 5):
- Change type Value to refer to the Object
- Define To_String operation for Value type
- Update operations to use Unbounded_String for some name parameters
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f30f49ebc9c75a3eeb968f801d67209d183f0db1
|
src/ado-drivers-dialects.ads
|
src/ado-drivers-dialects.ads
|
-----------------------------------------------------------------------
-- ADO Dialects -- Driver support for basic SQL Generation
-- 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.
-----------------------------------------------------------------------
-- The <b>ADO.Drivers.Dialects</b> package controls the database specific SQL dialects.
package ADO.Drivers.Dialects is
-- --------------------
-- SQL Dialect
-- --------------------
-- The <b>Dialect</b> defines the specific characteristics that must be
-- taken into account when building the SQL statement. This includes:
-- <ul>
-- <li>The definition of reserved keywords that must be escaped</li>
-- <li>How to escape those keywords</li>
-- <li>How to escape special characters</li>
-- </ul>
type Dialect is abstract tagged private;
type Dialect_Access is access all Dialect'Class;
-- Check if the string is a reserved keyword.
function Is_Reserved (D : Dialect;
Name : String) return Boolean is abstract;
-- Get the quote character to escape an identifier.
function Get_Identifier_Quote (D : in Dialect) return Character;
-- Append the item in the buffer escaping some characters if necessary.
-- The default implementation only escapes the single quote ' by doubling them.
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in String);
-- Append the item in the buffer escaping some characters if necessary
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in ADO.Blob_Ref);
private
type Dialect is abstract tagged null record;
end ADO.Drivers.Dialects;
|
-----------------------------------------------------------------------
-- ADO Dialects -- Driver support for basic SQL Generation
-- Copyright (C) 2010, 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ADO.Drivers.Dialects</b> package controls the database specific SQL dialects.
package ADO.Drivers.Dialects is
-- --------------------
-- SQL Dialect
-- --------------------
-- The <b>Dialect</b> defines the specific characteristics that must be
-- taken into account when building the SQL statement. This includes:
-- <ul>
-- <li>The definition of reserved keywords that must be escaped</li>
-- <li>How to escape those keywords</li>
-- <li>How to escape special characters</li>
-- </ul>
type Dialect is abstract tagged private;
type Dialect_Access is access all Dialect'Class;
-- Check if the string is a reserved keyword.
function Is_Reserved (D : Dialect;
Name : String) return Boolean is abstract;
-- Get the quote character to escape an identifier.
function Get_Identifier_Quote (D : in Dialect) return Character;
-- Append the item in the buffer escaping some characters if necessary.
-- The default implementation only escapes the single quote ' by doubling them.
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in String);
-- Append the item in the buffer escaping some characters if necessary
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in ADO.Blob_Ref);
-- Append the boolean item in the buffer.
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in Boolean);
private
type Dialect is abstract tagged null record;
end ADO.Drivers.Dialects;
|
Declare Escape_Sql to format a boolean value
|
Declare Escape_Sql to format a boolean value
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
0d24ce8f29e07f5d853dd102b29d40be673a897a
|
src/asf-servlets-mappers.adb
|
src/asf-servlets-mappers.adb
|
-----------------------------------------------------------------------
-- asf-servlets-mappers -- Read servlet configuration files
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with EL.Utils;
package body ASF.Servlets.Mappers is
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
use type Ada.Containers.Count_Type;
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String);
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Filter_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Filter_Name));
end Add_Filter;
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Servlet_Name));
end Add_Mapping;
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String) is
Last : constant Ada.Containers.Count_Type := N.URL_Patterns.Length;
begin
if Last = 0 then
raise Util.Serialize.Mappers.Field_Error with Message;
end if;
for I in 1 .. Last loop
N.URL_Patterns.Query_Element (Positive (I), Handler);
end loop;
N.URL_Patterns.Clear;
end Add_Mapping;
begin
-- <context-param>
-- <param-name>property</param-name>
-- <param-value>false</param-value>
-- </context-param>
-- <filter-mapping>
-- <filter-name>Dump Filter</filter-name>
-- <servlet-name>Faces Servlet</servlet-name>
-- </filter-mapping>
case Field is
when FILTER_NAME =>
N.Filter_Name := Value;
when SERVLET_NAME =>
N.Servlet_Name := Value;
when URL_PATTERN =>
N.URL_Patterns.Append (Value);
when PARAM_NAME =>
N.Param_Name := Value;
when PARAM_VALUE =>
N.Param_Value := EL.Utils.Eval (To_String (Value), N.Context.all);
when MIME_TYPE =>
N.Mime_Type := Value;
when EXTENSION =>
N.Extension := Value;
when ERROR_CODE =>
N.Error_Code := Value;
when LOCATION =>
N.Location := Value;
when FILTER_MAPPING =>
Add_Mapping (Add_Filter'Access, "Missing url-pattern for the filter mapping");
when SERVLET_MAPPING =>
Add_Mapping (Add_Mapping'Access, "Missing url-pattern for the servlet mapping");
when CONTEXT_PARAM =>
declare
Name : constant String := To_String (N.Param_Name);
begin
-- If the context parameter already has a value, do not set it again.
-- The value comes from an application setting and we want to keep it.
if N.Handler.Get_Init_Parameter (Name) = "" then
if Util.Beans.Objects.Is_Null (N.Param_Value) then
N.Handler.Set_Init_Parameter (Name => Name,
Value => "");
else
N.Handler.Set_Init_Parameter (Name => Name,
Value => To_String (N.Param_Value));
end if;
end if;
end;
when MIME_MAPPING =>
null;
when ERROR_PAGE =>
N.Handler.Set_Error_Page (Error => To_Integer (N.Error_Code),
Page => To_String (N.Location));
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>,
-- <b>filter-mapping</b> and <b>servlet-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("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 ("filter-mapping", FILTER_MAPPING);
SMapper.Add_Mapping ("filter-mapping/filter-name", FILTER_NAME);
SMapper.Add_Mapping ("filter-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("filter-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("servlet-mapping", SERVLET_MAPPING);
SMapper.Add_Mapping ("servlet-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("servlet-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("context-param", CONTEXT_PARAM);
SMapper.Add_Mapping ("context-param/param-name", PARAM_NAME);
SMapper.Add_Mapping ("context-param/param-value", PARAM_VALUE);
SMapper.Add_Mapping ("error-page", ERROR_PAGE);
SMapper.Add_Mapping ("error-page/error-code", ERROR_CODE);
SMapper.Add_Mapping ("error-page/location", LOCATION);
end ASF.Servlets.Mappers;
|
-----------------------------------------------------------------------
-- asf-servlets-mappers -- Read servlet configuration files
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with EL.Utils;
package body ASF.Servlets.Mappers is
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
use type Ada.Containers.Count_Type;
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String);
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Filter_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Filter_Name));
end Add_Filter;
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Servlet_Name));
end Add_Mapping;
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String) is
Last : constant Ada.Containers.Count_Type := N.URL_Patterns.Length;
begin
if Last = 0 then
raise Util.Serialize.Mappers.Field_Error with Message;
end if;
for I in 0 .. Last - 1 loop
N.URL_Patterns.Query_Element (Natural (I), Handler);
end loop;
N.URL_Patterns.Clear;
end Add_Mapping;
begin
-- <context-param>
-- <param-name>property</param-name>
-- <param-value>false</param-value>
-- </context-param>
-- <filter-mapping>
-- <filter-name>Dump Filter</filter-name>
-- <servlet-name>Faces Servlet</servlet-name>
-- </filter-mapping>
case Field is
when FILTER_NAME =>
N.Filter_Name := Value;
when SERVLET_NAME =>
N.Servlet_Name := Value;
when URL_PATTERN =>
N.URL_Patterns.Append (Value);
when PARAM_NAME =>
N.Param_Name := Value;
when PARAM_VALUE =>
N.Param_Value := EL.Utils.Eval (To_String (Value), N.Context.all);
when MIME_TYPE =>
N.Mime_Type := Value;
when EXTENSION =>
N.Extension := Value;
when ERROR_CODE =>
N.Error_Code := Value;
when LOCATION =>
N.Location := Value;
when FILTER_MAPPING =>
Add_Mapping (Add_Filter'Access, "Missing url-pattern for the filter mapping");
when SERVLET_MAPPING =>
Add_Mapping (Add_Mapping'Access, "Missing url-pattern for the servlet mapping");
when CONTEXT_PARAM =>
declare
Name : constant String := To_String (N.Param_Name);
begin
-- If the context parameter already has a value, do not set it again.
-- The value comes from an application setting and we want to keep it.
if N.Handler.Get_Init_Parameter (Name) = "" then
if Util.Beans.Objects.Is_Null (N.Param_Value) then
N.Handler.Set_Init_Parameter (Name => Name,
Value => "");
else
N.Handler.Set_Init_Parameter (Name => Name,
Value => To_String (N.Param_Value));
end if;
end if;
end;
when MIME_MAPPING =>
null;
when ERROR_PAGE =>
N.Handler.Set_Error_Page (Error => To_Integer (N.Error_Code),
Page => To_String (N.Location));
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>,
-- <b>filter-mapping</b> and <b>servlet-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("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 ("filter-mapping", FILTER_MAPPING);
SMapper.Add_Mapping ("filter-mapping/filter-name", FILTER_NAME);
SMapper.Add_Mapping ("filter-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("filter-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("servlet-mapping", SERVLET_MAPPING);
SMapper.Add_Mapping ("servlet-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("servlet-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("context-param", CONTEXT_PARAM);
SMapper.Add_Mapping ("context-param/param-name", PARAM_NAME);
SMapper.Add_Mapping ("context-param/param-value", PARAM_VALUE);
SMapper.Add_Mapping ("error-page", ERROR_PAGE);
SMapper.Add_Mapping ("error-page/error-code", ERROR_CODE);
SMapper.Add_Mapping ("error-page/location", LOCATION);
end ASF.Servlets.Mappers;
|
Fix the filter/servlet mapping installation
|
Fix the filter/servlet mapping installation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
0bfb993107fa06441f8b6c1b4bba2510d8315f27
|
src/asf-sessions-factory.adb
|
src/asf-sessions-factory.adb
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
use Interfaces;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Lock.Write;
-- Generate the random sequence.
for I in 0 .. Factory.Id_Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Factory.Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
Factory.Lock.Release_Write;
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access := new Session_Record;
begin
Impl.Ref_Counter := Util.Concurrent.Counters.ONE;
Impl.Create_Time := Ada.Calendar.Clock;
Impl.Access_Time := Impl.Create_Time;
Impl.Max_Inactive := Factory.Max_Inactive;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Lock.Write;
Factory.Sessions.Insert (Impl.Id.all'Access, Sess);
Factory.Lock.Release_Write;
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
null;
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Null_Session;
Factory.Lock.Read;
declare
Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
Result := Session_Maps.Element (Pos);
end if;
end;
Factory.Lock.Release_Read;
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Id_Random.Reset (Factory.Random);
end Initialize;
end ASF.Sessions.Factory;
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
use Interfaces;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Lock.Write;
-- Generate the random sequence.
for I in 0 .. Factory.Id_Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Factory.Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
Factory.Lock.Release_Write;
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access := new Session_Record;
begin
Impl.Ref_Counter := Util.Concurrent.Counters.ONE;
Impl.Create_Time := Ada.Calendar.Clock;
Impl.Access_Time := Impl.Create_Time;
Impl.Max_Inactive := Factory.Max_Inactive;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Lock.Write;
Factory.Sessions.Insert (Impl.Id.all'Access, Sess);
Factory.Lock.Release_Write;
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
null;
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Null_Session;
Factory.Lock.Read;
declare
Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
Result := Session_Maps.Element (Pos);
end if;
end;
Factory.Lock.Release_Read;
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Id_Random.Reset (Factory.Random);
end Initialize;
end ASF.Sessions.Factory;
|
Add logs on servlet session to help in fixing session issues in applications
|
Add logs on servlet session to help in fixing session issues in applications
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
e1774c49113d9975bcd170b100faf5c3b07b29f8
|
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 (Document : in out Filter_Type;
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 (Document : in out Filter_Type;
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 (Document : 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 (Document : in out Filter_Type;
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 (Document : in out Filter_Type;
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;
|
Rename Finish procedure parameter
|
Rename Finish procedure parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
ed023b1c07625bcf1eb22a8fa5b6eca554b80686
|
mat/src/frames/mat-frames.adb
|
mat/src/frames/mat-frames.adb
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Interfaces; use Interfaces;
with MAT.Types; use MAT.Types;
package body MAT.Frames is
procedure Free is
new Ada.Unchecked_Deallocation (Frame, Frame_Type);
-- ------------------------------
-- Return the parent frame.
-- ------------------------------
function Parent (Frame : in Frame_Type) return Frame_Type is
begin
if Frame = null then
return null;
else
return Frame.Parent;
end if;
end Parent;
-- Returns the backtrace of the current frame (up to the root).
function Backtrace (Frame : in Frame_Type) return Frame_Table is
Pc : Prame_Table (1 .. F.Depth);
Current : Frame_Type := Frame;
Pos : Natural := Current.Depth;
New_Pos : Natural;
begin
while Pos /= 0 loop
New_Pos := Pos - Current.Local_Depth + 1;
Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth);
Pos := New_Pos - 1;
Current := Current.Parent;
end loop;
return Pc;
end Backtrace;
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
function Count_Children (F : in Frame_Ptr;
Recursive : in Boolean := False) return Natural is
Count : Natural := 0;
N : Natural;
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
Count := Count + 1;
if Recursive then
declare
N : Natural := Count_Children (Child, True);
begin
if N > 0 then
N := N - 1;
end if;
Count := Count + N;
end;
end if;
Child := Child.Next;
end loop;
return Count;
end Count_Children;
-- Returns all the direct calls made by the current frame.
function Calls (F : in Frame_Ptr) return PC_Table is
Nb_Calls : Natural := Count_Children (F);
Pc : Pc_Table (1 .. Nb_Calls);
Child : Frame_Ptr := F.Children;
Pos : Natural := 1;
begin
while Child /= null loop
Pc (Pos) := Child.Calls (1);
Pos := Pos + 1;
Child := Child.Next;
end loop;
return Pc;
end Calls;
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
function Current_Depth (F : in Frame_Ptr) return Natural is
begin
return F.Depth;
end Current_Depth;
-- Create a root for stack frame representation.
function Create_Root return Frame_Ptr is
begin
return new Frame;
end Create_Root;
-- Destroy the frame tree recursively.
procedure Destroy (Tree : in out Frame_Ptr) is
F : Frame_Ptr;
begin
-- Destroy its children recursively.
while Tree.Children /= null loop
F := Tree.Children;
Destroy (F);
end loop;
-- Unlink from parent list.
if Tree.Parent /= null then
F := Tree.Parent.Children;
if F = Tree then
Tree.Parent.Children := Tree.Next;
else
while F /= null and F.Next /= Tree loop
F := F.Next;
end loop;
if F = null then
raise Program_Error;
end if;
F.Next := Tree.Next;
end if;
end if;
Free (Tree);
end Destroy;
-- Release the frame when its reference is no longer necessary.
procedure Release (F : in Frame_Ptr) is
Current : Frame_Ptr := F;
begin
-- Scan the fram until the root is reached
-- and decrement the used counter. Free the frames
-- when the used counter reaches 0.
while Current /= null loop
if Current.Used <= 1 then
declare
Tree : Frame_Ptr := Current;
begin
Current := Current.Parent;
Destroy (Tree);
end;
else
Current.Used := Current.Used - 1;
Current := Current.Parent;
end if;
end loop;
end Release;
-- Split the node pointed to by `F' at the position `Pos'
-- in the caller chain. A new parent is created for the node
-- and the brothers of the node become the brothers of the
-- new parent.
--
-- Returns in `F' the new parent node.
procedure Split (F : in out Frame_Ptr; Pos : in Positive) is
-- Before: After:
--
-- +-------+ +-------+
-- /-| P | /-| P |
-- | +-------+ | +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ...>| node |... ....>| new |... (0..N brothers)
-- +-------+ +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ->| c | ->| node |-->0 (0 brother)
-- +-------+ +-------+
-- |
-- +-------+
-- | c |
-- +-------+
--
New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent,
Next => F.Next,
Children => F,
Used => F.Used,
Depth => F.Depth,
Local_Depth => Pos,
Calls => (others => 0));
Child : Frame_Ptr := F.Parent.Children;
begin
-- Move the PC values in the new parent.
New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos);
F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth);
F.Parent := New_Parent;
F.Next := null;
New_Parent.Depth := F.Depth - F.Local_Depth + Pos;
F.Local_Depth := F.Local_Depth - Pos;
-- Remove F from its parent children list and replace if with New_Parent.
if Child = F then
New_Parent.Parent.Children := New_Parent;
else
while Child.Next /= F loop
Child := Child.Next;
end loop;
Child.Next := New_Parent;
end if;
F := New_Parent;
end Split;
procedure Add_Frame (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Current_Depth : Natural := F.Depth;
Cnt : Local_Depth_Type;
begin
while Pos <= Pc'Last loop
Cnt := Frame_Group_Size;
if Pos + Cnt > Pc'Last then
Cnt := Pc'Last - Pos + 1;
end if;
Current_Depth := Current_Depth + Cnt;
Child := new Frame '(Parent => Child,
Next => Child.Children,
Children => null,
Used => 1,
Depth => Current_Depth,
Local_Depth => Cnt,
Calls => (others => 0));
Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1);
Pos := Pos + Cnt;
Child.Parent.Children := Child;
end loop;
Result := Child;
end Add_Frame;
procedure Insert (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Current : Frame_Ptr := F;
Child : Frame_Ptr;
Pos : Positive := Pc'First;
Lpos : Positive := 1;
Addr : Target_Addr;
begin
while Pos <= Pc'Last loop
Addr := Pc (Pos);
if Lpos <= Current.Local_Depth then
if Addr = Current.Calls (Lpos) then
Lpos := Lpos + 1;
Pos := Pos + 1;
-- Split this node
else
if Lpos > 1 then
Split (Current, Lpos - 1);
end if;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
else
-- Find the first child which has the address.
Child := Current.Children;
while Child /= null loop
exit when Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
if Child = null then
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
Current := Child;
Lpos := 2;
Pos := Pos + 1;
Current.Used := Current.Used + 1;
end if;
end loop;
if Lpos <= Current.Local_Depth then
Split (Current, Lpos - 1);
end if;
Result := Current;
end Insert;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then
return Child;
end if;
Child := Child.Next;
end loop;
raise Not_Found;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
while Pos <= Pc'Last loop
Child := Find (Child, Pc (Pos));
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop
if Child.Calls (Lpos) /= Pc (Pos) then
raise Not_Found;
end if;
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end loop;
return Child;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (F : in Frame_Ptr;
Pc : in PC_Table;
Result : out Frame_Ptr;
Last_Pc : out Natural) is
Current : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
Main_Search:
while Pos <= Pc'Last loop
declare
Addr : Target_Addr := Pc (Pos);
Child : Frame_Ptr := Current.Children;
begin
-- Find the child which has the corresponding PC.
loop
exit Main_Search when Child = null;
exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
Current := Child;
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop
exit Main_Search when Current.Calls (Lpos) /= Pc (Pos);
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end;
end loop Main_Search;
Result := Current;
if Pos > Pc'Last then
Last_Pc := 0;
else
Last_Pc := Pos;
end if;
end Find;
end MAT.Frames;
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Interfaces; use Interfaces;
with MAT.Types; use MAT.Types;
package body MAT.Frames is
procedure Free is
new Ada.Unchecked_Deallocation (Frame, Frame_Type);
-- ------------------------------
-- Return the parent frame.
-- ------------------------------
function Parent (Frame : in Frame_Type) return Frame_Type is
begin
if Frame = null then
return null;
else
return Frame.Parent;
end if;
end Parent;
-- ------------------------------
-- Returns the backtrace of the current frame (up to the root).
-- ------------------------------
function Backtrace (Frame : in Frame_Type) return Frame_Table is
Pc : Frame_Table (1 .. Frame.Depth);
Current : Frame_Type := Frame;
Pos : Natural := Current.Depth;
New_Pos : Natural;
begin
while Current /= null and Pos /= 0 loop
New_Pos := Pos - Current.Local_Depth + 1;
Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth);
Pos := New_Pos - 1;
Current := Current.Parent;
end loop;
return Pc;
end Backtrace;
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
function Count_Children (F : in Frame_Ptr;
Recursive : in Boolean := False) return Natural is
Count : Natural := 0;
N : Natural;
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
Count := Count + 1;
if Recursive then
declare
N : Natural := Count_Children (Child, True);
begin
if N > 0 then
N := N - 1;
end if;
Count := Count + N;
end;
end if;
Child := Child.Next;
end loop;
return Count;
end Count_Children;
-- Returns all the direct calls made by the current frame.
function Calls (F : in Frame_Ptr) return PC_Table is
Nb_Calls : Natural := Count_Children (F);
Pc : Pc_Table (1 .. Nb_Calls);
Child : Frame_Ptr := F.Children;
Pos : Natural := 1;
begin
while Child /= null loop
Pc (Pos) := Child.Calls (1);
Pos := Pos + 1;
Child := Child.Next;
end loop;
return Pc;
end Calls;
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
function Current_Depth (F : in Frame_Ptr) return Natural is
begin
return F.Depth;
end Current_Depth;
-- Create a root for stack frame representation.
function Create_Root return Frame_Ptr is
begin
return new Frame;
end Create_Root;
-- Destroy the frame tree recursively.
procedure Destroy (Tree : in out Frame_Ptr) is
F : Frame_Ptr;
begin
-- Destroy its children recursively.
while Tree.Children /= null loop
F := Tree.Children;
Destroy (F);
end loop;
-- Unlink from parent list.
if Tree.Parent /= null then
F := Tree.Parent.Children;
if F = Tree then
Tree.Parent.Children := Tree.Next;
else
while F /= null and F.Next /= Tree loop
F := F.Next;
end loop;
if F = null then
raise Program_Error;
end if;
F.Next := Tree.Next;
end if;
end if;
Free (Tree);
end Destroy;
-- Release the frame when its reference is no longer necessary.
procedure Release (F : in Frame_Ptr) is
Current : Frame_Ptr := F;
begin
-- Scan the fram until the root is reached
-- and decrement the used counter. Free the frames
-- when the used counter reaches 0.
while Current /= null loop
if Current.Used <= 1 then
declare
Tree : Frame_Ptr := Current;
begin
Current := Current.Parent;
Destroy (Tree);
end;
else
Current.Used := Current.Used - 1;
Current := Current.Parent;
end if;
end loop;
end Release;
-- Split the node pointed to by `F' at the position `Pos'
-- in the caller chain. A new parent is created for the node
-- and the brothers of the node become the brothers of the
-- new parent.
--
-- Returns in `F' the new parent node.
procedure Split (F : in out Frame_Ptr; Pos : in Positive) is
-- Before: After:
--
-- +-------+ +-------+
-- /-| P | /-| P |
-- | +-------+ | +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ...>| node |... ....>| new |... (0..N brothers)
-- +-------+ +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ->| c | ->| node |-->0 (0 brother)
-- +-------+ +-------+
-- |
-- +-------+
-- | c |
-- +-------+
--
New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent,
Next => F.Next,
Children => F,
Used => F.Used,
Depth => F.Depth,
Local_Depth => Pos,
Calls => (others => 0));
Child : Frame_Ptr := F.Parent.Children;
begin
-- Move the PC values in the new parent.
New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos);
F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth);
F.Parent := New_Parent;
F.Next := null;
New_Parent.Depth := F.Depth - F.Local_Depth + Pos;
F.Local_Depth := F.Local_Depth - Pos;
-- Remove F from its parent children list and replace if with New_Parent.
if Child = F then
New_Parent.Parent.Children := New_Parent;
else
while Child.Next /= F loop
Child := Child.Next;
end loop;
Child.Next := New_Parent;
end if;
F := New_Parent;
end Split;
procedure Add_Frame (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Current_Depth : Natural := F.Depth;
Cnt : Local_Depth_Type;
begin
while Pos <= Pc'Last loop
Cnt := Frame_Group_Size;
if Pos + Cnt > Pc'Last then
Cnt := Pc'Last - Pos + 1;
end if;
Current_Depth := Current_Depth + Cnt;
Child := new Frame '(Parent => Child,
Next => Child.Children,
Children => null,
Used => 1,
Depth => Current_Depth,
Local_Depth => Cnt,
Calls => (others => 0));
Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1);
Pos := Pos + Cnt;
Child.Parent.Children := Child;
end loop;
Result := Child;
end Add_Frame;
procedure Insert (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Current : Frame_Ptr := F;
Child : Frame_Ptr;
Pos : Positive := Pc'First;
Lpos : Positive := 1;
Addr : Target_Addr;
begin
while Pos <= Pc'Last loop
Addr := Pc (Pos);
if Lpos <= Current.Local_Depth then
if Addr = Current.Calls (Lpos) then
Lpos := Lpos + 1;
Pos := Pos + 1;
-- Split this node
else
if Lpos > 1 then
Split (Current, Lpos - 1);
end if;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
else
-- Find the first child which has the address.
Child := Current.Children;
while Child /= null loop
exit when Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
if Child = null then
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
Current := Child;
Lpos := 2;
Pos := Pos + 1;
Current.Used := Current.Used + 1;
end if;
end loop;
if Lpos <= Current.Local_Depth then
Split (Current, Lpos - 1);
end if;
Result := Current;
end Insert;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then
return Child;
end if;
Child := Child.Next;
end loop;
raise Not_Found;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
while Pos <= Pc'Last loop
Child := Find (Child, Pc (Pos));
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop
if Child.Calls (Lpos) /= Pc (Pos) then
raise Not_Found;
end if;
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end loop;
return Child;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (F : in Frame_Ptr;
Pc : in PC_Table;
Result : out Frame_Ptr;
Last_Pc : out Natural) is
Current : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
Main_Search:
while Pos <= Pc'Last loop
declare
Addr : Target_Addr := Pc (Pos);
Child : Frame_Ptr := Current.Children;
begin
-- Find the child which has the corresponding PC.
loop
exit Main_Search when Child = null;
exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
Current := Child;
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop
exit Main_Search when Current.Calls (Lpos) /= Pc (Pos);
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end;
end loop Main_Search;
Result := Current;
if Pos > Pc'Last then
Last_Pc := 0;
else
Last_Pc := Pos;
end if;
end Find;
end MAT.Frames;
|
Refactor the Backtrace operation
|
Refactor the Backtrace operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
6f371af13a8ba870eee9b1ad5c3b256adc39e763
|
awa/plugins/awa-blogs/src/awa-blogs.ads
|
awa/plugins/awa-blogs/src/awa-blogs.ads
|
-----------------------------------------------------------------------
-- awa-blogs -- Blogs module
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The *blogs* plugin is a small blog application which allows users to publish articles.
--
-- @include blogs.xml
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_blogs_model.png]
--
-- @include Blog.hbm.xml
--
package AWA.Blogs is
end AWA.Blogs;
|
-----------------------------------------------------------------------
-- awa-blogs -- Blogs module
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The *blogs* plugin is a small blog application which allows users to publish articles.
--
-- == Ada Beans ==
-- @include blogs.xml
--
-- == Queries ==
-- @include blog-admin-post-list.xml
-- @include blog-post-list.xml
-- @include blog-list.xml
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_blogs_model.png]
--
-- @include Blog.hbm.xml
--
package AWA.Blogs is
end AWA.Blogs;
|
Add the specific queries and Ada beans in the documentation
|
Add the specific queries and Ada beans in the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.