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
|
---|---|---|---|---|---|---|---|---|---|
9c979e365e7e93c01db3edbb9d53a1bd22450c6a
|
matp/src/mat-expressions.ads
|
matp/src/mat-expressions.ads
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events.Targets;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE,
INSIDE_DIRECT_FILE,
INSIDE_FUNCTION,
INSIDE_DIRECT_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Create an event ID range expression node.
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type;
-- Create a thread ID range expression node.
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME, N_EVENT,
N_CONDITION, N_THREAD);
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Min_Thread : MAT.Types.Target_Thread_Ref;
Max_Thread : MAT.Types.Target_Thread_Ref;
when N_EVENT =>
Min_Event : MAT.Events.Targets.Event_Id_Type;
Max_Event : MAT.Events.Targets.Event_Id_Type;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events.Targets;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE,
INSIDE_DIRECT_FILE,
INSIDE_FUNCTION,
INSIDE_DIRECT_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Create an event ID range expression node.
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type;
-- Create a thread ID range expression node.
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type;
-- Create a event type expression check.
function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type)
return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME, N_EVENT,
N_CONDITION, N_THREAD, N_TYPE);
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Min_Thread : MAT.Types.Target_Thread_Ref;
Max_Thread : MAT.Types.Target_Thread_Ref;
when N_EVENT =>
Min_Event : MAT.Events.Targets.Event_Id_Type;
Max_Event : MAT.Events.Targets.Event_Id_Type;
when N_TYPE =>
Event_Kind : MAT.Events.Targets.Probe_Index_Type;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
Declare the Create_Event_Type function and add the N_TYPE expression node
|
Declare the Create_Event_Type function and add the N_TYPE expression node
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
4b6cb4655b33b7ccf6d41dc7ed0ab7fe9ca90042
|
testutil/aunit/util-test_caller.adb
|
testutil/aunit/util-test_caller.adb
|
-----------------------------------------------------------------------
-- AUnit utils - Helper for writing unit tests
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Test_Caller is
procedure Add_Test (Suite : in Util.Tests.Access_Test_Suite;
Test_Name : in String;
Method : in Caller.Test_Method) is
begin
Suite.Add_Test (Caller.Create (Test_Name, Method));
end Add_Test;
end Util.Test_Caller;
|
-----------------------------------------------------------------------
-- AUnit utils - Helper for writing unit tests
-- Copyright (C) 2009, 2010, 2011, 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 Util.Test_Caller is
procedure Add_Test (Suite : in Util.Tests.Access_Test_Suite;
Test_Name : in String;
Method : in Caller.Test_Method) is
begin
if Util.Tests.Is_Test_Enabled (Test_Name) then
Suite.Add_Test (Caller.Create (Test_Name, Method));
end if;
end Add_Test;
end Util.Test_Caller;
|
Use the Is_Test_Enabled function to ignore or take into account the test when it is added in the testsuite.
|
Use the Is_Test_Enabled function to ignore or take into account the
test when it is added in the testsuite.
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
07b4c3001129107683d3bcca9e6d6695288aa62c
|
src/asf-filters.ads
|
src/asf-filters.ads
|
-----------------------------------------------------------------------
-- asf.filters -- ASF Filters
-- 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 ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
-- The <b>ASF.Filters</b> package defines the servlet filter
-- interface described in Java Servlet Specification, JSR 315, 6. Filtering.
--
package ASF.Filters is
-- ------------------------------
-- Filter interface
-- ------------------------------
-- The <b>Filter</b> interface defines one mandatory procedure through
-- which the request/response pair are passed.
--
-- The <b>Filter</b> instance must be registered in the <b>Servlet_Registry</b>
-- by using the <b>Add_Filter</b> procedure. The same filter instance is used
-- to process multiple requests possibly at the same time.
type Filter is limited interface;
type Filter_Access is access all Filter'Class;
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- A typical implementation of this method would follow the following pattern:
-- 1. Examine the request
-- 2. Optionally wrap the request object with a custom implementation to
-- filter content or headers for input filtering
-- 3. Optionally wrap the response object with a custom implementation to
-- filter content or headers for output filtering
-- 4. Either invoke the next entity in the chain using the FilterChain
-- object (chain.Do_Filter()),
-- or, not pass on the request/response pair to the next entity in the
-- filter chain to block the request processing
-- 5. Directly set headers on the response after invocation of the next
-- entity in the filter chain.
procedure Do_Filter (F : in Filter;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is abstract;
-- Called by the servlet container to indicate to a filter that the filter
-- instance is being placed into service.
procedure Initialize (Server : in out Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is null;
end ASF.Filters;
|
-----------------------------------------------------------------------
-- asf.filters -- ASF Filters
-- Copyright (C) 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
-- The <b>ASF.Filters</b> package defines the servlet filter
-- interface described in Java Servlet Specification, JSR 315, 6. Filtering.
--
package ASF.Filters is
-- ------------------------------
-- Filter interface
-- ------------------------------
-- The <b>Filter</b> interface defines one mandatory procedure through
-- which the request/response pair are passed.
--
-- The <b>Filter</b> instance must be registered in the <b>Servlet_Registry</b>
-- by using the <b>Add_Filter</b> procedure. The same filter instance is used
-- to process multiple requests possibly at the same time.
type Filter is limited interface;
type Filter_Access is access all Filter'Class;
type Filter_List is array (Natural range <>) of Filter_Access;
type Filter_List_Access is access all Filter_List;
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- A typical implementation of this method would follow the following pattern:
-- 1. Examine the request
-- 2. Optionally wrap the request object with a custom implementation to
-- filter content or headers for input filtering
-- 3. Optionally wrap the response object with a custom implementation to
-- filter content or headers for output filtering
-- 4. Either invoke the next entity in the chain using the FilterChain
-- object (chain.Do_Filter()),
-- or, not pass on the request/response pair to the next entity in the
-- filter chain to block the request processing
-- 5. Directly set headers on the response after invocation of the next
-- entity in the filter chain.
procedure Do_Filter (F : in Filter;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is abstract;
-- Called by the servlet container to indicate to a filter that the filter
-- instance is being placed into service.
procedure Initialize (Server : in out Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is null;
end ASF.Filters;
|
Declare Filter_List and Filter_List_Access types
|
Declare Filter_List and Filter_List_Access types
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
6e48e3088a75807a2f48846cbc111cf634fe385a
|
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 := "22";
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 := "30";
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 to 1.30
|
Bump version to 1.30
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
a0c5c9bd6f6f122190bed7d93283a92dec70cd79
|
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");
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;
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");
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;
|
Call the initialize procedure that is now separate (as in previous ADO versions)
|
Call the initialize procedure that is now separate (as in previous ADO versions)
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
24bb58eb2b6e67bf43f7a8f2bbcd9acb70d28580
|
awa/src/awa-applications-factory.adb
|
awa/src/awa-applications-factory.adb
|
-----------------------------------------------------------------------
-- 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 AWA.Permissions.Managers;
with AWA.Permissions.Services;
package body AWA.Applications.Factory is
-- ------------------------------
-- 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 is
begin
return AWA.Permissions.Services.Create_Permission_Manager (App.App);
end Create_Permission_Manager;
-- ------------------------------
-- 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) is
begin
if Factory in Application_Factory'Class then
Application_Factory'Class (Factory).App := App;
end if;
end Set_Application;
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 AWA.Permissions.Services;
package body AWA.Applications.Factory is
-- ------------------------------
-- 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 is
begin
return AWA.Permissions.Services.Create_Permission_Manager (App.App);
end Create_Security_Manager;
-- ------------------------------
-- 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) is
begin
if Factory in Application_Factory'Class then
Application_Factory'Class (Factory).App := App;
end if;
end Set_Application;
end AWA.Applications.Factory;
|
Rename Create_Permission_Manager into Create_Security_Manager
|
Rename Create_Permission_Manager into Create_Security_Manager
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
84ef0a540021e76516662d9b7c3e276e6ab45844
|
src/util-systems.ads
|
src/util-systems.ads
|
-----------------------------------------------------------------------
-- util-systems -- System specific utilities
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Util.Systems is
pragma Preelaborate;
end Util.Systems;
|
-----------------------------------------------------------------------
-- util-systems -- System specific utilities
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Util.Systems is
pragma Pure;
end Util.Systems;
|
Make this package Pure
|
Make this package Pure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
aecf0dbfed91d12b4ba8e1573764dfa74f9953cb
|
src/sys/streams/util-streams-buffered-encoders.adb
|
src/sys/streams/util-streams-buffered-encoders.adb
|
-----------------------------------------------------------------------
-- util-streams-encoders -- Streams with encoding and decoding capabilities
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
package body Util.Streams.Buffered.Encoders is
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
procedure Initialize (Stream : in out Encoding_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String) is
pragma Unreferenced (Format);
begin
Stream.Initialize (Output, Size);
Stream.Transform := new Util.Encoders.Base64.Encoder;
end Initialize;
-- -----------------------
-- Close the sink.
-- -----------------------
overriding
procedure Close (Stream : in out Encoding_Stream) is
begin
Stream.Flush;
Stream.Output.Close;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Encoding_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First;
Last_Encoded : Ada.Streams.Stream_Element_Offset;
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
while First_Encoded <= Buffer'Last loop
Stream.Transform.Transform
(Data => Buffer (First_Encoded .. Buffer'Last),
Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last => Last_Pos,
Encoded => Last_Encoded);
if Last_Encoded < Buffer'Last then
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Write_Pos := Stream.Buffer'First;
else
Stream.Write_Pos := Last_Pos + 1;
end if;
First_Encoded := Last_Encoded + 1;
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Encoding_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1;
begin
Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last_Pos);
Stream.Write_Pos := Last_Pos + 1;
Output_Buffer_Stream (Stream).Flush;
end Flush;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Encoding_Stream) is
begin
null;
end Finalize;
end Util.Streams.Buffered.Encoders;
|
-----------------------------------------------------------------------
-- util-streams-encoders -- Streams with encoding and decoding capabilities
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
package body Util.Streams.Buffered.Encoders is
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
procedure Initialize (Stream : in out Encoding_Stream;
Output : access Output_Stream'Class;
Size : in Natural;
Format : in String) is
pragma Unreferenced (Format);
begin
Stream.Initialize (Output, Size);
Stream.Transform := new Util.Encoders.Base64.Encoder;
end Initialize;
-- -----------------------
-- Close the sink.
-- -----------------------
overriding
procedure Close (Stream : in out Encoding_Stream) is
begin
Stream.Flush;
Stream.Output.Close;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Encoding_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First;
Last_Encoded : Ada.Streams.Stream_Element_Offset;
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
while First_Encoded <= Buffer'Last loop
Stream.Transform.Transform
(Data => Buffer (First_Encoded .. Buffer'Last),
Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last => Last_Pos,
Encoded => Last_Encoded);
if Last_Encoded < Buffer'Last then
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Write_Pos := Stream.Buffer'First;
else
Stream.Write_Pos := Last_Pos + 1;
end if;
First_Encoded := Last_Encoded + 1;
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Encoding_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1;
begin
Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last_Pos);
Stream.Write_Pos := Last_Pos + 1;
Output_Buffer_Stream (Stream).Flush;
end Flush;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Encoding_Stream) is
begin
null;
end Finalize;
end Util.Streams.Buffered.Encoders;
|
Use anonymous access type for the input and output streams
|
Use anonymous access type for the input and output streams
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c00240c2c907b6f997a2fb9db23dacd5a236e721
|
mat/src/mat-types.ads
|
mat/src/mat-types.ads
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
package MAT.Types is
type String_Ptr is access all String;
subtype Uint8 is Interfaces.Unsigned_8;
subtype Uint16 is Interfaces.Unsigned_16;
subtype Uint32 is Interfaces.Unsigned_32;
subtype Uint64 is Interfaces.Unsigned_64;
subtype Target_Addr is Interfaces.Unsigned_32;
subtype Target_Size is Interfaces.Unsigned_32;
subtype Target_Offset is Interfaces.Unsigned_32;
subtype Target_Tick_Ref is Uint64;
subtype Target_Thread_Ref is Uint32;
subtype Target_Process_Ref is Uint32;
subtype Target_Time is Uint64;
-- Return an hexadecimal string representation of the value.
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String;
-- Format the target time to a printable representation.
function Tick_Image (Value : in Target_Tick_Ref) return String;
end MAT.Types;
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
package MAT.Types is
type String_Ptr is access all String;
subtype Uint8 is Interfaces.Unsigned_8;
subtype Uint16 is Interfaces.Unsigned_16;
subtype Uint32 is Interfaces.Unsigned_32;
subtype Uint64 is Interfaces.Unsigned_64;
subtype Target_Addr is Interfaces.Unsigned_32;
subtype Target_Size is Interfaces.Unsigned_32;
subtype Target_Offset is Interfaces.Unsigned_32;
type Target_Tick_Ref is new Uint64;
type Target_Thread_Ref is new Uint32;
subtype Target_Process_Ref is Uint32;
subtype Target_Time is Target_Tick_Ref;
-- Return an hexadecimal string representation of the value.
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String;
-- Format the target time to a printable representation.
function Tick_Image (Value : in Target_Tick_Ref) return String;
function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref;
end MAT.Types;
|
Make Target_Tick_Ref, Target_Thread_Ref a new type
|
Make Target_Tick_Ref, Target_Thread_Ref a new type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
be9a12a2de15ff47e8e37350bdb9f8de0a307156
|
src/gen-commands-propset.ads
|
src/gen-commands-propset.ads
|
-----------------------------------------------------------------------
-- gen-commands-propset -- Set a property on dynamo project
-- Copyright (C) 2011, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Propset is
-- ------------------------------
-- Propset Command
-- ------------------------------
-- This command sets a property in the dynamo project configuration.
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Propset;
|
-----------------------------------------------------------------------
-- gen-commands-propset -- Set a property on dynamo project
-- Copyright (C) 2011, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Propset is
-- ------------------------------
-- Propset Command
-- ------------------------------
-- This command sets a property in the dynamo project configuration.
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Name : in String;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Propset;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
e6ce4976019af0093ba9c3b1c8d5fb5825286a0d
|
samples/csv_city.adb
|
samples/csv_city.adb
|
-----------------------------------------------------------------------
-- csv_city -- Read CSV file which contains city mapping
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Containers;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Serialize.IO.CSV;
with City_Mapping;
procedure CSV_City is
use Ada.Containers;
use Ada.Strings.Unbounded;
use Ada.Text_IO;
use Util.Serialize.IO.CSV;
Count : constant Natural := Ada.Command_Line.Argument_Count;
begin
Util.Log.Loggers.Initialize ("samples/log4j.properties");
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: csv_city file [city...]");
Ada.Text_IO.Put_Line ("Example: csv_city samples/cities.csv albertville");
return;
end if;
declare
File : constant String := Ada.Command_Line.Argument (1);
List : aliased City_Mapping.City_Vector.Vector;
Reader : Util.Serialize.IO.CSV.Parser;
begin
Reader.Add_Mapping ("", City_Mapping.Get_City_Vector_Mapper.all'Access);
City_Mapping.City_Vector_Mapper.Set_Context (Reader, List'Unchecked_Access);
Reader.Parse (File);
if List.Length = 0 then
Ada.Text_IO.Put_Line ("No city found.");
elsif List.Length = 1 then
Ada.Text_IO.Put_Line ("Found only one city.");
else
Ada.Text_IO.Put_Line ("Found " & Count_Type'Image (List.Length) & " cities");
end if;
for I in 2 .. Count loop
declare
Name : constant String := Ada.Command_Line.Argument (I);
Found : Boolean := False;
procedure Print (City : in City_Mapping.City);
procedure Print (City : in City_Mapping.City) is
begin
Found := City.City = Name;
if Found then
Ada.Text_IO.Put_Line ("City : " & To_String (City.Name));
Ada.Text_IO.Put_Line ("Country code: " & To_String (City.Country));
Ada.Text_IO.Put_Line ("Region : " & To_String (City.Region));
Ada.Text_IO.Put_Line ("Latitude : " & Float'Image (City.Latitude));
Ada.Text_IO.Put_Line ("Longitude : " & Float'Image (City.Longitude));
end if;
end Print;
begin
for J in 1 .. Positive (List.Length) loop
List.Query_Element (J, Print'Access);
exit when Found;
end loop;
if not Found then
Ada.Text_IO.Put_Line ("City '" & Name & "' not found");
end if;
end;
end loop;
end;
end CSV_City;
|
-----------------------------------------------------------------------
-- csv_city -- Read CSV file which contains city mapping
-- Copyright (C) 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Containers;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Serialize.IO.CSV;
with Util.Serialize.Mappers;
with City_Mapping;
procedure CSV_City is
use Ada.Containers;
use Ada.Strings.Unbounded;
use Ada.Text_IO;
use Util.Serialize.IO.CSV;
Count : constant Natural := Ada.Command_Line.Argument_Count;
begin
Util.Log.Loggers.Initialize ("samples/log4j.properties");
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: csv_city file [city...]");
Ada.Text_IO.Put_Line ("Example: csv_city samples/cities.csv albertville");
return;
end if;
declare
File : constant String := Ada.Command_Line.Argument (1);
List : aliased City_Mapping.City_Vector.Vector;
Mapper : aliased Util.Serialize.Mappers.Processing;
Reader : Util.Serialize.IO.CSV.Parser;
begin
Mapper.Add_Mapping ("", City_Mapping.Get_City_Vector_Mapper.all'Access);
City_Mapping.City_Vector_Mapper.Set_Context (Mapper, List'Unchecked_Access);
Reader.Parse (File, Mapper);
if List.Length = 0 then
Ada.Text_IO.Put_Line ("No city found.");
elsif List.Length = 1 then
Ada.Text_IO.Put_Line ("Found only one city.");
else
Ada.Text_IO.Put_Line ("Found " & Count_Type'Image (List.Length) & " cities");
end if;
for I in 2 .. Count loop
declare
Name : constant String := Ada.Command_Line.Argument (I);
Found : Boolean := False;
procedure Print (City : in City_Mapping.City);
procedure Print (City : in City_Mapping.City) is
begin
Found := City.City = Name;
if Found then
Ada.Text_IO.Put_Line ("City : " & To_String (City.Name));
Ada.Text_IO.Put_Line ("Country code: " & To_String (City.Country));
Ada.Text_IO.Put_Line ("Region : " & To_String (City.Region));
Ada.Text_IO.Put_Line ("Latitude : " & Float'Image (City.Latitude));
Ada.Text_IO.Put_Line ("Longitude : " & Float'Image (City.Longitude));
end if;
end Print;
begin
for J in 1 .. Positive (List.Length) loop
List.Query_Element (J, Print'Access);
exit when Found;
end loop;
if not Found then
Ada.Text_IO.Put_Line ("City '" & Name & "' not found");
end if;
end;
end loop;
end;
end CSV_City;
|
Update the city example to use the new parser/mapper interface
|
Update the city example to use the new parser/mapper interface
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a6314e28ed4cfda7b3aeb42325c231c4a21d5c1a
|
awa/plugins/awa-votes/src/awa-votes.ads
|
awa/plugins/awa-votes/src/awa-votes.ads
|
-----------------------------------------------------------------------
-- awa-votes -- Module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Votes</b> module allows users to vote for objects defined in the application.
-- Users can vote by setting a rating value on an item (+1, -1 or any other integer value).
-- The Votes module makes sure that users can vote only once for an item. A global rating
-- is associated with the item to give the vote summary. The vote can be associated with
-- any database entity and it is not necessary to change other entities data model.
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_votes_model.png]
--
-- == Integration ==
-- To add the <b>Votes</b> module in an application, the <tt>Vote_Module</tt> instance must
-- be declared and registered in the AWA application.
--
-- @include awa-votes-beans.ads
package AWA.Votes is
pragma Preelaborate;
end AWA.Votes;
|
-----------------------------------------------------------------------
-- awa-votes -- Module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Votes</b> module allows users to vote for objects defined in the application.
-- Users can vote by setting a rating value on an item (+1, -1 or any other integer value).
-- The Votes module makes sure that users can vote only once for an item. A global rating
-- is associated with the item to give the vote summary. The vote can be associated with
-- any database entity and it is not necessary to change other entities in your data model.
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_votes_model.png]
--
-- == Integration ==
-- To add the <b>Votes</b> module in an application, the <tt>Vote_Module</tt> instance must
-- be declared and registered in the AWA application.
--
-- @include awa-votes-beans.ads
--
-- == Javascript Integration ==
-- The <b>Votes</b> module provides a Javascript support to help users vote for items.
-- The Javascript file <tt>/js/awa-votes.js</tt> must be included in the Javascript page.
-- It is based on jQuery and ASF. The vote actions are activated on the page items as
-- follows in XHTML facelet files:
--
-- <util:script>
-- $('.question-vote').votes({
-- voteUrl: "#{contextPath}/questions/ajax/questionVote/vote?id=",
-- itemPrefix: "vote_for-"
-- });
-- </util:script>
--
-- When the vote up or down HTML element is clicked, the <tt>vote</tt> operation of the
-- managed bean <tt>questionVote</tt> is called. The operation will update the user's vote
-- for the selected item (in the example "a question").
package AWA.Votes is
pragma Preelaborate;
end AWA.Votes;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b9843eb6b37a9e5105817c6dda0fd1bf17e2a293
|
src/wiki-nodes.ads
|
src/wiki-nodes.ads
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Strings;
package Wiki.Nodes is
pragma Preelaborate;
subtype Format_Map is Wiki.Documents.Format_Map;
subtype WString is Wide_Wide_String;
type Node_Kind is (N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_HEADER,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- Node kinds which are simple markers in the document.
subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH;
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag_Type is
(
-- Section 4.1 The root element
HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
-- Find the tag from the tag name.
function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type;
type String_Access is access constant String;
-- Get the HTML tag name.
function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access;
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT =>
Level : Natural := 0;
Header : WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : WString (1 .. Len);
when N_LINK | N_IMAGE | N_QUOTE =>
Link_Attr : Wiki.Attributes.Attribute_List_Type;
Title : WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag_Type;
Attributes : Wiki.Attributes.Attribute_List_Type;
Children : Node_List_Access;
Parent : Node_Type_Access;
when others =>
null;
end case;
end record;
-- Create a text node.
function Create_Text (Text : in WString) return Node_Type_Access;
type Document is limited private;
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Node_Type_Access);
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Document : in out Wiki.Nodes.Document;
Tag : in Html_Tag_Type;
Attributes : in Wiki.Attributes.Attribute_List_Type);
-- Pop the HTML tag.
procedure Pop_Node (Document : in out Wiki.Nodes.Document;
Tag : in Html_Tag_Type);
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- procedure Add_Text (Doc : in out Document;
-- Text : in WString);
-- type Renderer is limited interface;
--
-- procedure Render (Engine : in out Renderer;
-- Doc : in Document;
-- Node : in Node_Type) is abstract;
--
-- procedure Iterate (Doc : in Document;
-- Process : access procedure (Doc : in Document; Node : in Node_Type)) is
-- Node : Document_Node_Access := Doc.First;
-- begin
-- while Node /= null loop
-- Process (Doc, Node.Data);
-- Node := Node.Next;
-- end loop;
-- end Iterate;
private
NODE_LIST_BLOCK_SIZE : constant Positive := 20;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block_Access;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
-- Append a node to the node list.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
type Document is limited record
Nodes : Node_List;
Current : Node_Type_Access;
end record;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Strings;
package Wiki.Nodes is
pragma Preelaborate;
subtype Format_Map is Wiki.Documents.Format_Map;
subtype WString is Wide_Wide_String;
type Node_Kind is (N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_HEADER,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- Node kinds which are simple markers in the document.
subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH;
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag_Type is
(
-- Section 4.1 The root element
HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
-- Find the tag from the tag name.
function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type;
type String_Access is access constant String;
-- Get the HTML tag name.
function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access;
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT =>
Level : Natural := 0;
Header : WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : WString (1 .. Len);
when N_LINK | N_IMAGE | N_QUOTE =>
Link_Attr : Wiki.Attributes.Attribute_List_Type;
Title : WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag_Type;
Attributes : Wiki.Attributes.Attribute_List_Type;
Children : Node_List_Access;
Parent : Node_Type_Access;
when others =>
null;
end case;
end record;
-- Create a text node.
function Create_Text (Text : in WString) return Node_Type_Access;
type Document is limited private;
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Node_Type_Access);
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Document : in out Wiki.Nodes.Document;
Tag : in Html_Tag_Type;
Attributes : in Wiki.Attributes.Attribute_List_Type);
-- Pop the HTML tag.
procedure Pop_Node (Document : in out Wiki.Nodes.Document;
Tag : in Html_Tag_Type);
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- procedure Add_Text (Doc : in out Document;
-- Text : in WString);
-- type Renderer is limited interface;
--
-- procedure Render (Engine : in out Renderer;
-- Doc : in Document;
-- Node : in Node_Type) is abstract;
--
-- procedure Iterate (Doc : in Document;
-- Process : access procedure (Doc : in Document; Node : in Node_Type)) is
-- Node : Document_Node_Access := Doc.First;
-- begin
-- while Node /= null loop
-- Process (Doc, Node.Data);
-- Node := Node.Next;
-- end loop;
-- end Iterate;
private
NODE_LIST_BLOCK_SIZE : constant Positive := 20;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block_Access;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
-- Append a node to the node list.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
type Document is limited record
Nodes : Node_List;
Current : Node_Type_Access;
end record;
end Wiki.Nodes;
|
Declare the Add_Blockquote procedure
|
Declare the Add_Blockquote procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
447fa7d7460a4ab74e0e4b4c1adaba9864823bc9
|
matp/src/events/mat-events-probes.adb
|
matp/src/events/mat-events-probes.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- 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.Readers.Marshaller;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Tick_Ref;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Types.Target_Thread_Ref
(MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind));
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
-- Convert the time in usec to make computation easier.
Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000;
Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- 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.Readers.Marshaller;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Tick_Ref;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Types.Target_Thread_Ref
(MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind));
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
-- Convert the time in usec to make computation easier.
Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000;
Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec);
Frame.Cur_Depth := Count;
exception
when E : others =>
Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count));
raise;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Handler.Probe.Execute (Client.Event);
Client.Events.Insert (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
end MAT.Events.Probes;
|
Insert the event after calling the Execute to let the handler update the event (useful for the free event to retrieve the size of memory allocation and get the correct value in the event list)
|
Insert the event after calling the Execute to let the handler update
the event (useful for the free event to retrieve the size of memory
allocation and get the correct value in the event list)
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
5e7a074bc68239dfdc6471f2757eee5f89bb04bc
|
src/security-auth.ads
|
src/security-auth.ads
|
-----------------------------------------------------------------------
-- security-auth -- Authentication Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == Auth ==
-- The <b>Security.Auth</b> package implements an authentication framework that is
-- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application
-- to authenticate users using an external authorization server such as Google, Facebook,
-- Google +, Twitter and others.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- See OpenID Connect Standard 1.0
-- http://openid.net/specs/openid-connect-standard-1_0.html
--
-- See Facebook API: The Login Flow for Web (without JavaScript SDK)
-- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
--
-- Despite their subtle differences, all these authentication frameworks share almost
-- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable
-- for all these frameworks.
--
-- There are basically two steps that an application must implement:
--
-- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * <b>Verify</b>: to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- === Initialization ===
-- The initialization process must be done before each two steps (discovery and verify).
-- The Authentication manager must be declared and configured.
--
-- Mgr : Security.Auth.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the Auth realm and set the authentication return callback URL. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify",
-- Realm => "openid");
--
-- After this initialization, the authentication manager can be used in the authentication
-- process.
--
-- === Discovery: creating the authentication URL ===
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenID manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an
-- URL, below is an example for Google OpenID:
--
-- Provider : constant String := "https://www.google.com/accounts/o8/id";
-- OP : Security.Auth.End_Point;
-- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- === Verify: acknowledge the authentication in the callback URL ===
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Credential : Security.Auth.Authentication;
-- Params : Auth_Params;
--
-- The auth manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Credential);
-- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success.
--
-- === Principal creation ===
-- After the user is successfully authenticated, a user principal can be created and saved in
-- the session. The user principal can then be used to assign permissions to that user and
-- enforce the application permissions using the security policy manger.
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential);
--
package Security.Auth is
-- Use an authentication server implementing OpenID 2.0.
PROVIDER_OPENID : constant String := "openid";
-- Use the Facebook OAuth 2.0 - draft 12 authentication server.
PROVIDER_FACEBOOK : constant String := "facebook";
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- Auth provider
-- ------------------------------
-- The <b>End_Point</b> represents the authentication provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The association contains the shared secret between the relying party
-- and the authentication provider. The association can be cached and reused to authenticate
-- different users using the same authentication provider. The association also has an
-- expiration date.
type Association is private;
-- Get the provider.
function Get_Provider (Assoc : in Association) return String;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- Authentication result
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- Authentication Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the authentication process.
type Manager is tagged limited private;
-- Initialize the authentication realm.
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- Discover the authentication provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned. The discover step may do nothing for
-- authentication providers based on OAuth.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the authentication provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
private
use Ada.Strings.Unbounded;
type Association is record
Provider : Unbounded_String;
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager_Access is access all Manager'Class;
type Manager is new Ada.Finalization.Limited_Controlled with record
Provider : Unbounded_String;
Delegate : Manager_Access;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String);
end Security.Auth;
|
-----------------------------------------------------------------------
-- security-auth -- Authentication Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == Auth ==
-- The <b>Security.Auth</b> package implements an authentication framework that is
-- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application
-- to authenticate users using an external authorization server such as Google, Facebook,
-- Google +, Twitter and others.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- See OpenID Connect Standard 1.0
-- http://openid.net/specs/openid-connect-standard-1_0.html
--
-- See Facebook API: The Login Flow for Web (without JavaScript SDK)
-- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
--
-- Despite their subtle differences, all these authentication frameworks share almost
-- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable
-- for all these frameworks.
--
-- There are basically two steps that an application must implement:
--
-- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * <b>Verify</b>: to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- === Initialization ===
-- The initialization process must be done before each two steps (discovery and verify).
-- The Authentication manager must be declared and configured.
--
-- Mgr : Security.Auth.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the Auth realm and set the authentication return callback URL. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify",
-- Realm => "openid");
--
-- After this initialization, the authentication manager can be used in the authentication
-- process.
--
-- @include security-auth-openid.ads
-- @include security-auth-oauth.ads
--
-- === Discovery: creating the authentication URL ===
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenID manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an
-- URL, below is an example for Google OpenID:
--
-- Provider : constant String := "https://www.google.com/accounts/o8/id";
-- OP : Security.Auth.End_Point;
-- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- === Verify: acknowledge the authentication in the callback URL ===
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Credential : Security.Auth.Authentication;
-- Params : Auth_Params;
--
-- The auth manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Credential);
-- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success.
--
-- === Principal creation ===
-- After the user is successfully authenticated, a user principal can be created and saved in
-- the session. The user principal can then be used to assign permissions to that user and
-- enforce the application permissions using the security policy manger.
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential);
--
package Security.Auth is
-- Use an authentication server implementing OpenID 2.0.
PROVIDER_OPENID : constant String := "openid";
-- Use the Facebook OAuth 2.0 - draft 12 authentication server.
PROVIDER_FACEBOOK : constant String := "facebook";
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- Auth provider
-- ------------------------------
-- The <b>End_Point</b> represents the authentication provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The association contains the shared secret between the relying party
-- and the authentication provider. The association can be cached and reused to authenticate
-- different users using the same authentication provider. The association also has an
-- expiration date.
type Association is private;
-- Get the provider.
function Get_Provider (Assoc : in Association) return String;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- Authentication result
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- Authentication Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the authentication process.
type Manager is tagged limited private;
-- Initialize the authentication realm.
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- Discover the authentication provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned. The discover step may do nothing for
-- authentication providers based on OAuth.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the authentication provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
private
use Ada.Strings.Unbounded;
type Association is record
Provider : Unbounded_String;
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager_Access is access all Manager'Class;
type Manager is new Ada.Finalization.Limited_Controlled with record
Provider : Unbounded_String;
Delegate : Manager_Access;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String);
end Security.Auth;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
a7683fd05e2d6145cdcab522d392a13d649b7a7c
|
src/util-measures.adb
|
src/util-measures.adb
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
use Util.Streams.Buffered;
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Total : constant String := Format (Item.Time);
Time : constant String := Format (Item.Time / Item.Count);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
if Item.Count > 1 then
Stream.Write (""" total=""");
Stream.Write (Total (Total'First + 1 .. Total'Last));
end if;
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Unchecked_Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title, Count);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D, Count);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : in String;
D : in Duration;
Count : in Positive := 1) is
use Ada.Containers;
use Ada.Calendar;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title
then
Node.Count := Node.Count + Count;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => Count,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) (1 .. 6) & " us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) (1 .. 6) & " ms";
else
return Duration'Image (D) (1 .. 6) & " s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
with Util.Streams.Texts.TR;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
use Util.Streams.Buffered;
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Total : constant String := Format (Item.Time);
Time : constant String := Format (Item.Time / Item.Count);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
if Item.Count > 1 then
Stream.Write (""" total=""");
Stream.Write (Total (Total'First + 1 .. Total'Last));
end if;
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream,
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream,
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Unchecked_Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title, Count);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D, Count);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : in String;
D : in Duration;
Count : in Positive := 1) is
use Ada.Containers;
use Ada.Calendar;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title
then
Node.Count := Node.Count + Count;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => Count,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) (1 .. 6) & " us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) (1 .. 6) & " ms";
else
return Duration'Image (D) (1 .. 6) & " s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
Update to import the Util.Streams.Texts.TR package explicitly
|
Update to import the Util.Streams.Texts.TR package explicitly
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8ee3f189e9eee7ce0637214d3fec3ed331551d03
|
mat/src/events/mat-events-probes.adb
|
mat/src/events/mat-events-probes.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type Interfaces.Unsigned_64;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Frame.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Frame.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32);
Frame.Time := Frame.Time or Interfaces.Unsigned_64 (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
-- ------------------------------
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
-- ------------------------------
procedure Read_Headers (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
begin
Client.Read_Event_Definitions (Msg);
Client.Frame := new MAT.Events.Frame_Info (512);
exception
when E : others =>
Log.Error ("Exception while reading headers ", E);
end Read_Headers;
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type Interfaces.Unsigned_64;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Client.Event.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32);
Client.Event.Time := Client.Event.Time or Interfaces.Unsigned_64 (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
-- ------------------------------
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
-- ------------------------------
procedure Read_Headers (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
begin
Client.Read_Event_Definitions (Msg);
Client.Frame := new MAT.Events.Frame_Info (512);
exception
when E : others =>
Log.Error ("Exception while reading headers ", E);
end Read_Headers;
end MAT.Events.Probes;
|
Fix the event initialization that was lacking the thread and time
|
Fix the event initialization that was lacking the thread and time
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
8c7c1e7f02d009a7e6dd59809dc3ef7c718822e6
|
regtests/security-policies-tests.adb
|
regtests/security-policies-tests.adb
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
with Security.Permissions.Tests;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin_Perm : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
User.Roles (Admin_Perm) := True;
declare
use Security.Permissions.Tests;
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
end;
declare
use Security.Permissions.Tests;
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/list.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin_Perm := R.Find_Role (Role);
declare
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URI=" & URI);
-- Set the role.
User.Roles (Admin_Perm) := True;
T.Assert (U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URI=" & URI);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
with Security.Permissions.Tests;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
use Security.Permissions.Tests;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role ("admin");
T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was granted but user has no role");
User.Roles (Admin) := True;
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was not granted and user has admin role");
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
end;
declare
use Security.Permissions.Tests;
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/list.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin_Perm := R.Find_Role (Role);
declare
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URI=" & URI);
-- Set the role.
User.Roles (Admin_Perm) := True;
T.Assert (U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URI=" & URI);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
Fix the unit test for simple-policy
|
Fix the unit test for simple-policy
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
a2e961edde835d13d38db935442f0f2ca00da530
|
src/asf-applications-main-configs.adb
|
src/asf-applications-main-configs.adb
|
-----------------------------------------------------------------------
-- applications-main-configs -- Configuration support for ASF Applications
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Navigations;
with ASF.Navigations.Mappers;
with ASF.Servlets.Mappers;
with ASF.Beans.Mappers;
package body ASF.Applications.Main.Configs is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs");
function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale is
Name : constant String := Util.Beans.Objects.To_String (Value);
Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name);
begin
return Locale;
end Get_Locale;
-- ------------------------------
-- Save in the application config object the value associated with the given field.
-- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition
-- in the application.
-- ------------------------------
procedure Set_Member (N : in out Application_Config;
Field : in Application_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when TAG_MESSAGE_VAR =>
N.Name := Value;
when TAG_MESSAGE_BUNDLE =>
declare
Bundle : constant String := Util.Beans.Objects.To_String (Value);
begin
if Util.Beans.Objects.Is_Null (N.Name) then
N.App.Register (Name => Bundle & "Msg",
Bundle => Bundle);
else
N.App.Register (Name => Util.Beans.Objects.To_String (N.Name),
Bundle => Bundle);
end if;
N.Name := Util.Beans.Objects.Null_Object;
end;
when TAG_DEFAULT_LOCALE =>
declare
L : Util.Locales.Locale := Get_Locale (Value);
begin
N.App.Set_Default_Locale (L);
end;
when TAG_SUPPORTED_LOCALE =>
null;
end case;
end Set_Member;
AMapper : aliased Application_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the managed bean definitions.
-- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings
-- to read the servlet, managed beans and navigation rules.
-- ------------------------------
package body Reader_Config is
-- Get the navigation handler for the Navigation_Config instantiation
-- GNAT crashes if the call is made in the instantation part.
Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler;
package Bean_Config is
new ASF.Beans.Mappers.Reader_Config (Reader, App.Factory'Access,
Context.all'Access);
package Navigation_Config is
new ASF.Navigations.Mappers.Reader_Config (Reader, Nav, Context.all'Access);
package Servlet_Config is
new ASF.Servlets.Mappers.Reader_Config (Reader, App.all'Access,
Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Navigation_Config);
pragma Warnings (Off, Servlet_Config);
Config : aliased Application_Config;
begin
-- Install the property context that gives access
-- to the application configuration properties
Prop_Context.Set_Properties (App.Conf);
Context.Set_Resolver (Prop_Context'Unchecked_Access);
Reader.Add_Mapping ("faces-config", AMapper'Access);
Reader.Add_Mapping ("module", AMapper'Access);
Reader.Add_Mapping ("web-app", AMapper'Access);
Config.App := App;
Application_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
-- ------------------------------
-- Read the configuration file associated with the application. This includes:
-- <ul>
-- <li>The servlet and filter mappings</li>
-- <li>The managed bean definitions</li>
-- <li>The navigation rules</li>
-- </ul>
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String) is
Reader : Util.Serialize.IO.XML.Parser;
Context : aliased EL.Contexts.Default.Default_Context;
-- Setup the <b>Reader</b> to parse and build the configuration for managed beans,
-- navigation rules, servlet rules. Each package instantiation creates a local variable
-- used while parsing the XML file.
package Config is
new Reader_Config (Reader, App'Unchecked_Access, Context'Unchecked_Access);
pragma Warnings (Off, Config);
begin
Log.Info ("Reading module configuration file {0}", File);
-- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end Read_Configuration;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access,
Default => PARAM_VALUE'Access);
-- ------------------------------
-- Returns the configuration parameter.
-- ------------------------------
function P return Config_Param is
begin
return Param;
end P;
end Parameter;
begin
AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR);
AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE);
AMapper.Add_Mapping ("application/locale-config/default-locale", TAG_DEFAULT_LOCALE);
AMapper.Add_Mapping ("application/locale-config/supported-locale", TAG_SUPPORTED_LOCALE);
end ASF.Applications.Main.Configs;
|
-----------------------------------------------------------------------
-- applications-main-configs -- Configuration support for ASF Applications
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Navigations;
with ASF.Navigations.Mappers;
with ASF.Servlets.Mappers;
with ASF.Beans.Mappers;
package body ASF.Applications.Main.Configs is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs");
function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale;
function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale is
Name : constant String := Util.Beans.Objects.To_String (Value);
Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name);
begin
return Locale;
end Get_Locale;
-- ------------------------------
-- Save in the application config object the value associated with the given field.
-- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition
-- in the application.
-- ------------------------------
procedure Set_Member (N : in out Application_Config;
Field : in Application_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when TAG_MESSAGE_VAR =>
N.Name := Value;
when TAG_MESSAGE_BUNDLE =>
declare
Bundle : constant String := Util.Beans.Objects.To_String (Value);
begin
if Util.Beans.Objects.Is_Null (N.Name) then
N.App.Register (Name => Bundle & "Msg",
Bundle => Bundle);
else
N.App.Register (Name => Util.Beans.Objects.To_String (N.Name),
Bundle => Bundle);
end if;
N.Name := Util.Beans.Objects.Null_Object;
end;
when TAG_DEFAULT_LOCALE =>
N.App.Set_Default_Locale (Get_Locale (Value));
when TAG_SUPPORTED_LOCALE =>
N.App.Add_Supported_Locale (Get_Locale (Value));
end case;
end Set_Member;
AMapper : aliased Application_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the managed bean definitions.
-- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings
-- to read the servlet, managed beans and navigation rules.
-- ------------------------------
package body Reader_Config is
-- Get the navigation handler for the Navigation_Config instantiation
-- GNAT crashes if the call is made in the instantation part.
Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler;
package Bean_Config is
new ASF.Beans.Mappers.Reader_Config (Reader, App.Factory'Access,
Context.all'Access);
package Navigation_Config is
new ASF.Navigations.Mappers.Reader_Config (Reader, Nav, Context.all'Access);
package Servlet_Config is
new ASF.Servlets.Mappers.Reader_Config (Reader, App.all'Access,
Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Navigation_Config);
pragma Warnings (Off, Servlet_Config);
Config : aliased Application_Config;
begin
-- Install the property context that gives access
-- to the application configuration properties
Prop_Context.Set_Properties (App.Conf);
Context.Set_Resolver (Prop_Context'Unchecked_Access);
Reader.Add_Mapping ("faces-config", AMapper'Access);
Reader.Add_Mapping ("module", AMapper'Access);
Reader.Add_Mapping ("web-app", AMapper'Access);
Config.App := App;
Application_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
-- ------------------------------
-- Read the configuration file associated with the application. This includes:
-- <ul>
-- <li>The servlet and filter mappings</li>
-- <li>The managed bean definitions</li>
-- <li>The navigation rules</li>
-- </ul>
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String) is
Reader : Util.Serialize.IO.XML.Parser;
Context : aliased EL.Contexts.Default.Default_Context;
-- Setup the <b>Reader</b> to parse and build the configuration for managed beans,
-- navigation rules, servlet rules. Each package instantiation creates a local variable
-- used while parsing the XML file.
package Config is
new Reader_Config (Reader, App'Unchecked_Access, Context'Unchecked_Access);
pragma Warnings (Off, Config);
begin
Log.Info ("Reading module configuration file {0}", File);
-- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end Read_Configuration;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access,
Default => PARAM_VALUE'Access);
-- ------------------------------
-- Returns the configuration parameter.
-- ------------------------------
function P return Config_Param is
begin
return Param;
end P;
end Parameter;
begin
AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR);
AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE);
AMapper.Add_Mapping ("application/locale-config/default-locale", TAG_DEFAULT_LOCALE);
AMapper.Add_Mapping ("application/locale-config/supported-locale", TAG_SUPPORTED_LOCALE);
end ASF.Applications.Main.Configs;
|
Add the supported locales on the application
|
Add the supported locales on the application
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
9764b354f48f9ffe00929f651a658fa86b0848ed
|
src/ado-sessions.ads
|
src/ado-sessions.ads
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Databases;
with ADO.Queries;
with ADO.SQL;
with ADO.Caches;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
-- == Session ==
-- The <tt>ADO.Sessions</tt> package defines the control and management of database sessions.
-- The database session is represented by the <tt>Session</tt> or <tt>Master_Session</tt> types.
-- It provides operation to create a database statement that can be executed.
-- The <tt>Session</tt> type is used to represent read-only database sessions. It provides
-- operations to query the database but it does not allow to update or delete content.
-- The <tt>Master_Session</tt> type extends the <tt>Session</tt> type to provide write
-- access and it provides operations to get update or delete statements. The differentiation
-- between the two sessions is provided for the support of database replications with
-- databases such as MySQL.
--
-- @include ado-sessions-factory.ads
--
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return ADO.Databases.Connection_Status;
-- Close the session.
procedure Close (Database : in out Session);
-- Get the database connection.
function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class;
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition);
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Database : ADO.Databases.Master_Connection;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
Values : ADO.Caches.Cache_Manager_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access all ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class;
Message : in String := "");
pragma Inline (Check_Session);
end ADO.Sessions;
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Drivers.Connections;
with ADO.Queries;
with ADO.SQL;
with ADO.Caches;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
-- == Session ==
-- The <tt>ADO.Sessions</tt> package defines the control and management of database sessions.
-- The database session is represented by the <tt>Session</tt> or <tt>Master_Session</tt> types.
-- It provides operation to create a database statement that can be executed.
-- The <tt>Session</tt> type is used to represent read-only database sessions. It provides
-- operations to query the database but it does not allow to update or delete content.
-- The <tt>Master_Session</tt> type extends the <tt>Session</tt> type to provide write
-- access and it provides operations to get update or delete statements. The differentiation
-- between the two sessions is provided for the support of database replications with
-- databases such as MySQL.
--
-- @include ado-sessions-factory.ads
--
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- The database connection status
type Connection_Status is (OPEN, CLOSED);
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return Connection_Status;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access;
-- Close the session.
procedure Close (Database : in out Session);
-- Get the database connection.
-- function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class;
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition);
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Database : ADO.Drivers.Connections.Ref.Ref;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
Values : ADO.Caches.Cache_Manager_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access all ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class;
Message : in String := "");
pragma Inline (Check_Session);
end ADO.Sessions;
|
Refactor the session management Declare the Connection_Status type Declare the Get_Driver operation
|
Refactor the session management
Declare the Connection_Status type
Declare the Get_Driver operation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
8664b3728f20be36a5695cc91f49843db46d785a
|
regtests/asf-views-facelets-tests.adb
|
regtests/asf-views-facelets-tests.adb
|
-----------------------------------------------------------------------
-- Facelet Tests - Unit tests for ASF.Views.Facelet
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AUnit.Test_Caller;
with AUnit.Assertions;
with Ada.Text_IO;
with ASF.Testsuite;
with AUnit.Assertions;
with ASF.Contexts.Facelets;
with ASF.Components.Util.Factory;
package body ASF.Views.Facelets.Tests is
use AUnit.Assertions;
use ASF.Testsuite;
use ASF.Contexts.Facelets;
-- Set up performed before each test case
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Tear down performed after each test case
overriding
procedure Tear_Down (T : in out Test) is
begin
null;
end Tear_Down;
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
Factory : ASF.Views.Facelets.Facelet_Factory;
Components : aliased ASF.Factory.Component_Factory;
View : ASF.Views.Facelets.Facelet;
Ctx : Facelet_Context;
begin
Initialize (Factory, Components'Unchecked_Access, "regtests/files/views;.", True, True, True);
Find_Facelet (Factory, "text.xhtml", Ctx, View);
T.Assert (Condition => not Is_Null (View),
Message => "Loading an existing facelet should return a view");
end Test_Load_Facelet;
-- Test loading of an unknown file
procedure Test_Load_Unknown_Facelet (T : in out Test) is
Factory : ASF.Views.Facelets.Facelet_Factory;
Components : aliased ASF.Factory.Component_Factory;
View : ASF.Views.Facelets.Facelet;
Ctx : Facelet_Context;
begin
Initialize (Factory, Components'Unchecked_Access, "regtests/files;.", True, True, True);
Find_Facelet (Factory, "not-found-file.xhtml", Ctx, View);
T.Assert (Condition => Is_Null (View),
Message => "Loading a missing facelet should not raise any exception");
end Test_Load_Unknown_Facelet;
package Caller is new AUnit.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Suite.Add_Test (Caller.Create ("Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Facelet'Access));
Suite.Add_Test (Caller.Create ("Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Unknown_Facelet'Access));
end Add_Tests;
end ASF.Views.Facelets.Tests;
|
-----------------------------------------------------------------------
-- Facelet Tests - Unit tests for ASF.Views.Facelet
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AUnit.Test_Caller;
with AUnit.Assertions;
with Ada.Text_IO;
with ASF.Testsuite;
with AUnit.Assertions;
with ASF.Contexts.Facelets;
with ASF.Components.Utils.Factory;
with ASF.Applications.Main;
package body ASF.Views.Facelets.Tests is
use AUnit.Assertions;
use ASF.Testsuite;
use ASF.Contexts.Facelets;
type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with null record;
-- Get the application associated with this facelet context.
overriding
function Get_Application (Context : in Facelet_Context)
return access ASF.Applications.Main.Application'Class;
-- Get the application associated with this facelet context.
overriding
function Get_Application (Context : in Facelet_Context)
return access ASF.Applications.Main.Application'Class is
begin
return null;
end Get_Application;
-- Set up performed before each test case
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Tear down performed after each test case
overriding
procedure Tear_Down (T : in out Test) is
begin
null;
end Tear_Down;
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
Factory : ASF.Views.Facelets.Facelet_Factory;
Components : aliased ASF.Factory.Component_Factory;
View : ASF.Views.Facelets.Facelet;
Ctx : Facelet_Context;
begin
Initialize (Factory, Components'Unchecked_Access, "regtests/files/views;.", True, True, True);
Find_Facelet (Factory, "text.xhtml", Ctx, View);
T.Assert (Condition => not Is_Null (View),
Message => "Loading an existing facelet should return a view");
end Test_Load_Facelet;
-- Test loading of an unknown file
procedure Test_Load_Unknown_Facelet (T : in out Test) is
Factory : ASF.Views.Facelets.Facelet_Factory;
Components : aliased ASF.Factory.Component_Factory;
View : ASF.Views.Facelets.Facelet;
Ctx : Facelet_Context;
begin
Initialize (Factory, Components'Unchecked_Access, "regtests/files;.", True, True, True);
Find_Facelet (Factory, "not-found-file.xhtml", Ctx, View);
T.Assert (Condition => Is_Null (View),
Message => "Loading a missing facelet should not raise any exception");
end Test_Load_Unknown_Facelet;
package Caller is new AUnit.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Suite.Add_Test (Caller.Create ("Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Facelet'Access));
Suite.Add_Test (Caller.Create ("Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Unknown_Facelet'Access));
end Add_Tests;
end ASF.Views.Facelets.Tests;
|
Fix compilation of unit tests
|
Fix compilation of unit tests
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
32dbe252bc4b5f09095c03c8b9ce3f1bae5285a7
|
src/core/texts/util-texts-builders.ads
|
src/core/texts/util-texts-builders.ads
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Finalization;
-- == Text Builders ==
-- The `Util.Texts.Builders` generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The `Builder` type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an `Append` procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the `Iterate` operation that allows to get the content
-- collected by the builder. When using the `Iterate` operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that receives
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the `Iterate` operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
generic
type Element_Type is (<>);
type Input is array (Positive range <>) of Element_Type;
Chunk_Size : Positive := 80;
package Util.Texts.Builders is
pragma Preelaborate;
type Builder (Len : Positive) is limited private;
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Input);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Element_Type);
generic
with procedure Process (Content : in out Input; Last : out Natural);
procedure Inline_Append (Source : in out Builder);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input));
generic
with procedure Process (Content : in Input);
procedure Inline_Iterate (Source : in Builder);
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Input;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Input;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Input);
procedure Get (Source : in Builder);
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
generic
type Value is limited private;
type Value_List is array (Positive range <>) of Value;
with procedure Append (Input : in out Builder; Item : in Value);
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List);
private
pragma Inline (Length);
pragma Inline (Iterate);
type Block;
type Block_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Block_Access;
Last : Natural := 0;
Content : Input (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Block_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Block (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
end Util.Texts.Builders;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Finalization;
-- == Text Builders ==
-- The `Util.Texts.Builders` generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The `Builder` type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an `Append` procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the `Iterate` operation that allows to get the content
-- collected by the builder. When using the `Iterate` operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that receives
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the `Iterate` operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
generic
type Element_Type is (<>);
type Input is array (Positive range <>) of Element_Type;
Chunk_Size : Positive := 80;
package Util.Texts.Builders is
pragma Preelaborate;
type Builder (Len : Positive) is limited private;
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Input);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Element_Type);
generic
with procedure Process (Content : in out Input; Last : out Natural);
procedure Inline_Append (Source : in out Builder);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input));
generic
with procedure Process (Content : in Input);
procedure Inline_Iterate (Source : in Builder);
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Input;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Input;
-- Get the element at the given position.
function Element (Source : in Builder;
Position : in Positive) return Element_Type;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Input);
procedure Get (Source : in Builder);
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
generic
type Value is limited private;
type Value_List is array (Positive range <>) of Value;
with procedure Append (Input : in out Builder; Item : in Value);
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List);
private
pragma Inline (Length);
pragma Inline (Iterate);
type Block;
type Block_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Block_Access;
Last : Natural := 0;
Content : Input (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Block_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Block (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
end Util.Texts.Builders;
|
Add the Element function to get an element at a given position in the builder
|
Add the Element function to get an element at a given position in the builder
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
18c9c8f498c16cef40fa57adf55207bcedb8fbb4
|
samples/add_user.adb
|
samples/add_user.adb
|
-----------------------------------------------------------------------
-- Add_User -- Example to add an object in the database
-- 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 Samples.User.Model;
with ADO;
with ADO.Drivers;
with ADO.Sessions;
with ADO.Sessions.Factory;
with Util.Strings;
with Util.Log.Loggers;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Add_User is
use Samples.User.Model;
function Get_Name (Email : in String) return String;
Factory : ADO.Sessions.Factory.Session_Factory;
function Get_Name (Email : in String) return String is
Pos : constant Natural := Util.Strings.Index (Email, '@');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name;
begin
Util.Log.Loggers.Initialize ("samples.properties");
-- Initialize the database drivers.
ADO.Drivers.Initialize ("samples.properties");
if Ada.Command_Line.Argument_Count < 1 then
Ada.Text_IO.Put_Line ("Usage: add_user user-email ...");
Ada.Text_IO.Put_Line ("Example: add_user [email protected]");
Ada.Command_Line.Set_Exit_Status (2);
return;
end if;
-- Initialize the session factory to connect to the
-- database defined by 'ado.database' property.
Factory.Create (ADO.Drivers.Get_Config ("ado.database"));
declare
DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session;
begin
DB.Begin_Transaction;
for I in 1 .. Ada.Command_Line.Argument_Count loop
declare
Email : constant String := Ada.Command_Line.Argument (I);
Name : constant String := Get_Name (Email);
User : User_Ref;
begin
User.Set_Name (Name);
User.Set_Email (Email);
User.Set_Description ("My friend " & Name);
User.Set_Status (0);
User.Save (DB);
Ada.Text_IO.Put_Line ("User " & Name & " has id "
& ADO.Identifier'Image (User.Get_Id));
end;
end loop;
DB.Commit;
end;
end Add_User;
|
-----------------------------------------------------------------------
-- Add_User -- Example to add an object in the database
-- 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 Samples.User.Model;
with ADO;
with ADO.Drivers.Initializer;
with ADO.Sessions;
with ADO.Sessions.Factory;
with Util.Strings;
with Util.Log.Loggers;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Add_User is
use Samples.User.Model;
function Get_Name (Email : in String) return String;
Factory : ADO.Sessions.Factory.Session_Factory;
function Get_Name (Email : in String) return String is
Pos : constant Natural := Util.Strings.Index (Email, '@');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name;
procedure Initialize is new ADO.Drivers.Initializer (String, ADO.Drivers.Initialize);
begin
Util.Log.Loggers.Initialize ("samples.properties");
-- Initialize the database drivers.
Initialize ("samples.properties");
if Ada.Command_Line.Argument_Count < 1 then
Ada.Text_IO.Put_Line ("Usage: add_user user-email ...");
Ada.Text_IO.Put_Line ("Example: add_user [email protected]");
Ada.Command_Line.Set_Exit_Status (2);
return;
end if;
-- Initialize the session factory to connect to the
-- database defined by 'ado.database' property.
Factory.Create (ADO.Drivers.Get_Config ("ado.database"));
declare
DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session;
begin
DB.Begin_Transaction;
for I in 1 .. Ada.Command_Line.Argument_Count loop
declare
Email : constant String := Ada.Command_Line.Argument (I);
Name : constant String := Get_Name (Email);
User : User_Ref;
begin
User.Set_Name (Name);
User.Set_Email (Email);
User.Set_Description ("My friend " & Name);
User.Set_Status (0);
User.Save (DB);
Ada.Text_IO.Put_Line ("User " & Name & " has id "
& ADO.Identifier'Image (User.Get_Id));
end;
end loop;
DB.Commit;
end;
end Add_User;
|
Update the initialization
|
Update the initialization
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
4544a8dd5e6357df7b7cf434b5d7aced649e31c0
|
src/wiki-buffers.ads
|
src/wiki-buffers.ads
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Ada.Finalization;
-- == Text Builders ==
-- The `Util.Texts.Builders` generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The `Builder` type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an `Append` procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the `Iterate` operation that allows to get the content
-- collected by the builder. When using the `Iterate` operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that receives
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the `Iterate` operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
private package Wiki.Buffers with Preelaborate is
Chunk_Size : constant := 256;
type Buffer;
type Buffer_Access is access all Buffer;
type Buffer (Len : Positive) is limited record
Next_Block : Buffer_Access;
Last : Natural := 0;
Offset : Natural := 0;
Content : Wiki.Strings.WString (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Buffer_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Buffer (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
-- Move forward to skip a number of items.
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive) with Inline_Always;
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive;
Count : in Natural);
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Wiki.Strings.WString);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Wiki.Strings.WChar);
-- Append in `Into` builder the `Content` builder starting at `From` position
-- and the up to and including the `To` position.
procedure Append (Into : in out Builder;
Content : in Builder;
From : in Positive;
To : in Positive);
procedure Append (Into : in out Builder;
Buffer : in Buffer_Access;
From : in Positive);
generic
with procedure Process (Content : in out Wiki.Strings.WString; Last : out Natural);
procedure Inline_Append (Source : in out Builder);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null
access procedure (Chunk : in Wiki.Strings.WString)) with Inline;
generic
with procedure Process (Content : in Wiki.Strings.WString);
procedure Inline_Iterate (Source : in Builder);
generic
with procedure Process (Content : in out Wiki.Strings.WString);
procedure Inline_Update (Source : in out Builder);
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Wiki.Strings.WString;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Wiki.Strings.WString;
-- Get the element at the given position.
function Element (Source : in Builder;
Position : in Positive) return Wiki.Strings.WChar;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Wiki.Strings.WString);
procedure Get (Source : in Builder);
function Count_Occurence (Buffer : in Buffer_Access;
From : in Positive;
Item : in Wiki.Strings.WChar) return Natural;
procedure Count_Occurence (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar;
Count : out Natural);
-- Skip spaces and tabs starting at the given position in the buffer
-- and return the number of spaces skipped.
procedure Skip_Spaces (Buffer : in out Buffer_Access;
From : in out Positive;
Count : out Natural);
procedure Find (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar);
end Wiki.Buffers;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Ada.Finalization;
-- == Text Builders ==
-- The `Util.Texts.Builders` generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The `Builder` type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an `Append` procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the `Iterate` operation that allows to get the content
-- collected by the builder. When using the `Iterate` operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that receives
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the `Iterate` operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
private package Wiki.Buffers with Preelaborate is
Chunk_Size : constant := 256;
type Buffer;
type Buffer_Access is access all Buffer;
type Buffer (Len : Positive) is limited record
Next_Block : Buffer_Access;
Last : Natural := 0;
Offset : Natural := 0;
Content : Wiki.Strings.WString (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Buffer_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Buffer (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
-- Move forward to skip a number of items.
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive) with Inline_Always;
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive;
Count : in Natural);
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Wiki.Strings.WString);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Wiki.Strings.WChar);
-- Append in `Into` builder the `Content` builder starting at `From` position
-- and the up to and including the `To` position.
procedure Append (Into : in out Builder;
Content : in Builder;
From : in Positive;
To : in Positive);
procedure Append (Into : in out Builder;
Buffer : in Buffer_Access;
From : in Positive);
generic
with procedure Process (Content : in out Wiki.Strings.WString; Last : out Natural);
procedure Inline_Append (Source : in out Builder);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null
access procedure (Chunk : in Wiki.Strings.WString)) with Inline;
generic
with procedure Process (Content : in Wiki.Strings.WString);
procedure Inline_Iterate (Source : in Builder);
generic
with procedure Process (Content : in out Wiki.Strings.WString);
procedure Inline_Update (Source : in out Builder);
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Wiki.Strings.WString;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Wiki.Strings.WString;
-- Get the element at the given position.
function Element (Source : in Builder;
Position : in Positive) return Wiki.Strings.WChar;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Wiki.Strings.WString);
procedure Get (Source : in Builder);
function Count_Occurence (Buffer : in Buffer_Access;
From : in Positive;
Item : in Wiki.Strings.WChar) return Natural;
procedure Count_Occurence (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar;
Count : out Natural);
-- Skip spaces and tabs starting at the given position in the buffer
-- and return the number of spaces skipped.
procedure Skip_Spaces (Buffer : in out Buffer_Access;
From : in out Positive;
Count : out Natural);
-- Skip one optional space or tab.
procedure Skip_Optional_Space (Buffer : in out Buffer_Access;
From : in out Positive);
procedure Find (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar);
end Wiki.Buffers;
|
Declare Skip_Optional_Space procedure
|
Declare Skip_Optional_Space procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
32a3814e67e6e24fc7e0f757c91367fe7e8e0151
|
asfunit/asf-tests.adb
|
asfunit/asf-tests.adb
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Servlet.Core;
with ASF.Servlets.Faces;
with ASF.Servlets.Ajax;
with ASF.Responses;
with ASF.Contexts.Faces;
with EL.Variables.Default;
package body ASF.Tests is
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
App_Created : ASF.Applications.Main.Application_Access;
App : ASF.Applications.Main.Application_Access;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
Empty : Util.Properties.Manager;
begin
if Application /= null then
App := Application;
else
if App_Created = null then
App_Created := new ASF.Applications.Main.Application;
end if;
App := App_Created;
end if;
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
Servlet.Tests.Initialize (Empty, CONTEXT_PATH, App.all'Access);
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
use type Servlet.Core.Servlet_Registry_Access;
Result : constant Servlet.Core.Servlet_Registry_Access := Servlet.Tests.Get_Application;
begin
if Result = null then
return App;
elsif Result.all in ASF.Applications.Main.Application'Class then
return ASF.Applications.Main.Application'Class (Result.all)'Access;
else
return App;
end if;
end Get_Application;
-- ------------------------------
-- Cleanup the test instance.
-- ------------------------------
overriding
procedure Tear_Down (T : in out EL_Test) is
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class,
EL.Contexts.Default.Default_Context_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class,
EL.Variables.Variable_Mapper_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class,
EL.Contexts.Default.Default_ELResolver_Access);
begin
ASF.Contexts.Faces.Restore (null);
Free (T.ELContext);
Free (T.Variables);
Free (T.Root_Resolver);
end Tear_Down;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out EL_Test) is
begin
T.ELContext := new EL.Contexts.Default.Default_Context;
T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver;
T.Variables := new EL.Variables.Default.Default_Variable_Mapper;
T.ELContext.Set_Resolver (T.Root_Resolver.all'Access);
T.ELContext.Set_Variable_Mapper (T.Variables.all'Access);
end Set_Up;
end ASF.Tests;
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Servlet.Core;
with ASF.Servlets.Faces;
with ASF.Servlets.Ajax;
with Servlet.Filters;
with Servlet.Core.Files;
with Servlet.Core.Measures;
with ASF.Responses;
with ASF.Contexts.Faces;
with EL.Variables.Default;
package body ASF.Tests is
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
App_Created : ASF.Applications.Main.Application_Access;
App : ASF.Applications.Main.Application_Access;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Files : aliased Servlet.Core.Files.File_Servlet;
Measures : aliased Servlet.Core.Measures.Measure_Servlet;
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
Empty : Util.Properties.Manager;
begin
if Application /= null then
App := Application;
else
if App_Created = null then
App_Created := new ASF.Applications.Main.Application;
end if;
App := App_Created;
end if;
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
App.Add_Servlet (Name => "files", Server => Files'Access);
App.Add_Servlet (Name => "measures", Server => Measures'Access);
App.Add_Filter (Name => "measures",
Filter => Servlet.Filters.Filter'Class (Measures)'Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.txt");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "files", Pattern => "*.jpg");
App.Add_Mapping (Name => "files", Pattern => "*.gif");
App.Add_Mapping (Name => "files", Pattern => "*.pdf");
App.Add_Mapping (Name => "files", Pattern => "*.properties");
App.Add_Mapping (Name => "files", Pattern => "*.xhtml");
App.Add_Mapping (Name => "measures", Pattern => "stats.xml");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml");
Servlet.Tests.Initialize (Empty, CONTEXT_PATH, App.all'Access);
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
use type Servlet.Core.Servlet_Registry_Access;
Result : constant Servlet.Core.Servlet_Registry_Access := Servlet.Tests.Get_Application;
begin
if Result = null then
return App;
elsif Result.all in ASF.Applications.Main.Application'Class then
return ASF.Applications.Main.Application'Class (Result.all)'Access;
else
return App;
end if;
end Get_Application;
-- ------------------------------
-- Cleanup the test instance.
-- ------------------------------
overriding
procedure Tear_Down (T : in out EL_Test) is
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class,
EL.Contexts.Default.Default_Context_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class,
EL.Variables.Variable_Mapper_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class,
EL.Contexts.Default.Default_ELResolver_Access);
begin
ASF.Contexts.Faces.Restore (null);
Free (T.ELContext);
Free (T.Variables);
Free (T.Root_Resolver);
end Tear_Down;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out EL_Test) is
begin
T.ELContext := new EL.Contexts.Default.Default_Context;
T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver;
T.Variables := new EL.Variables.Default.Default_Variable_Mapper;
T.ELContext.Set_Resolver (T.Root_Resolver.all'Access);
T.ELContext.Set_Variable_Mapper (T.Variables.all'Access);
end Set_Up;
end ASF.Tests;
|
Change the Initialize procedure to register the files, measures servlet (after changes in servlet_unit library)
|
Change the Initialize procedure to register the files, measures servlet (after changes in servlet_unit library)
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a1475677abac93bc69c945d014d10dae4727fb8d
|
mat/src/events/mat-events.ads
|
mat/src/events/mat-events.ads
|
-----------------------------------------------------------------------
-- gprofiler-events - Profiler Events Description
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.Strings.Unbounded;
with MAT.Types;
with Util.Strings;
package MAT.Events is
use Interfaces;
type Attribute_Type is (T_UINT8,
T_UINT16,
T_UINT32,
T_UINT64,
T_POINTER,
T_PROBE,
T_FRAME,
T_THREAD,
T_TIME,
T_SIZE_T);
type Event_Type is (EVENT_BEGIN, EVENT_END, EVENT_MALLOC, EVENT_FREE, EVENT_REALLOC);
subtype Internal_Reference is Natural;
type Attribute is record
Name : Util.Strings.Name_Access;
Size : Natural := 0;
Kind : Attribute_Type := T_UINT8;
Ref : Internal_Reference := 0;
end record;
-- Logical description of an event attribute.
type Attribute_Table is array (Natural range <>) of Attribute;
type Attribute_Table_Ptr is access all Attribute_Table;
type Const_Attribute_Table_Access is access constant Attribute_Table;
type Event_Description (Nb_Attributes : Natural) is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Id : Unsigned_32;
Kind : Event_Type;
Def : Attribute_Table (1 .. Nb_Attributes);
end record;
type Event_Description_Ptr is access all Event_Description;
subtype Addr is MAT.Types.Uint32;
type Frame_Table is array (Natural range <>) of Addr;
type Rusage_Info is record
Minflt : Unsigned_32;
Majflt : Unsigned_32;
Nswap : Unsigned_32;
end record;
type Frame_Info (Depth : Natural) is record
Time : MAT.Types.Target_Time;
Thread : MAT.Types.Target_Thread_Ref;
Stack : MAT.Types.Target_Addr;
Rusage : Rusage_Info;
Cur_Depth : Natural;
Frame : Frame_Table (1 .. Depth);
end record;
type Event_Data is record
Kind : Attribute_Type;
U8 : MAT.Types.Uint8;
U16 : MAT.Types.Uint16;
U32 : MAT.Types.Uint32;
U64 : MAT.Types.Uint64;
Probe : Frame_Info (Depth => 10);
end record;
type Event_Data_Table is array (Natural range <>) of Event_Data;
procedure Dump (Table : in Event_Data_Table;
Def : in Event_Description);
end MAT.Events;
|
-----------------------------------------------------------------------
-- gprofiler-events - Profiler Events Description
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.Strings.Unbounded;
with MAT.Types;
with Util.Strings;
package MAT.Events is
use Interfaces;
type Attribute_Type is (T_UINT8,
T_UINT16,
T_UINT32,
T_UINT64,
T_POINTER,
T_PROBE,
T_FRAME,
T_THREAD,
T_TIME,
T_SIZE_T);
type Event_Type is (EVENT_BEGIN, EVENT_END, EVENT_MALLOC, EVENT_FREE, EVENT_REALLOC);
subtype Internal_Reference is Natural;
type Attribute is record
Name : Util.Strings.Name_Access;
Size : Natural := 0;
Kind : Attribute_Type := T_UINT8;
Ref : Internal_Reference := 0;
end record;
-- Logical description of an event attribute.
type Attribute_Table is array (Natural range <>) of Attribute;
type Attribute_Table_Ptr is access all Attribute_Table;
type Const_Attribute_Table_Access is access constant Attribute_Table;
type Event_Description (Nb_Attributes : Natural) is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Id : Unsigned_32;
Kind : Event_Type;
Def : Attribute_Table (1 .. Nb_Attributes);
end record;
type Event_Description_Access is access all Event_Description;
subtype Addr is MAT.Types.Uint32;
type Frame_Table is array (Natural range <>) of Addr;
type Rusage_Info is record
Minflt : Unsigned_32;
Majflt : Unsigned_32;
Nswap : Unsigned_32;
end record;
type Frame_Info (Depth : Natural) is record
Time : MAT.Types.Target_Time;
Thread : MAT.Types.Target_Thread_Ref;
Stack : MAT.Types.Target_Addr;
Rusage : Rusage_Info;
Cur_Depth : Natural;
Frame : Frame_Table (1 .. Depth);
end record;
type Event_Data is record
Kind : Attribute_Type;
U8 : MAT.Types.Uint8;
U16 : MAT.Types.Uint16;
U32 : MAT.Types.Uint32;
U64 : MAT.Types.Uint64;
Probe : Frame_Info (Depth => 10);
end record;
type Event_Data_Table is array (Natural range <>) of Event_Data;
procedure Dump (Table : in Event_Data_Table;
Def : in Event_Description);
end MAT.Events;
|
Rename Event_Description_Ptr into Event_Description_Access
|
Rename Event_Description_Ptr into Event_Description_Access
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
46e1de644c8b998dbb92ca2f09a3511fe011c926
|
src/wiki-render-wiki.ads
|
src/wiki-render-wiki.ads
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- 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 Util.Strings;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Writers;
with Wiki.Parsers;
-- == Wiki Renderer ==
-- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private;
-- Set the output writer.
procedure Set_Writer (Document : in out Wiki_Renderer;
Writer : in Writers.Writer_Type_Access;
Format : in Parsers.Wiki_Syntax_Type);
-- Add a section header in the document.
overriding
procedure Add_Header (Document : in out Wiki_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
overriding
procedure Add_Line_Break (Document : in out Wiki_Renderer);
-- 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 Wiki_Renderer);
-- 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 Wiki_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.
overriding
procedure Add_List_Item (Document : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
overriding
procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer);
-- Add a link.
overriding
procedure Add_Link (Document : in out Wiki_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.
overriding
procedure Add_Image (Document : in out Wiki_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.
overriding
procedure Add_Quote (Document : in out Wiki_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.
overriding
procedure Add_Text (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
overriding
procedure Start_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Attribute_List_Type);
overriding
procedure End_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Wiki_Renderer);
private
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End,
Underline_Start, Underline_End,
Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End,
Line_Break,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
-- Emit a new line.
procedure New_Line (Document : in out Wiki_Renderer);
procedure Close_Paragraph (Document : in out Wiki_Renderer);
procedure Open_Paragraph (Document : in out Wiki_Renderer);
procedure Start_Keep_Content (Document : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Documents.Document_Reader with record
Writer : Writers.Writer_Type_Access := null;
Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE;
Format : Documents.Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Keep_Content : Boolean := False;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
Current_Style : Documents.Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- 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 Util.Strings;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Writers;
with Wiki.Parsers;
-- == Wiki Renderer ==
-- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private;
-- Set the output writer.
procedure Set_Writer (Document : in out Wiki_Renderer;
Writer : in Writers.Writer_Type_Access;
Format : in Parsers.Wiki_Syntax_Type);
-- Add a section header in the document.
overriding
procedure Add_Header (Document : in out Wiki_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
overriding
procedure Add_Line_Break (Document : in out Wiki_Renderer);
-- 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 Wiki_Renderer);
-- 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 Wiki_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.
overriding
procedure Add_List_Item (Document : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
overriding
procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer);
-- Add a link.
overriding
procedure Add_Link (Document : in out Wiki_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.
overriding
procedure Add_Image (Document : in out Wiki_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.
overriding
procedure Add_Quote (Document : in out Wiki_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.
overriding
procedure Add_Text (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
overriding
procedure Start_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Attribute_List_Type);
overriding
procedure End_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Wiki_Renderer);
private
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End,
Underline_Start, Underline_End,
Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End,
Preformat_Start, Preformat_End,
Line_Break,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
-- Emit a new line.
procedure New_Line (Document : in out Wiki_Renderer);
procedure Close_Paragraph (Document : in out Wiki_Renderer);
procedure Open_Paragraph (Document : in out Wiki_Renderer);
procedure Start_Keep_Content (Document : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Documents.Document_Reader with record
Writer : Writers.Writer_Type_Access := null;
Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE;
Format : Documents.Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Keep_Content : Boolean := False;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
Current_Style : Documents.Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
Define Preformat_Start and Preformat_End
|
Define Preformat_Start and Preformat_End
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
1289fce229667a4d689263a8f7e2f300cc1a0f06
|
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");
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;
|
-----------------------------------------------------------------------
-- 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);
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'Range loop
declare
Name : constant String := Html_Tag'Image (I);
Wname : constant Wide_Wide_String := Html_Tag'Wide_Wide_Image (I);
Pos : constant Natural := Util.Strings.Index (Name, '_');
Tag : constant Html_Tag := 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;
|
Move the Html_Tag type from Wiki.Nodes to Wiki package
|
Move the Html_Tag type from Wiki.Nodes to Wiki package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
32e94edf2457b59f6b183a53de50e8000c3473b0
|
src/gen-artifacts-distribs-bundles.adb
|
src/gen-artifacts-distribs-bundles.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-bundles -- Merge bundles for distribution artifact
-- 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.Directories;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Util.Log.Loggers;
with Util.Properties;
package body Gen.Artifacts.Distribs.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Bundles");
-- ------------------------------
-- 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
pragma Unreferenced (Node);
Result : constant Bundle_Rule_Access := new Bundle_Rule;
begin
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 Bundle_Rule) return String is
pragma Unreferenced (Rule);
begin
return "bundle";
end Get_Install_Name;
-- ------------------------------
-- Install the file <b>File</b> according to the distribution rule.
-- Merge all the files listed in <b>Files</b> in the target path specified by <b>Path</b>.
-- ------------------------------
overriding
procedure Install (Rule : in Bundle_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
procedure Load_File (File : in File_Record);
procedure Merge_Property (Name, Item : in Util.Properties.Value);
procedure Save_Property (Name, Item : in Util.Properties.Value);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : Ada.Text_IO.File_Type;
Merge : Util.Properties.Manager;
-- ------------------------------
-- Merge the property into the target property list.
-- ------------------------------
procedure Merge_Property (Name, Item : in Util.Properties.Value) is
begin
Merge.Set (Name, Item);
end Merge_Property;
procedure Save_Property (Name, Item : in Util.Properties.Value) is
begin
Ada.Text_IO.Put (Output, Ada.Strings.Unbounded.To_String (Name));
Ada.Text_IO.Put (Output, "=");
Ada.Text_IO.Put_Line (Output, Ada.Strings.Unbounded.To_String (Item));
end Save_Property;
-- ------------------------------
-- Append the file to the output
-- ------------------------------
procedure Load_File (File : in File_Record) is
File_Path : constant String := Rule.Get_Source_Path (File);
Props : Util.Properties.Manager;
begin
Log.Info ("loading {0}", File_Path);
Props.Load_Properties (Path => File_Path);
Props.Iterate (Process => Merge_Property'Access);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Context.Error ("Cannot read {0}: ", File_Path, Ada.Exceptions.Exception_Message (Ex));
end Load_File;
Iter : File_Cursor := Files.First;
begin
Ada.Directories.Create_Path (Dir);
while File_Record_Vectors.Has_Element (Iter) loop
File_Record_Vectors.Query_Element (Iter, Load_File'Access);
File_Record_Vectors.Next (Iter);
end loop;
Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => Path);
Merge.Iterate (Process => Save_Property'Access);
Ada.Text_IO.Close (File => Output);
end Install;
end Gen.Artifacts.Distribs.Bundles;
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-bundles -- Merge bundles for distribution artifact
-- Copyright (C) 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.Directories;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Util.Log.Loggers;
with Util.Properties;
package body Gen.Artifacts.Distribs.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Bundles");
-- ------------------------------
-- 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
pragma Unreferenced (Node);
Result : constant Bundle_Rule_Access := new Bundle_Rule;
begin
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 Bundle_Rule) return String is
pragma Unreferenced (Rule);
begin
return "bundle";
end Get_Install_Name;
-- ------------------------------
-- Install the file <b>File</b> according to the distribution rule.
-- Merge all the files listed in <b>Files</b> in the target path specified by <b>Path</b>.
-- ------------------------------
overriding
procedure Install (Rule : in Bundle_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
procedure Load_File (File : in File_Record);
procedure Merge_Property (Name : in String;
Item : in Util.Properties.Value);
procedure Save_Property (Name : in String;
Item : in Util.Properties.Value);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : Ada.Text_IO.File_Type;
Merge : Util.Properties.Manager;
-- ------------------------------
-- Merge the property into the target property list.
-- ------------------------------
procedure Merge_Property (Name : in String;
Item : in Util.Properties.Value) is
begin
Merge.Set_Value (Name, Item);
end Merge_Property;
procedure Save_Property (Name : in String;
Item : in Util.Properties.Value) is
begin
Ada.Text_IO.Put (Output, Name);
Ada.Text_IO.Put (Output, "=");
Ada.Text_IO.Put_Line (Output, Util.Properties.To_String (Item));
end Save_Property;
-- ------------------------------
-- Append the file to the output
-- ------------------------------
procedure Load_File (File : in File_Record) is
File_Path : constant String := Rule.Get_Source_Path (File);
Props : Util.Properties.Manager;
begin
Log.Info ("loading {0}", File_Path);
Props.Load_Properties (Path => File_Path);
Props.Iterate (Process => Merge_Property'Access);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Context.Error ("Cannot read {0}: ", File_Path, Ada.Exceptions.Exception_Message (Ex));
end Load_File;
Iter : File_Cursor := Files.First;
begin
Ada.Directories.Create_Path (Dir);
while File_Record_Vectors.Has_Element (Iter) loop
File_Record_Vectors.Query_Element (Iter, Load_File'Access);
File_Record_Vectors.Next (Iter);
end loop;
Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => Path);
Merge.Iterate (Process => Save_Property'Access);
Ada.Text_IO.Close (File => Output);
end Install;
end Gen.Artifacts.Distribs.Bundles;
|
Update to use the new Iterate procedure from the Util.Properties package
|
Update to use the new Iterate procedure from the Util.Properties package
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
f2b0e1e28bb847e788fbe59940ba63371f792041
|
src/asf-components-widgets-factory.adb
|
src/asf-components-widgets-factory.adb
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
with ASF.Components.Widgets.Likes;
with ASF.Components.Widgets.Panels;
with ASF.Components.Widgets.Tabs;
with ASF.Components.Widgets.Selects;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Accordion return UIComponent_Access;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Chosen return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
function Create_Like return UIComponent_Access;
function Create_Panel return UIComponent_Access;
function Create_TabView return UIComponent_Access;
function Create_Tab return UIComponent_Access;
-- ------------------------------
-- Create a UIAccordion component
-- ------------------------------
function Create_Accordion return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UIAccordion;
end Create_Accordion;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIChoser component
-- ------------------------------
function Create_Chosen return UIComponent_Access is
begin
return new ASF.Components.Widgets.Selects.UIChosen;
end Create_Chosen;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
-- ------------------------------
-- Create a UILike component
-- ------------------------------
function Create_Like return UIComponent_Access is
begin
return new ASF.Components.Widgets.Likes.UILike;
end Create_Like;
-- ------------------------------
-- Create a UIPanel component
-- ------------------------------
function Create_Panel return UIComponent_Access is
begin
return new ASF.Components.Widgets.Panels.UIPanel;
end Create_Panel;
-- ------------------------------
-- Create a UITab component
-- ------------------------------
function Create_Tab return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UITab;
end Create_Tab;
-- ------------------------------
-- Create a UITabView component
-- ------------------------------
function Create_TabView return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UITabView;
end Create_TabView;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
ACCORDION_TAG : aliased constant String := "accordion";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
CHOSEN_TAG : aliased constant String := "chosen";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
LIKE_TAG : aliased constant String := "like";
PANEL_TAG : aliased constant String := "panel";
TAB_TAG : aliased constant String := "tab";
TAB_VIEW_TAG : aliased constant String := "tabView";
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
procedure Register (Factory : in out ASF.Factory.Component_Factory) is
begin
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => ACCORDION_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Accordion'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => AUTOCOMPLETE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Complete'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => CHOSEN_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Chosen'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INPUT_DATE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Input_Date'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INPUT_TEXT_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Input'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => GRAVATAR_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Gravatar'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => LIKE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Like'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => PANEL_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Panel'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => TAB_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Tab'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => TAB_VIEW_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_TabView'Access);
end Register;
end ASF.Components.Widgets.Factory;
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 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 ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
with ASF.Components.Widgets.Likes;
with ASF.Components.Widgets.Panels;
with ASF.Components.Widgets.Tabs;
with ASF.Components.Widgets.Selects;
with ASF.Components.Widgets.Progress;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Accordion return UIComponent_Access;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Chosen return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
function Create_Like return UIComponent_Access;
function Create_Panel return UIComponent_Access;
function Create_Progress return UIComponent_Access;
function Create_TabView return UIComponent_Access;
function Create_Tab return UIComponent_Access;
-- ------------------------------
-- Create a UIAccordion component
-- ------------------------------
function Create_Accordion return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UIAccordion;
end Create_Accordion;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIChoser component
-- ------------------------------
function Create_Chosen return UIComponent_Access is
begin
return new ASF.Components.Widgets.Selects.UIChosen;
end Create_Chosen;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
-- ------------------------------
-- Create a UILike component
-- ------------------------------
function Create_Like return UIComponent_Access is
begin
return new ASF.Components.Widgets.Likes.UILike;
end Create_Like;
-- ------------------------------
-- Create a UIPanel component
-- ------------------------------
function Create_Panel return UIComponent_Access is
begin
return new ASF.Components.Widgets.Panels.UIPanel;
end Create_Panel;
-- ------------------------------
-- Create a UIProgressBar component
-- ------------------------------
function Create_Progress return UIComponent_Access is
begin
return new ASF.Components.Widgets.Progress.UIProgressBar;
end Create_Progress;
-- ------------------------------
-- Create a UITab component
-- ------------------------------
function Create_Tab return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UITab;
end Create_Tab;
-- ------------------------------
-- Create a UITabView component
-- ------------------------------
function Create_TabView return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UITabView;
end Create_TabView;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
ACCORDION_TAG : aliased constant String := "accordion";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
CHOSEN_TAG : aliased constant String := "chosen";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
LIKE_TAG : aliased constant String := "like";
PANEL_TAG : aliased constant String := "panel";
PROGRESS_TAG : aliased constant String := "progress";
TAB_TAG : aliased constant String := "tab";
TAB_VIEW_TAG : aliased constant String := "tabView";
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
procedure Register (Factory : in out ASF.Factory.Component_Factory) is
begin
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => ACCORDION_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Accordion'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => AUTOCOMPLETE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Complete'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => CHOSEN_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Chosen'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INPUT_DATE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Input_Date'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INPUT_TEXT_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Input'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => GRAVATAR_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Gravatar'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => LIKE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Like'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => PANEL_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Panel'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => PROGRESS_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Progress'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => TAB_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Tab'Access);
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => TAB_VIEW_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_TabView'Access);
end Register;
end ASF.Components.Widgets.Factory;
|
Update the factory to register the <w:progress> component
|
Update the factory to register the <w:progress> component
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b73373536096dc66b987064eeb736259b13c1038
|
awa/samples/src/atlas-reviews-beans.ads
|
awa/samples/src/atlas-reviews-beans.ads
|
-----------------------------------------------------------------------
-- atlas-reviews-beans -- Beans for module reviews
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Methods;
with Atlas.Reviews.Modules;
with Atlas.Reviews.Models;
package Atlas.Reviews.Beans is
type Review_Bean is new Atlas.Reviews.Models.Review_Bean with record
Module : Atlas.Reviews.Modules.Review_Module_Access := null;
end record;
type Review_Bean_Access is access all Review_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Review_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Review_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Save (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
overriding
procedure Delete (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Reviews_Bean bean instance.
function Create_Review_Bean (Module : in Atlas.Reviews.Modules.Review_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end Atlas.Reviews.Beans;
|
-----------------------------------------------------------------------
-- atlas-reviews-beans -- Beans for module reviews
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Methods;
with Atlas.Reviews.Modules;
with Atlas.Reviews.Models;
package Atlas.Reviews.Beans is
type Review_Bean is new Atlas.Reviews.Models.Review_Bean with record
Module : Atlas.Reviews.Modules.Review_Module_Access := null;
end record;
type Review_Bean_Access is access all Review_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Review_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Review_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Save (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
overriding
procedure Delete (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
overriding
procedure Load (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Reviews_Bean bean instance.
function Create_Review_Bean (Module : in Atlas.Reviews.Modules.Review_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Review_List_Bean is new Atlas.Reviews.Models.Review_List_Bean with record
Module : Atlas.Reviews.Modules.Review_Module_Access := null;
Reviews : aliased Atlas.Reviews.Models.List_Info_List_Bean;
Reviews_Bean : Atlas.Reviews.Models.List_Info_List_Bean_Access;
end record;
type Review_List_Bean_Access is access all Review_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Review_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Review_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (Into : in out Review_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Review_List_Bean bean instance.
function Create_Review_List_Bean (Module : in Atlas.Reviews.Modules.Review_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end Atlas.Reviews.Beans;
|
Define the Review_List_Bean type
|
Define the Review_List_Bean type
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b099a731d41dc6b67de4b898cfe75e5710153502
|
awa/awaunit/awa-tests.adb
|
awa/awaunit/awa-tests.adb
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Setup test {0}", T.Get_Name);
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access);
end Initialize_Filters;
end AWA.Tests;
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
pragma Unreferenced (Add_Modules);
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access);
end Initialize_Filters;
end AWA.Tests;
|
Fix compilation with Aunit
|
Fix compilation with Aunit
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7d465e0e78f06ad000bf2df513bfe53cdfd67a16
|
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);
Assert (T, 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
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;
|
Fix compilation with GNAT 2011
|
Fix compilation with GNAT 2011
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
943e45f2722c87bb77a3c3abc6d4ac14912bfbd3
|
mat/src/memory/mat-memory-targets.ads
|
mat/src/memory/mat-memory-targets.ads
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Util.Events;
with MAT.Frames;
with MAT.Readers;
with MAT.Memory.Events;
with MAT.Memory.Tools;
package MAT.Memory.Targets is
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- 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);
private
protected type Memory_Allocator is
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- 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);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Reader : MAT.Readers.Reader_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Util.Events;
with MAT.Frames;
with MAT.Readers;
with MAT.Memory.Events;
with MAT.Memory.Tools;
package MAT.Memory.Targets is
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- 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);
-- 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);
private
protected type Memory_Allocator is
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- 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);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Reader : MAT.Readers.Reader_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
Define the Find procedure for the Target_Memory object
|
Define the Find procedure for the Target_Memory object
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
4a47010e0b03a4f6e90cfd1330602db8fa3fe1b8
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
-----------------------------------------------------------------------
-- 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 Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
with AWA.Tags.Beans;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Service : Modules.Question_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- 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);
-- Create or save the question.
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record
Service : Modules.Question_Module_Access := null;
Question : AWA.Questions.Models.Question_Ref;
end record;
type Answer_Bean_Access is access all Answer_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- 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);
-- Create or save the answer.
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the answer bean instance.
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Question_List_Bean is
new AWA.Questions.Models.Question_Info_List_Bean and Util.Beans.Basic.Bean with record
Service : Modules.Question_Module_Access := null;
Tag : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Question_List_Bean_Access is access all Question_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of question. If a tag was set, filter the list of questions with the tag.
procedure Load_List (Into : in out Question_List_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;
type Question_Display_Bean is new Util.Beans.Basic.Bean with record
Service : Modules.Question_Module_Access := null;
-- List of answers associated with the question.
Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean;
Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access;
-- The question.
Question : aliased AWA.Questions.Models.Question_Display_Info;
Question_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Question_Display_Bean_Access is access all Question_Display_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- 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);
-- 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;
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 Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
with AWA.Tags.Beans;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Service : Modules.Question_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- 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);
-- Create or save the question.
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record
Service : Modules.Question_Module_Access := null;
Question : AWA.Questions.Models.Question_Ref;
end record;
type Answer_Bean_Access is access all Answer_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- 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);
-- Create or save the answer.
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the answer bean instance.
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Question_List_Bean is limited new Util.Beans.Basic.Bean with record
Questions : aliased AWA.Questions.Models.Question_Info_List_Bean;
Service : Modules.Question_Module_Access := null;
Tag : Ada.Strings.Unbounded.Unbounded_String;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Questions_Bean : AWA.Questions.Models.Question_Info_List_Bean_Access;
end record;
type Question_List_Bean_Access is access all Question_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of question. If a tag was set, filter the list of questions with the tag.
procedure Load_List (Into : in out Question_List_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;
type Question_Display_Bean is new Util.Beans.Basic.Bean with record
Service : Modules.Question_Module_Access := null;
-- List of answers associated with the question.
Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean;
Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access;
-- The question.
Question : aliased AWA.Questions.Models.Question_Display_Info;
Question_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Question_Display_Bean_Access is access all Question_Display_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- 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);
-- 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;
end AWA.Questions.Beans;
|
Add the tags map for the list of question
|
Add the tags map for the list of question
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
730f7d12f37ad479501337e425e1bd3eb87a10e3
|
regtests/util-streams-files-tests.adb
|
regtests/util-streams-files-tests.adb
|
-----------------------------------------------------------------------
-- streams.files.tests -- Unit tests for buffered streams
-- Copyright (C) 2010, 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Files;
with Util.Streams.Texts;
package body Util.Streams.Files.Tests is
use Util.Tests;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Files.Create, Write, Flush, Close",
Test_Read_Write'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Files.Write, Flush",
Test_Write'Access);
end Add_Tests;
-- ------------------------------
-- Test reading and writing on a buffered stream with various buffer sizes
-- ------------------------------
procedure Test_Read_Write (T : in out Test) is
Stream : aliased File_Stream;
Buffer : Util.Streams.Texts.Print_Stream;
begin
for I in 1 .. 32 loop
Buffer.Initialize (Output => Stream'Unchecked_Access,
Input => null,
Size => I);
Stream.Create (Mode => Out_File, Name => "test-stream.txt");
Buffer.Write ("abcd");
Buffer.Write (" fghij");
Buffer.Flush;
Stream.Close;
declare
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Files.Read_File (Path => "test-stream.txt",
Into => Content,
Max_Size => 10000);
Assert_Equals (T, "abcd fghij", Content, "Invalid content written to the file stream");
end;
end loop;
end Test_Read_Write;
procedure Test_Write (T : in out Test) is
begin
null;
end Test_Write;
end Util.Streams.Files.Tests;
|
-----------------------------------------------------------------------
-- streams.files.tests -- Unit tests for buffered streams
-- Copyright (C) 2010, 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Files;
with Util.Streams.Texts;
package body Util.Streams.Files.Tests is
use Util.Tests;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Files.Create, Write, Flush, Close",
Test_Read_Write'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Files.Write, Flush",
Test_Write'Access);
end Add_Tests;
-- ------------------------------
-- Test reading and writing on a buffered stream with various buffer sizes
-- ------------------------------
procedure Test_Read_Write (T : in out Test) is
Stream : aliased File_Stream;
Buffer : Util.Streams.Texts.Print_Stream;
begin
for I in 1 .. 32 loop
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => I);
Stream.Create (Mode => Out_File, Name => "test-stream.txt");
Buffer.Write ("abcd");
Buffer.Write (" fghij");
Buffer.Flush;
Stream.Close;
declare
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Files.Read_File (Path => "test-stream.txt",
Into => Content,
Max_Size => 10000);
Assert_Equals (T, "abcd fghij", Content, "Invalid content written to the file stream");
end;
end loop;
end Test_Read_Write;
procedure Test_Write (T : in out Test) is
begin
null;
end Test_Write;
end Util.Streams.Files.Tests;
|
Update Print_Stream initialization
|
Update Print_Stream initialization
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e0349b4d39d820ab87d3944e241aea4ad9647b34
|
src/util-serialize-io-csv.adb
|
src/util-serialize-io-csv.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Ada.Strings.Unbounded.To_String (Value.Value));
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Ada.Strings.Unbounded.To_String (Value.Value));
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Write the attribute with a null value.
-- ------------------------------
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Entity (Name, "");
end Write_Null_Attribute;
-- ------------------------------
-- Write an entity with a null value.
-- ------------------------------
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Null_Attribute (Name);
end Write_Null_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Handler.Sink.Finish_Object ("", Handler);
else
Handler.Sink.Start_Array ("", Handler);
end if;
Handler.Sink.Start_Object ("", Handler);
end if;
Handler.Row := Row;
Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler);
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
begin
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
Handler.Sink := Sink'Unchecked_Access;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Handler.Sink := null;
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Write the attribute with a null value.
-- ------------------------------
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Entity (Name, "");
end Write_Null_Attribute;
-- ------------------------------
-- Write an entity with a null value.
-- ------------------------------
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Null_Attribute (Name);
end Write_Null_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Handler.Sink.Finish_Object ("", Handler);
else
Handler.Sink.Start_Array ("", Handler);
end if;
Handler.Sink.Start_Object ("", Handler);
end if;
Handler.Row := Row;
Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler);
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
begin
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
Handler.Sink := Sink'Unchecked_Access;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Handler.Sink := null;
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
Remove Write_Entity and Write_Attribute on Nullable_String
|
Remove Write_Entity and Write_Attribute on Nullable_String
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
51609ba9fcb7467fa3c4ae6f247d75c86158a0fe
|
src/gen.ads
|
src/gen.ads
|
-----------------------------------------------------------------------
-- Gen -- Code 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.
-----------------------------------------------------------------------
package Gen is
-- Library SVN identification
SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk";
-- Revision used (must run 'make version' to update)
SVN_REV : constant Positive := 1095;
end Gen;
|
-----------------------------------------------------------------------
-- gen -- Code Generator
-- Copyright (C) 2009, 2010, 2011, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
package Gen is
-- Library SVN identification
SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk";
-- Revision used (must run 'make version' to update)
SVN_REV : constant Positive := 1095;
subtype UString is Ada.Strings.Unbounded.Unbounded_String;
function To_UString (Value : in String) return UString
renames Ada.Strings.Unbounded.To_Unbounded_String;
function To_String (Value : in UString) return String
renames Ada.Strings.Unbounded.To_String;
function Length (Value : in UString) return Natural
renames Ada.Strings.Unbounded.Length;
function "=" (Left, Right : in UString) return Boolean
renames Ada.Strings.Unbounded."=";
function "=" (Left : in UString; Right : in String) return Boolean
renames Ada.Strings.Unbounded."=";
end Gen;
|
Declare the UString subtype to simplify the implementation and use of Unbounded_String
|
Declare the UString subtype to simplify the implementation and use of Unbounded_String
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
0807a3e633e2564ed870c8bdef5b4c529be3814f
|
src/asf-utils.ads
|
src/asf-utils.ads
|
-----------------------------------------------------------------------
-- asf-utils -- Various utility operations for ASF
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Strings.Unbounded;
with Util.Texts.Formats;
with Util.Beans.Objects;
package ASF.Utils is
-- Add in the <b>names</b> set, the basic text attributes that can be set
-- on HTML elements (dir, lang, style, title).
procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the onXXX attributes that can be set
-- on HTML elements (accesskey, tabindex, onXXX).
procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the size attributes that can be set
-- on HTML elements.
procedure Set_Input_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the size attributes that can be set
-- on <textarea> elements.
procedure Set_Textarea_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the online and onunload attributes that can be set
-- on <body> elements.
procedure Set_Body_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the dir, lang attributes that can be set
-- on <head> elements.
procedure Set_Head_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the onreset and onsubmit attributes that can be set
-- on <form> elements.
procedure Set_Form_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the attributes which are specific to a link.
procedure Set_Link_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the attributes which are specific to an input file.
procedure Set_File_Attributes (Names : in out Util.Strings.String_Set.Set);
type Object_Array is array (Positive range <>) of Util.Beans.Objects.Object;
package Formats is
new Util.Texts.Formats (Stream => Ada.Strings.Unbounded.Unbounded_String,
Char => Character,
Input => String,
Value => Util.Beans.Objects.Object,
Value_List => Object_Array,
Put => Ada.Strings.Unbounded.Append,
To_Input => Util.Beans.Objects.To_String);
end ASF.Utils;
|
-----------------------------------------------------------------------
-- asf-utils -- Various utility operations for ASF
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Strings.Unbounded;
with Util.Texts.Formats;
with Util.Beans.Objects;
package ASF.Utils is
pragma Preelaborate;
-- Add in the <b>names</b> set, the basic text attributes that can be set
-- on HTML elements (dir, lang, style, title).
procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the onXXX attributes that can be set
-- on HTML elements (accesskey, tabindex, onXXX).
procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the size attributes that can be set
-- on HTML elements.
procedure Set_Input_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the size attributes that can be set
-- on <textarea> elements.
procedure Set_Textarea_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the online and onunload attributes that can be set
-- on <body> elements.
procedure Set_Body_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the dir, lang attributes that can be set
-- on <head> elements.
procedure Set_Head_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the onreset and onsubmit attributes that can be set
-- on <form> elements.
procedure Set_Form_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the attributes which are specific to a link.
procedure Set_Link_Attributes (Names : in out Util.Strings.String_Set.Set);
-- Add in the <b>names</b> set, the attributes which are specific to an input file.
procedure Set_File_Attributes (Names : in out Util.Strings.String_Set.Set);
type Object_Array is array (Positive range <>) of Util.Beans.Objects.Object;
package Formats is
new Util.Texts.Formats (Stream => Ada.Strings.Unbounded.Unbounded_String,
Char => Character,
Input => String,
Value => Util.Beans.Objects.Object,
Value_List => Object_Array,
Put => Ada.Strings.Unbounded.Append,
To_Input => Util.Beans.Objects.To_String);
end ASF.Utils;
|
Add Preelaborate pragma
|
Add Preelaborate pragma
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
7387a615cb503344e06f3bccb1fcb0a075306688
|
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 := "61";
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 := "62";
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
|
16be00f81217d96bf483c32049b5577bc24e9f58
|
regtests/util-serialize-io-csv-tests.adb
|
regtests/util-serialize-io-csv-tests.adb
|
-----------------------------------------------------------------------
-- serialize-io-csv-tests -- Unit tests for CSV parser
-- Copyright (C) 2011, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Serialize.Mappers.Tests;
with Util.Serialize.IO.JSON.Tests;
package body Util.Serialize.IO.CSV.Tests is
package Caller is new Util.Test_Caller (Test, "Serialize.IO.CSV");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Write",
Test_Output'Access);
end Add_Tests;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
use Util.Serialize.Mappers.Tests;
procedure Check_Parse (Content : in String;
Expect : in Integer);
Mapping : aliased Util.Serialize.Mappers.Tests.Map_Test_Mapper.Mapper;
Mapper : aliased Util.Serialize.Mappers.Tests.Map_Test_Vector_Mapper.Mapper;
procedure Check_Parse (Content : in String;
Expect : in Integer) is
P : Parser;
Value : aliased Map_Test_Vector.Vector;
begin
P.Add_Mapping ("", Mapper'Unchecked_Access);
Map_Test_Vector_Mapper.Set_Context (P, Value'Unchecked_Access);
P.Parse_String (Content);
T.Assert (not P.Has_Error, "Parse error for: " & Content);
Util.Tests.Assert_Equals (T, 1, Integer (Value.Length), "Invalid result length");
Util.Tests.Assert_Equals (T, Expect, Integer (Value.Element (1).Value), "Invalid value");
end Check_Parse;
HDR : constant String := "name,status,value,bool" & ASCII.CR & ASCII.LF;
begin
Mapping.Add_Mapping ("name", FIELD_NAME);
Mapping.Add_Mapping ("value", FIELD_VALUE);
Mapping.Add_Mapping ("status", FIELD_BOOL);
Mapping.Add_Mapping ("bool", FIELD_BOOL);
Mapper.Set_Mapping (Mapping'Unchecked_Access);
Check_Parse (HDR & "joe,false,23,true", 23);
Check_Parse (HDR & "billy,false,""12"",true", 12);
Check_Parse (HDR & """John Potter"",false,""1234"",true", 1234);
Check_Parse (HDR & """John" & ASCII.CR & "Potter"",False,""3234"",True", 3234);
Check_Parse (HDR & """John" & ASCII.LF & "Potter"",False,""3234"",True", 3234);
end Test_Parser;
-- ------------------------------
-- Test the CSV output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Stream : Util.Serialize.IO.CSV.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.csv");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.csv");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Stream.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Util.Serialize.IO.JSON.Tests.Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "CSV output serialization");
end Test_Output;
end Util.Serialize.IO.CSV.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-csv-tests -- Unit tests for CSV parser
-- Copyright (C) 2011, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Serialize.Mappers.Tests;
with Util.Serialize.IO.JSON.Tests;
package body Util.Serialize.IO.CSV.Tests is
package Caller is new Util.Test_Caller (Test, "Serialize.IO.CSV");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Write",
Test_Output'Access);
end Add_Tests;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
use Util.Serialize.Mappers.Tests;
procedure Check_Parse (Content : in String;
Expect : in Integer);
Mapping : aliased Util.Serialize.Mappers.Tests.Map_Test_Mapper.Mapper;
Vector_Mapper : aliased Util.Serialize.Mappers.Tests.Map_Test_Vector_Mapper.Mapper;
procedure Check_Parse (Content : in String;
Expect : in Integer) is
P : Parser;
Value : aliased Map_Test_Vector.Vector;
Mapper : Util.Serialize.Mappers.Processing;
begin
Mapper.Add_Mapping ("", Vector_Mapper'Unchecked_Access);
Map_Test_Vector_Mapper.Set_Context (Mapper, Value'Unchecked_Access);
P.Parse_String (Content, Mapper);
T.Assert (not P.Has_Error, "Parse error for: " & Content);
Util.Tests.Assert_Equals (T, 1, Integer (Value.Length), "Invalid result length");
Util.Tests.Assert_Equals (T, Expect, Integer (Value.Element (1).Value), "Invalid value");
end Check_Parse;
HDR : constant String := "name,status,value,bool" & ASCII.CR & ASCII.LF;
begin
Mapping.Add_Mapping ("name", FIELD_NAME);
Mapping.Add_Mapping ("value", FIELD_VALUE);
Mapping.Add_Mapping ("status", FIELD_BOOL);
Mapping.Add_Mapping ("bool", FIELD_BOOL);
Vector_Mapper.Set_Mapping (Mapping'Unchecked_Access);
Check_Parse (HDR & "joe,false,23,true", 23);
Check_Parse (HDR & "billy,false,""12"",true", 12);
Check_Parse (HDR & """John Potter"",false,""1234"",true", 1234);
Check_Parse (HDR & """John" & ASCII.CR & "Potter"",False,""3234"",True", 3234);
Check_Parse (HDR & """John" & ASCII.LF & "Potter"",False,""3234"",True", 3234);
end Test_Parser;
-- ------------------------------
-- Test the CSV output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Stream : Util.Serialize.IO.CSV.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.csv");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.csv");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Stream.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Util.Serialize.IO.JSON.Tests.Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "CSV output serialization");
end Test_Output;
end Util.Serialize.IO.CSV.Tests;
|
Update the unit tests for the new parser/reader interfaces
|
Update the unit tests for the new parser/reader interfaces
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
3e4d2b3a06880ea17808857845fa7661e74337c1
|
src/util-commands-drivers.adb
|
src/util-commands-drivers.adb
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body Util.Commands.Drivers is
-- The logger
Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name);
-- ------------------------------
-- Write the command usage.
-- ------------------------------
procedure Usage (Command : in Command_Type) is
begin
null;
end Usage;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
-- ------------------------------
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
begin
Command.Driver.Log (Level, Name, Message);
end Log;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access) is
begin
Command.Driver := Driver'Unchecked_Access;
Driver.List.Include (Name, Command);
end Add_Command;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Handler : in Command_Handler) is
begin
Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access,
Handler => Handler));
end Add_Command;
-- ------------------------------
-- Find the command having the given name.
-- Returns null if the command was not found.
-- ------------------------------
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access is
Pos : constant Command_Maps.Cursor := Driver.List.Find (Name);
begin
if Command_Maps.Has_Element (Pos) then
return Command_Maps.Element (Pos);
else
return null;
end if;
end Find_Command;
-- ------------------------------
-- Execute the command registered under the given name.
-- ------------------------------
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type) is
Command : constant Command_Access := Driver.Find_Command (Name);
begin
if Command /= null then
Command.Execute (Name, Args, Context);
end if;
end Execute;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- ------------------------------
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
begin
Logs.Print (Level, "{0}: {1}", Name, Message);
end Log;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Command : in Handler_Command_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type) is
begin
Command.Handler (Name, Args, Context);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Handler_Command_Type;
Context : in out Context_Type) is
begin
null;
end Help;
end Util.Commands.Drivers;
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Ada.Text_IO; use Ada.Text_IO;
package body Util.Commands.Drivers is
-- The logger
Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name);
-- ------------------------------
-- Write the command usage.
-- ------------------------------
procedure Usage (Command : in Command_Type) is
begin
null;
end Usage;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
-- ------------------------------
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
begin
Command.Driver.Log (Level, Name, Message);
end Log;
-- ------------------------------
-- Execute the help command with the arguments.
-- Print the help for every registered command.
-- ------------------------------
overriding
procedure Execute (Command : in Help_Command_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type) is
procedure Print (Position : in Command_Maps.Cursor);
procedure Print (Position : in Command_Maps.Cursor) is
Name : constant String := Command_Maps.Key (Position);
begin
Put_Line (" " & Name);
end Print;
begin
Logs.Debug ("Execute command {0}", Name);
if Name'Length = 0 then
-- Usage;
New_Line;
Put ("Type '");
-- Put (Ada.Command_Line.Command_Name);
Put_Line (" help {command}' for help on a specific command.");
New_Line;
Put_Line ("Available subcommands:");
Command.Driver.List.Iterate (Process => Print'Access);
else
declare
Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Name);
begin
if Target_Cmd = null then
Logs.Error ("Unknown command {0}", Name);
else
Target_Cmd.Help (Context);
end if;
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in Help_Command_Type;
Context : in out Context_Type) is
begin
null;
end Help;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access) is
begin
Command.Driver := Driver'Unchecked_Access;
Driver.List.Include (Name, Command);
end Add_Command;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Handler : in Command_Handler) is
begin
Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access,
Handler => Handler));
end Add_Command;
-- ------------------------------
-- Find the command having the given name.
-- Returns null if the command was not found.
-- ------------------------------
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access is
Pos : constant Command_Maps.Cursor := Driver.List.Find (Name);
begin
if Command_Maps.Has_Element (Pos) then
return Command_Maps.Element (Pos);
else
return null;
end if;
end Find_Command;
-- ------------------------------
-- Execute the command registered under the given name.
-- ------------------------------
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type) is
Command : constant Command_Access := Driver.Find_Command (Name);
begin
if Command /= null then
Command.Execute (Name, Args, Context);
end if;
end Execute;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- ------------------------------
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
begin
Logs.Print (Level, "{0}: {1}", Name, Message);
end Log;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Command : in Handler_Command_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type) is
begin
Command.Handler (Name, Args, Context);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Handler_Command_Type;
Context : in out Context_Type) is
begin
null;
end Help;
end Util.Commands.Drivers;
|
Implement the Execute and Help procedures for the Help_Command_Type
|
Implement the Execute and Help procedures for the Help_Command_Type
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ccf218b182c51448dcd16584e8f9d3510f292464
|
src/util-properties-bundles.adb
|
src/util-properties-bundles.adb
|
-----------------------------------------------------------------------
-- util-properties-bundles -- Generic name/value property management
-- Copyright (C) 2001 - 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
with Util.Files;
package body Util.Properties.Bundles is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles");
use type Util.Properties.Manager_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
-- 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.
overriding
function Exists (Self : in Manager;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Manager;
Name : in String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object));
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl = null then
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
end if;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Integer := Loc_Name'Last;
begin
Log.Debug ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos + 1 >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Log.Debug ("Searching for {0}", Bundle_Name);
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Util.Concurrent.Counters.Increment (Bundle.Impl.Count);
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1;
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean);
Path : constant String := To_String (Factory.Path);
Pattern : constant String := Name & "*.properties";
Names : Util.Strings.String_Set.Set;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
subtype Cursor is Bundle_Map.Cursor;
Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11);
Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access);
Bundle_Name : Name_Access;
Bundle : Bundle_Manager_Access;
begin
Log.Info ("Loading file {0}", File_Path);
if Bundle_Map.Has_Element (Pos) then
Bundle := Bundle_Map.Element (Pos);
else
Bundle := new Manager;
Bundle_Name := new String '(Base_Name);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Names.Insert (Bundle_Name);
end if;
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Found := True;
Done := False;
end Process_File;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Factory.Lock.Write;
begin
Util.Files.Iterate_Files_Path (Pattern => Pattern,
Path => Path,
Process => Process_File'Access,
Going => Ada.Strings.Backward);
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name);
begin
if Util.Beans.Objects.Is_Null (Result) then
declare
Iter : Cursor := From.List.First;
begin
while Has_Element (Iter) loop
Result := Element (Iter).all.Get_Value (Name);
exit when not Util.Beans.Objects.Is_Null (Result);
Iter := Next (Iter);
end loop;
end;
end if;
return Result;
end Get_Value;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in String)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager;
Name : in String) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- 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
begin
raise Program_Error with "Iterate is not implemented on Bundle";
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Ada.Strings.Unbounded.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Ada.Strings.Unbounded.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
-----------------------------------------------------------------------
-- util-properties-bundles -- Generic name/value property management
-- Copyright (C) 2001 - 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
with Util.Files;
package body Util.Properties.Bundles is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles");
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is new Util.Properties.Interface_P.Manager with private;
-- 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.
overriding
function Exists (Self : in Manager;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Manager;
Name : in String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object));
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
private
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is new Util.Properties.Interface_P.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
end record;
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Initialize;
procedure Adjust (Object : in out Manager) is
use Util.Properties.Interface_P;
begin
if Object.Impl = null then
Object.Impl := new Util.Properties.Bundles.Interface_P.Manager;
end if;
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Integer := Loc_Name'Last;
begin
Log.Debug ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos + 1 >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Log.Debug ("Searching for {0}", Bundle_Name);
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Util.Concurrent.Counters.Increment (Bundle.Impl.Count);
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1;
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean);
Path : constant String := To_String (Factory.Path);
Pattern : constant String := Name & "*.properties";
Names : Util.Strings.String_Set.Set;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
subtype Cursor is Bundle_Map.Cursor;
Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11);
Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access);
Bundle_Name : Name_Access;
Bundle : Bundle_Manager_Access;
begin
Log.Info ("Loading file {0}", File_Path);
if Bundle_Map.Has_Element (Pos) then
Bundle := Bundle_Map.Element (Pos);
else
Bundle := new Manager;
Bundle_Name := new String '(Base_Name);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Names.Insert (Bundle_Name);
end if;
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Found := True;
Done := False;
end Process_File;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Factory.Lock.Write;
begin
Util.Files.Iterate_Files_Path (Pattern => Pattern,
Path => Path,
Process => Process_File'Access,
Going => Ada.Strings.Backward);
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name);
begin
if Util.Beans.Objects.Is_Null (Result) then
declare
Iter : Cursor := From.List.First;
begin
while Has_Element (Iter) loop
Result := Element (Iter).all.Get_Value (Name);
exit when not Util.Beans.Objects.Is_Null (Result);
Iter := Next (Iter);
end loop;
end;
end if;
return Result;
end Get_Value;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in String)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager;
Name : in String) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- 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
begin
raise Program_Error with "Iterate is not implemented on Bundle";
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
function Create_Copy (Self : in Manager)
return Util.Properties.Interface_P.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Ada.Strings.Unbounded.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Ada.Strings.Unbounded.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
Remove unecessary use type clause
|
Remove unecessary use type clause
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c2bb7a98027f8f6e44b0d03460a258a2e056459a
|
src/ado-sessions.adb
|
src/ado-sessions.adb
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ADO.Drivers;
with ADO.Sequences;
package body ADO.Sessions is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sessions");
procedure Check_Session (Database : in Session'Class) is
begin
if Database.Impl = null then
Log.Error ("Session is closed or not initialized");
raise NOT_OPEN;
end if;
end Check_Session;
-- ---------
-- Session
-- ---------
-- ------------------------------
-- Get the session status.
-- ------------------------------
function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is
begin
if Database.Impl = null then
return ADO.Databases.CLOSED;
end if;
return Database.Impl.Database.Get_Status;
end Get_Status;
-- ------------------------------
-- Close the session.
-- ------------------------------
procedure Close (Database : in out Session) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
begin
Log.Info ("Closing session");
if Database.Impl /= null then
Database.Impl.Database.Close;
Database.Impl.Counter := Database.Impl.Counter - 1;
if Database.Impl.Counter = 0 then
Free (Database.Impl);
end if;
--
-- if Database.Impl.Proxy /= null then
-- Database.Impl.Proxy.Counter := Database.Impl.Proxy.Counter - 1;
-- end if;
Database.Impl := null;
end if;
end Close;
-- ------------------------------
-- Get the database connection.
-- ------------------------------
function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is
begin
Check_Session (Database);
return Database.Impl.Database;
end Get_Connection;
-- ------------------------------
-- Attach the object to the session.
-- ------------------------------
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class) is
pragma Unreferenced (Object);
begin
Check_Session (Database);
end Attach;
-- ------------------------------
-- Check if the session contains the object identified by the given key.
-- ------------------------------
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean is
begin
Check_Session (Database);
return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item);
end Contains;
-- ------------------------------
-- Remove the object from the session cache.
-- ------------------------------
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key) is
begin
Check_Session (Database);
ADO.Objects.Cache.Remove (Database.Impl.Cache, Item);
end Evict;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Query);
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index);
Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement and initialize the SQL statement with the query definition.
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index;
SQL : constant String := ADO.Queries.Get_SQL (Query, Index);
begin
return Database.Impl.Database.Create_Statement (SQL);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
if Query in ADO.Queries.Context'Class then
declare
Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index;
SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Index);
Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
else
declare
Stmt : Query_Statement := Database.Impl.Database.Create_Statement (Table);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
end if;
end Create_Statement;
-- ---------
-- Master Session
-- ---------
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Session) is
begin
Log.Info ("Begin transaction");
Check_Session (Database);
Database.Impl.Database.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Session) is
begin
Log.Info ("Commit transaction");
Check_Session (Database);
Database.Impl.Database.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Session) is
begin
Log.Info ("Rollback transaction");
Check_Session (Database);
Database.Impl.Database.Rollback;
end Rollback;
-- ------------------------------
-- Allocate an identifier for the table.
-- ------------------------------
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class) is
begin
Check_Session (Database);
ADO.Sequences.Allocate (Database.Sequences.all, Id);
end Allocate;
-- ------------------------------
-- Flush the objects that were modified.
-- ------------------------------
procedure Flush (Database : in out Master_Session) is
begin
Check_Session (Database);
end Flush;
overriding
procedure Adjust (Object : in out Session) is
begin
if Object.Impl /= null then
Object.Impl.Counter := Object.Impl.Counter + 1;
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Session) is
begin
if Object.Impl /= null then
if Object.Impl.Counter = 1 then
Object.Close;
else
Object.Impl.Counter := Object.Impl.Counter - 1;
end if;
end if;
end Finalize;
-- ------------------------------
-- Create a delete statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is
use type ADO.Objects.Session_Proxy_Access;
begin
Check_Session (Database);
if Database.Impl.Proxy = null then
Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl);
end if;
return Database.Impl.Proxy;
end Get_Session_Proxy;
end ADO.Sessions;
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ADO.Drivers;
with ADO.Sequences;
package body ADO.Sessions is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sessions");
procedure Check_Session (Database : in Session'Class) is
begin
if Database.Impl = null then
Log.Error ("Session is closed or not initialized");
raise NOT_OPEN;
end if;
end Check_Session;
-- ---------
-- Session
-- ---------
-- ------------------------------
-- Get the session status.
-- ------------------------------
function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is
begin
if Database.Impl = null then
return ADO.Databases.CLOSED;
end if;
return Database.Impl.Database.Get_Status;
end Get_Status;
-- ------------------------------
-- Close the session.
-- ------------------------------
procedure Close (Database : in out Session) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
begin
Log.Info ("Closing session");
if Database.Impl /= null then
Database.Impl.Database.Close;
Database.Impl.Counter := Database.Impl.Counter - 1;
if Database.Impl.Counter = 0 then
Free (Database.Impl);
end if;
--
-- if Database.Impl.Proxy /= null then
-- Database.Impl.Proxy.Counter := Database.Impl.Proxy.Counter - 1;
-- end if;
Database.Impl := null;
end if;
end Close;
-- ------------------------------
-- Get the database connection.
-- ------------------------------
function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is
begin
Check_Session (Database);
return Database.Impl.Database;
end Get_Connection;
-- ------------------------------
-- Attach the object to the session.
-- ------------------------------
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class) is
pragma Unreferenced (Object);
begin
Check_Session (Database);
end Attach;
-- ------------------------------
-- Check if the session contains the object identified by the given key.
-- ------------------------------
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean is
begin
Check_Session (Database);
return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item);
end Contains;
-- ------------------------------
-- Remove the object from the session cache.
-- ------------------------------
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key) is
begin
Check_Session (Database);
ADO.Objects.Cache.Remove (Database.Impl.Cache, Item);
end Evict;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Query);
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index);
Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement and initialize the SQL statement with the query definition.
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index;
SQL : constant String := ADO.Queries.Get_SQL (Query, Index);
begin
return Database.Impl.Database.Create_Statement (SQL);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
if False and Query in ADO.Queries.Context'Class then
declare
Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index;
SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Index);
Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
else
declare
Stmt : Query_Statement := Database.Impl.Database.Create_Statement (Table);
begin
if Query in ADO.Queries.Context'Class then
declare
Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index;
SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Index);
begin
ADO.SQL.Append (Stmt.Get_Query.SQL, SQL);
end;
end if;
Stmt.Set_Parameters (Query);
return Stmt;
end;
end if;
end Create_Statement;
-- ---------
-- Master Session
-- ---------
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Session) is
begin
Log.Info ("Begin transaction");
Check_Session (Database);
Database.Impl.Database.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Session) is
begin
Log.Info ("Commit transaction");
Check_Session (Database);
Database.Impl.Database.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Session) is
begin
Log.Info ("Rollback transaction");
Check_Session (Database);
Database.Impl.Database.Rollback;
end Rollback;
-- ------------------------------
-- Allocate an identifier for the table.
-- ------------------------------
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class) is
begin
Check_Session (Database);
ADO.Sequences.Allocate (Database.Sequences.all, Id);
end Allocate;
-- ------------------------------
-- Flush the objects that were modified.
-- ------------------------------
procedure Flush (Database : in out Master_Session) is
begin
Check_Session (Database);
end Flush;
overriding
procedure Adjust (Object : in out Session) is
begin
if Object.Impl /= null then
Object.Impl.Counter := Object.Impl.Counter + 1;
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Session) is
begin
if Object.Impl /= null then
if Object.Impl.Counter = 1 then
Object.Close;
else
Object.Impl.Counter := Object.Impl.Counter - 1;
end if;
end if;
end Finalize;
-- ------------------------------
-- Create a delete statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Check_Session (Database);
return Database.Impl.Database.Create_Statement (Table);
end Create_Statement;
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is
use type ADO.Objects.Session_Proxy_Access;
begin
Check_Session (Database);
if Database.Impl.Proxy = null then
Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl);
end if;
return Database.Impl.Proxy;
end Get_Session_Proxy;
end ADO.Sessions;
|
Simplify the Create_Statement based on an external filter
|
Simplify the Create_Statement based on an external filter
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
9adf5714a6939d76bbf03601994ed831df78a968
|
src/wiki-writers.ads
|
src/wiki-writers.ads
|
-----------------------------------------------------------------------
-- wiki-writers -- Wiki writers
-- 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.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;
-- 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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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;
|
Declare a Write_Wide_Attribute procedure
|
Declare a Write_Wide_Attribute procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
0f7b0f4ea902a8af1ad0af805894bd9c2179da63
|
src/core/texts/util-texts-builders.ads
|
src/core/texts/util-texts-builders.ads
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 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.
-----------------------------------------------------------------------
private with Ada.Finalization;
-- == Description ==
-- The <tt>Util.Texts.Builders</tt> generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The <tt>Builder</tt> type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an <tt>Append</tt> procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the <tt>Iterate</tt> operation that allows to get the content
-- collected by the builder. When using the <tt>Iterate</tt> operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- == Example ==
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that recieves
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the <tt>Iterate</tt> operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
generic
type Element_Type is (<>);
type Input is array (Positive range <>) of Element_Type;
Chunk_Size : Positive := 80;
package Util.Texts.Builders is
pragma Preelaborate;
type Builder (Len : Positive) is limited private;
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Input);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Element_Type);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input));
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Input;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Input;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Input);
procedure Get (Source : in Builder);
private
pragma Inline (Length);
pragma Inline (Iterate);
type Block;
type Block_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Block_Access;
Last : Natural := 0;
Content : Input (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Block_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Block (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
end Util.Texts.Builders;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2017, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Finalization;
-- == Description ==
-- The <tt>Util.Texts.Builders</tt> generic package was designed to provide string builders.
-- The interface was designed to reduce memory copies as much as possible.
--
-- * The <tt>Builder</tt> type holds a list of chunks into which texts are appended.
-- * The builder type holds an initial chunk whose capacity is defined when the builder
-- instance is declared.
-- * There is only an <tt>Append</tt> procedure which allows to append text to the builder.
-- This is the only time when a copy is made.
-- * The package defines the <tt>Iterate</tt> operation that allows to get the content
-- collected by the builder. When using the <tt>Iterate</tt> operation, no copy is
-- performed since chunks data are passed passed by reference.
-- * The type is limited to forbid copies of the builder instance.
--
-- == Example ==
-- First, instantiate the package for the element type (eg, String):
--
-- package String_Builder is new Util.Texts.Builders (Character, String);
--
-- Declare the string builder instance with its initial capacity:
--
-- Builder : String_Builder.Builder (256);
--
-- And append to it:
--
-- String_Builder.Append (Builder, "Hello");
--
-- To get the content collected in the builder instance, write a procedure that recieves
-- the chunk data as parameter:
--
-- procedure Collect (Item : in String) is ...
--
-- And use the <tt>Iterate</tt> operation:
--
-- String_Builder.Iterate (Builder, Collect'Access);
--
generic
type Element_Type is (<>);
type Input is array (Positive range <>) of Element_Type;
Chunk_Size : Positive := 80;
package Util.Texts.Builders is
pragma Preelaborate;
type Builder (Len : Positive) is limited private;
-- Get the length of the item builder.
function Length (Source : in Builder) return Natural;
-- Get the capacity of the builder.
function Capacity (Source : in Builder) return Natural;
-- Get the builder block size.
function Block_Size (Source : in Builder) return Positive;
-- Set the block size for the allocation of next chunks.
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Input);
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
procedure Append (Source : in out Builder;
New_Item : in Element_Type);
-- Clear the source freeing any storage allocated for the buffer.
procedure Clear (Source : in out Builder);
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input));
-- Get the buffer content as an array.
function To_Array (Source : in Builder) return Input;
-- Return the content starting from the tail and up to <tt>Length</tt> items.
function Tail (Source : in Builder;
Length : in Natural) return Input;
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
generic
with procedure Process (Content : in Input);
procedure Get (Source : in Builder);
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
generic
type Value is limited private;
type Value_List is array (Positive range <>) of Value;
with procedure Append (Input : in out Builder; Item : in Value);
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List);
private
pragma Inline (Length);
pragma Inline (Iterate);
type Block;
type Block_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Block_Access;
Last : Natural := 0;
Content : Input (1 .. Len);
end record;
type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record
Current : Block_Access;
Block_Size : Positive := Chunk_Size;
Length : Natural := 0;
First : aliased Block (Len);
end record;
pragma Finalize_Storage_Only (Builder);
-- Setup the builder.
overriding
procedure Initialize (Source : in out Builder);
-- Finalize the builder releasing the storage.
overriding
procedure Finalize (Source : in out Builder);
end Util.Texts.Builders;
|
Declare the Format generic procedure
|
Declare the Format generic procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
94cd9d36845e5d39714e08807771ad4f26b0a6c3
|
src/sys/streams/util-streams-pipes.ads
|
src/sys/streams/util-streams-pipes.ads
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Processes;
-- == Pipes ==
-- The `Util.Streams.Pipes` package defines a pipe stream to or from a process.
-- It allows to launch an external program while getting the program standard output or
-- providing the program standard input. The `Pipe_Stream` type represents the input or
-- output stream for the external program. This is a portable interface that works on
-- Unix and Windows.
--
-- The process is created and launched by the `Open` operation. The pipe allows
-- to read or write to the process through the `Read` and `Write` operation.
-- It is very close to the *popen* operation provided by the C stdio library.
-- First, create the pipe instance:
--
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
--
-- The pipe instance can be associated with only one process at a time.
-- The process is launched by using the `Open` command and by specifying the command
-- to execute as well as the pipe redirection mode:
--
-- * `READ` to read the process standard output,
-- * `WRITE` to write the process standard input.
--
-- For example to run the `ls -l` command and read its output, we could run it by using:
--
-- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ);
--
-- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the
-- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads
-- the pipe to fill the buffer. The initialization of the buffer is the following:
--
-- with Util.Streams.Buffered;
-- ...
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Access, Size => 1024);
--
-- And to read the process output, one can use the following:
--
-- Content : Ada.Strings.Unbounded.Unbounded_String;
-- ...
-- Buffer.Read (Into => Content);
--
-- The pipe object should be closed when reading or writing to it is finished.
-- By closing the pipe, the caller will wait for the termination of the process.
-- The process exit status can be obtained by using the `Get_Exit_Status` function.
--
-- Pipe.Close;
-- if Pipe.Get_Exit_Status /= 0 then
-- Ada.Text_IO.Put_Line ("Command exited with status "
-- & Integer'Image (Pipe.Get_Exit_Status));
-- end if;
--
-- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied.
-- When leaving the scope of the `Pipe_Stream` instance, the application will wait for
-- the process to terminate.
--
-- Before opening the pipe, it is possible to have some control on the process that
-- will be created to configure:
--
-- * The shell that will be used to launch the process,
-- * The process working directory,
-- * Redirect the process output to a file,
-- * Redirect the process error to a file,
-- * Redirect the process input from a file.
--
-- All these operations must be made before calling the `Open` procedure.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String);
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Input_Stream (Stream : in out Pipe_Stream;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Stream : in out Pipe_Stream;
Path : in String);
-- Closes the given file descriptor in the child process before executing the command.
procedure Add_Close (Stream : in out Pipe_Stream;
Fd : in Util.Processes.File_Type);
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
procedure Stop (Stream : in out Pipe_Stream;
Signal : in Positive := 15);
private
type Pipe_Stream is limited new Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
end Util.Streams.Pipes;
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018, 2019, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Processes;
-- == Pipes ==
-- The `Util.Streams.Pipes` package defines a pipe stream to or from a process.
-- It allows to launch an external program while getting the program standard output or
-- providing the program standard input. The `Pipe_Stream` type represents the input or
-- output stream for the external program. This is a portable interface that works on
-- Unix and Windows.
--
-- The process is created and launched by the `Open` operation. The pipe allows
-- to read or write to the process through the `Read` and `Write` operation.
-- It is very close to the *popen* operation provided by the C stdio library.
-- First, create the pipe instance:
--
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
--
-- The pipe instance can be associated with only one process at a time.
-- The process is launched by using the `Open` command and by specifying the command
-- to execute as well as the pipe redirection mode:
--
-- * `READ` to read the process standard output,
-- * `WRITE` to write the process standard input.
--
-- For example to run the `ls -l` command and read its output, we could run it by using:
--
-- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ);
--
-- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the
-- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads
-- the pipe to fill the buffer. The initialization of the buffer is the following:
--
-- with Util.Streams.Buffered;
-- ...
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024);
--
-- And to read the process output, one can use the following:
--
-- Content : Ada.Strings.Unbounded.Unbounded_String;
-- ...
-- Buffer.Read (Into => Content);
--
-- The pipe object should be closed when reading or writing to it is finished.
-- By closing the pipe, the caller will wait for the termination of the process.
-- The process exit status can be obtained by using the `Get_Exit_Status` function.
--
-- Pipe.Close;
-- if Pipe.Get_Exit_Status /= 0 then
-- Ada.Text_IO.Put_Line ("Command exited with status "
-- & Integer'Image (Pipe.Get_Exit_Status));
-- end if;
--
-- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied.
-- When leaving the scope of the `Pipe_Stream` instance, the application will wait for
-- the process to terminate.
--
-- Before opening the pipe, it is possible to have some control on the process that
-- will be created to configure:
--
-- * The shell that will be used to launch the process,
-- * The process working directory,
-- * Redirect the process output to a file,
-- * Redirect the process error to a file,
-- * Redirect the process input from a file.
--
-- All these operations must be made before calling the `Open` procedure.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String);
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Input_Stream (Stream : in out Pipe_Stream;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Stream : in out Pipe_Stream;
Path : in String);
-- Closes the given file descriptor in the child process before executing the command.
procedure Add_Close (Stream : in out Pipe_Stream;
Fd : in Util.Processes.File_Type);
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
procedure Stop (Stream : in out Pipe_Stream;
Signal : in Positive := 15);
private
type Pipe_Stream is limited new Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
end Util.Streams.Pipes;
|
Fix the examples in the documentation
|
Fix the examples in the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8b68ee9656c59476ff7c55145bae3389ced9a858
|
regtests/util-events-timers-tests.adb
|
regtests/util-events-timers-tests.adb
|
-----------------------------------------------------------------------
-- util-events-timers-tests -- Unit tests for timers
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Events.Timers.Tests is
use Util.Tests;
use type Ada.Real_Time.Time;
package Caller is new Util.Test_Caller (Test, "Events.Timers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled",
Test_Empty_Timer'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Process",
Test_Timer_Event'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat",
Test_Repeat_Timer'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat+Process",
Test_Many_Timers'Access);
end Add_Tests;
overriding
procedure Time_Handler (Sub : in out Test;
Event : in out Timer_Ref'Class) is
begin
Sub.Count := Sub.Count + 1;
if Sub.Repeat > 1 then
Sub.Repeat := Sub.Repeat - 1;
Event.Repeat (Ada.Real_Time.Milliseconds (1));
end if;
end Time_Handler;
-- -----------------------
-- Test empty timers.
-- -----------------------
procedure Test_Empty_Timer (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Deadline : Ada.Real_Time.Time;
begin
T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled");
T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value");
R.Cancel;
M.Process (Deadline);
T.Assert (Deadline = Ada.Real_Time.Time_Last,
"The Process operation returned invalid deadline");
end Test_Empty_Timer;
procedure Test_Timer_Event (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
Now : Ada.Real_Time.Time;
begin
for Retry in 1 .. 10 loop
M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10));
M.Process (Deadline);
Now := Ada.Real_Time.Clock;
exit when Now < Deadline;
end loop;
T.Assert (Now < Deadline, "The timer deadline is not correct");
delay until Deadline;
M.Process (Deadline);
Assert_Equals (T, 1, T.Count, "The timer handler was not called");
end Test_Timer_Event;
-- -----------------------
-- Test repeating timers.
-- -----------------------
procedure Test_Repeat_Timer (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
Now : Ada.Real_Time.Time;
begin
T.Count := 0;
T.Repeat := 5;
for Retry in 1 .. 10 loop
M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10));
M.Process (Deadline);
Now := Ada.Real_Time.Clock;
exit when Now < Deadline;
end loop;
T.Assert (Now < Deadline, "The timer deadline is not correct");
loop
delay until Deadline;
M.Process (Deadline);
exit when Deadline >= Now + Ada.Real_Time.Seconds (1);
end loop;
Assert_Equals (T, 5, T.Count, "The timer handler was not repeated");
end Test_Repeat_Timer;
-- -----------------------
-- Test executing several timers.
-- -----------------------
procedure Test_Many_Timers (T : in out Test) is
Timer_Count : constant Positive := 30;
type Timer_Ref_Array is array (1 .. Timer_Count) of Timer_Ref;
type Test_Ref_Array is array (1 .. Timer_Count) of aliased Test;
M : Timer_List;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
R : Timer_Ref_Array;
D : Test_Ref_Array;
Dt : Ada.Real_Time.Time_Span;
Count : Natural := 0;
begin
for I in R'Range loop
D (I).Count := 0;
D (I).Repeat := 4;
if I mod 2 = 0 then
Dt := Ada.Real_Time.Milliseconds (40);
else
Dt := Ada.Real_Time.Milliseconds (20);
end if;
M.Set_Timer (D (I)'Unchecked_Access, R (I), Start + Dt);
end loop;
loop
M.Process (Deadline);
exit when Deadline >= Start + Ada.Real_Time.Seconds (10);
Count := Count + 1;
delay until Deadline;
end loop;
Util.Tests.Assert_Equals (T, 8, Count, "Count of Process");
for I in D'Range loop
Util.Tests.Assert_Equals (T, 4, D (I).Count, "Invalid count for timer at "
& Natural'Image (I) & " " & Natural'Image (Count));
end loop;
end Test_Many_Timers;
end Util.Events.Timers.Tests;
|
-----------------------------------------------------------------------
-- util-events-timers-tests -- Unit tests for timers
-- Copyright (C) 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Events.Timers.Tests is
use Util.Tests;
use type Ada.Real_Time.Time;
package Caller is new Util.Test_Caller (Test, "Events.Timers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled",
Test_Empty_Timer'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Process",
Test_Timer_Event'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat",
Test_Repeat_Timer'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat+Process",
Test_Many_Timers'Access);
end Add_Tests;
overriding
procedure Time_Handler (Sub : in out Test;
Event : in out Timer_Ref'Class) is
begin
Sub.Count := Sub.Count + 1;
if Sub.Repeat > 1 then
Sub.Repeat := Sub.Repeat - 1;
Event.Repeat (Ada.Real_Time.Milliseconds (1));
end if;
end Time_Handler;
-- -----------------------
-- Test empty timers.
-- -----------------------
procedure Test_Empty_Timer (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Deadline : Ada.Real_Time.Time;
begin
T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled");
T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value");
R.Cancel;
M.Process (Deadline);
T.Assert (Deadline = Ada.Real_Time.Time_Last,
"The Process operation returned invalid deadline");
end Test_Empty_Timer;
procedure Test_Timer_Event (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
Now : Ada.Real_Time.Time;
begin
for Retry in 1 .. 10 loop
M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10));
M.Process (Deadline);
Now := Ada.Real_Time.Clock;
exit when Now < Deadline;
end loop;
T.Assert (Now < Deadline, "The timer deadline is not correct");
delay until Deadline;
M.Process (Deadline);
Assert_Equals (T, 1, T.Count, "The timer handler was not called");
end Test_Timer_Event;
-- -----------------------
-- Test repeating timers.
-- -----------------------
procedure Test_Repeat_Timer (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
Now : Ada.Real_Time.Time;
begin
T.Count := 0;
T.Repeat := 5;
for Retry in 1 .. 10 loop
M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10));
M.Process (Deadline);
Now := Ada.Real_Time.Clock;
exit when Now < Deadline;
end loop;
T.Assert (Now < Deadline, "The timer deadline is not correct");
loop
delay until Deadline;
M.Process (Deadline);
exit when Deadline >= Now + Ada.Real_Time.Seconds (1);
end loop;
Assert_Equals (T, 5, T.Count, "The timer handler was not repeated");
end Test_Repeat_Timer;
-- -----------------------
-- Test executing several timers.
-- -----------------------
procedure Test_Many_Timers (T : in out Test) is
Timer_Count : constant Positive := 30;
type Timer_Ref_Array is array (1 .. Timer_Count) of Timer_Ref;
type Test_Ref_Array is array (1 .. Timer_Count) of aliased Test;
M : Timer_List;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
R : Timer_Ref_Array;
D : Test_Ref_Array;
Dt : Ada.Real_Time.Time_Span;
Count : Natural := 0;
begin
for I in R'Range loop
D (I).Count := 0;
D (I).Repeat := 4;
if I mod 2 = 0 then
Dt := Ada.Real_Time.Milliseconds (40);
else
Dt := Ada.Real_Time.Milliseconds (20);
end if;
M.Set_Timer (D (I)'Unchecked_Access, R (I), Start + Dt);
end loop;
loop
M.Process (Deadline);
exit when Deadline >= Start + Ada.Real_Time.Seconds (10);
Count := Count + 1;
delay until Deadline;
end loop;
-- Depending on the load we can have different values for Count.
Util.Tests.Assert (T, Count <= 8, "Count of Process");
Util.Tests.Assert (T, Count <= 4, "Count of Process");
for I in D'Range loop
Util.Tests.Assert_Equals (T, 4, D (I).Count, "Invalid count for timer at "
& Natural'Image (I) & " " & Natural'Image (Count));
end loop;
end Test_Many_Timers;
end Util.Events.Timers.Tests;
|
Fix the unit tests when run under some heavy load
|
Fix the unit tests when run under some heavy load
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
63b63c4314b35d610c0e9506bdcdcbb456851aa5
|
src/security-controllers-roles.adb
|
src/security-controllers-roles.adb
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Mappers.Record_Mapper;
package body Security.Controllers.Roles is
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
-- ------------------------------
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is
use type Security.Permissions.Principal_Access;
P : constant Security.Permissions.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
for I in Handler.Roles'Range loop
if P.Has_Role (Handler.Roles (I)) then
return True;
end if;
end loop;
end if;
return False;
end Has_Permission;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Permissions.Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Manager;
Config_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Controllers.Roles;
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Mappers.Record_Mapper;
package body Security.Controllers.Roles is
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
-- ------------------------------
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is
use type Security.Principal_Access;
P : constant Security.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
for I in Handler.Roles'Range loop
-- if P.Has_Role (Handler.Roles (I)) then
return True;
-- end if;
end loop;
end if;
return False;
end Has_Permission;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Permissions.Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Manager;
Config_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Controllers.Roles;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
2f2f834019d5a6de56f18637798e9d467fca8b17
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package Wiki.Documents is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT);
type Format_Map is array (Format_Type) of Boolean;
-- ------------------------------
-- Document reader
-- ------------------------------
type Document_Reader is limited interface;
type Document_Reader_Access is access all Document_Reader'Class;
-- Add a section header in the document.
procedure Add_Header (Document : in out Document_Reader;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is abstract;
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Document_Reader) is abstract;
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Document : in out Document_Reader) is abstract;
-- 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 Document_Reader;
Level : in Natural) is abstract;
-- 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 Document_Reader;
Level : in Positive;
Ordered : in Boolean) is abstract;
-- Add an horizontal rule (<hr>).
procedure Add_Horizontal_Rule (Document : in out Document_Reader) is abstract;
-- Add a link.
procedure Add_Link (Document : in out Document_Reader;
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 abstract;
-- Add an image.
procedure Add_Image (Document : in out Document_Reader;
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 abstract;
-- Add a quote.
procedure Add_Quote (Document : in out Document_Reader;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is abstract;
-- Add a text block with the given format.
procedure Add_Text (Document : in out Document_Reader;
Text : in Unbounded_Wide_Wide_String;
Format : in Format_Map) is abstract;
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Document_Reader;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is abstract;
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Document : in out Document_Reader) is abstract;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Attributes;
package Wiki.Documents is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT);
type Format_Map is array (Format_Type) of Boolean;
-- ------------------------------
-- Document reader
-- ------------------------------
type Document_Reader is limited interface;
type Document_Reader_Access is access all Document_Reader'Class;
-- Add a section header in the document.
procedure Add_Header (Document : in out Document_Reader;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is abstract;
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Document_Reader) is abstract;
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Document : in out Document_Reader) is abstract;
-- 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 Document_Reader;
Level : in Natural) is abstract;
-- 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 Document_Reader;
Level : in Positive;
Ordered : in Boolean) is abstract;
-- Add an horizontal rule (<hr>).
procedure Add_Horizontal_Rule (Document : in out Document_Reader) is abstract;
-- Add a link.
procedure Add_Link (Document : in out Document_Reader;
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 abstract;
-- Add an image.
procedure Add_Image (Document : in out Document_Reader;
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 abstract;
-- Add a quote.
procedure Add_Quote (Document : in out Document_Reader;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is abstract;
-- Add a text block with the given format.
procedure Add_Text (Document : in out Document_Reader;
Text : in Unbounded_Wide_Wide_String;
Format : in Format_Map) is abstract;
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Document_Reader;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is abstract;
procedure Start_Element (Document : in out Document_Reader;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is abstract;
procedure End_Element (Document : in out Document_Reader;
Name : in Unbounded_Wide_Wide_String) is abstract;
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Document : in out Document_Reader) is abstract;
end Wiki.Documents;
|
Declare the Start_Element and End_Element procedure
|
Declare the Start_Element and End_Element procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
db775ea531dd342b37e04b66dab6d77ebea7afa0
|
src/gen-artifacts-docs-markdown.ads
|
src/gen-artifacts-docs-markdown.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private package Gen.Artifacts.Docs.Markdown is
-- Format documentation for Google Wiki syntax.
type Document_Formatter is new Gen.Artifacts.Docs.Document_Formatter with record
Need_Newline : Boolean := False;
end record;
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String;
-- Start a new document.
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type);
-- Write a line in the target document formatting the line if necessary.
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type);
-- Finish the document.
overriding
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String);
end Gen.Artifacts.Docs.Markdown;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private package Gen.Artifacts.Docs.Markdown is
-- Format documentation for Google Wiki syntax.
type Document_Formatter is new Gen.Artifacts.Docs.Document_Formatter with record
Need_Newline : Boolean := False;
end record;
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String;
-- Start a new document.
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type);
-- Write a line in the target document formatting the line if necessary.
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type);
-- Finish the document.
overriding
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String);
-- Write a line in the document.
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in String);
end Gen.Artifacts.Docs.Markdown;
|
Declare the Write_Line procedure
|
Declare the Write_Line procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
9a745b44f0da614e688f4c99ec5bd8c002cfe0f9
|
src/gen-model-beans.ads
|
src/gen-model-beans.ads
|
-----------------------------------------------------------------------
-- gen-model-beans -- Ada Bean declarations
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Gen.Model.Tables;
with Gen.Model.Operations;
package Gen.Model.Beans is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Bean Definition
-- ------------------------------
type Bean_Definition is new Tables.Table_Definition with null record;
type Bean_Definition_Access is access all Bean_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Bean_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Bean_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Bean_Definition);
-- Create an attribute with the given name and add it to the bean.
procedure Add_Attribute (Bean : in out Bean_Definition;
Name : in Unbounded_String;
Column : out Gen.Model.Tables.Column_Definition_Access);
-- Create a bean with the given name.
function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access;
end Gen.Model.Beans;
|
-----------------------------------------------------------------------
-- gen-model-beans -- Ada Bean declarations
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Gen.Model.Tables;
package Gen.Model.Beans is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Bean Definition
-- ------------------------------
type Bean_Definition is new Tables.Table_Definition with null record;
type Bean_Definition_Access is access all Bean_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Bean_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Bean_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Bean_Definition);
-- Create an attribute with the given name and add it to the bean.
procedure Add_Attribute (Bean : in out Bean_Definition;
Name : in Unbounded_String;
Column : out Gen.Model.Tables.Column_Definition_Access);
-- Create a bean with the given name.
function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access;
end Gen.Model.Beans;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
ffe6cc2b3ad354afa6fd493e3951ec8796982a52
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- 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.Calendar;
with Ada.Strings.Unbounded;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File);
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
end record;
end AWA.Storages.Services;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File);
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
end record;
end AWA.Storages.Services;
|
Declare the Save procedure with a Storage_File type
|
Declare the Save procedure with a Storage_File type
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
753a765874986a5cd50ac99c5b923740f1b2f1bd
|
matp/src/symbols/mat-symbols-targets.ads
|
matp/src/symbols/mat-symbols-targets.ads
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with 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.Memory.Targets;
package MAT.Symbols.Targets is
type Symbol_Info is record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
end record;
-- 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;
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
-- 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
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
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);
-- 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);
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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.Memory.Targets;
package MAT.Symbols.Targets is
type Symbol_Info is record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
end record;
-- 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;
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
-- 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
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
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);
-- 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);
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;
|
Declare the Demangle procedure to demangle a symbol
|
Declare the Demangle procedure to demangle a symbol
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
a1d9e7b4c9e9c85852dc309bbeda0cc1c05291fa
|
regtests/ado-statements-tests.ads
|
regtests/ado-statements-tests.ads
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Statements.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test creation of several rows in test_table with different column type.
procedure Test_Save (T : in out Test);
-- Test queries using the $entity_type[] cache group.
procedure Test_Entity_Types (T : in out Test);
-- Test executing a SQL query and getting an invalid column.
procedure Test_Invalid_Column (T : in out Test);
end ADO.Statements.Tests;
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Statements.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test creation of several rows in test_table with different column type.
procedure Test_Save (T : in out Test);
-- Test queries using the $entity_type[] cache group.
procedure Test_Entity_Types (T : in out Test);
-- Test executing a SQL query and getting an invalid column.
procedure Test_Invalid_Column (T : in out Test);
-- Test executing a SQL query and getting an invalid value.
procedure Test_Invalid_Type (T : in out Test);
end ADO.Statements.Tests;
|
Declare the Test_Invalid_Type procedure
|
Declare the Test_Invalid_Type procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
5719cb7d7c0a8755a49f73aa7c706c9f6180adcf
|
regtests/util-processes-tests.adb
|
regtests/util-processes-tests.adb
|
-----------------------------------------------------------------------
-- util-processes-tests - Test for processes
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Test_Caller;
with Util.Files;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Streams.Texts;
with Util.Systems.Os;
package body Util.Processes.Tests is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests");
package Caller is new Util.Test_Caller (Test, "Processes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Processes.Is_Running",
Test_No_Process'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status",
Test_Spawn'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)",
Test_Output_Pipe'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)",
Test_Input_Pipe'Access);
if Util.Systems.Os.Directory_Separator /= '\' then
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)",
Test_Output_Redirect'Access);
end if;
Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)",
Test_Multi_Spawn'Access);
end Add_Tests;
-- ------------------------------
-- Tests when the process is not launched
-- ------------------------------
procedure Test_No_Process (T : in out Test) is
P : Process;
begin
T.Assert (not P.Is_Running, "Process should not be running");
T.Assert (P.Get_Pid < 0, "Invalid process id");
end Test_No_Process;
-- ------------------------------
-- Test executing a process
-- ------------------------------
procedure Test_Spawn (T : in out Test) is
P : Process;
begin
-- Launch the test process => exit code 2
P.Spawn ("bin/util_test_process");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status");
-- Launch the test process => exit code 0
P.Spawn ("bin/util_test_process 0 write b c d e f");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Spawn;
-- ------------------------------
-- Test output pipe redirection: read the process standard output
-- ------------------------------
procedure Test_Output_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 write b c d e f test_marker");
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (null, P'Unchecked_Access, 19);
Buffer.Read (Content);
P.Close;
Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Output_Pipe;
-- ------------------------------
-- Test input pipe redirection: write the process standard input
-- At the same time, read the process standard output.
-- ------------------------------
procedure Test_Input_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 read -", READ_WRITE);
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
Print : Util.Streams.Texts.Print_Stream;
begin
-- Write on the process input stream.
Print.Initialize (P'Unchecked_Access);
Print.Write ("Write test on the input pipe");
Print.Close;
-- Read the output.
Buffer.Initialize (null, P'Unchecked_Access, 19);
Buffer.Read (Content);
-- Wait for the process to finish.
P.Close;
Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Input_Pipe;
-- ------------------------------
-- Test launching several processes through pipes in several threads.
-- ------------------------------
procedure Test_Multi_Spawn (T : in out Test) is
Task_Count : constant Natural := 8;
Count_By_Task : constant Natural := 10;
type State_Array is array (1 .. Task_Count) of Boolean;
States : State_Array;
begin
declare
task type Worker is
entry Start (Count : in Natural);
entry Result (Status : out Boolean);
end Worker;
task body Worker is
Cnt : Natural;
State : Boolean := True;
begin
accept Start (Count : in Natural) do
Cnt := Count;
end Start;
declare
type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream;
Pipes : Pipe_Array;
begin
-- Launch the processes.
-- They will print their arguments on stdout, one by one on each line.
-- The expected exit status is the first argument.
for I in 1 .. Cnt loop
Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker");
end loop;
-- Read their output
for I in 1 .. Cnt loop
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (null, Pipes (I)'Unchecked_Access, 19);
Buffer.Read (Content);
Pipes (I).Close;
-- Check status and output.
State := State and Pipes (I).Get_Exit_Status = 0;
State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception raised", E);
State := False;
end;
accept Result (Status : out Boolean) do
Status := State;
end Result;
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
for I in Tasks'Range loop
Tasks (I).Start (Count_By_Task);
end loop;
-- Get the results (do not raise any assertion here because we have to call
-- 'Result' to ensure the thread terminates.
for I in Tasks'Range loop
Tasks (I).Result (States (I));
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
for I in States'Range loop
T.Assert (States (I), "Task " & Natural'Image (I) & " failed");
end loop;
end Test_Multi_Spawn;
-- ------------------------------
-- Test output file redirection.
-- ------------------------------
procedure Test_Output_Redirect (T : in out Test) is
P : Process;
Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt");
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Processes.Set_Output_Stream (P, Path);
Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker");
Util.Processes.Wait (P);
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed");
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*test_marker", Content,
"Invalid content");
Util.Processes.Set_Output_Stream (P, Path, True);
Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text");
Util.Processes.Wait (P);
Content := Ada.Strings.Unbounded.Null_Unbounded_String;
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*appended_text", Content,
"Invalid content");
Util.Tests.Assert_Matches (T, ".*test_marker.*", Content,
"Invalid content");
end Test_Output_Redirect;
end Util.Processes.Tests;
|
-----------------------------------------------------------------------
-- util-processes-tests - Test for processes
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Test_Caller;
with Util.Files;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Streams.Texts;
with Util.Systems.Os;
package body Util.Processes.Tests is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests");
package Caller is new Util.Test_Caller (Test, "Processes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Processes.Is_Running",
Test_No_Process'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status",
Test_Spawn'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)",
Test_Output_Pipe'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)",
Test_Input_Pipe'Access);
pragma Warnings (Off);
if Util.Systems.Os.Directory_Separator /= '\' then
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)",
Test_Output_Redirect'Access);
end if;
pragma Warnings (On);
Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)",
Test_Multi_Spawn'Access);
end Add_Tests;
-- ------------------------------
-- Tests when the process is not launched
-- ------------------------------
procedure Test_No_Process (T : in out Test) is
P : Process;
begin
T.Assert (not P.Is_Running, "Process should not be running");
T.Assert (P.Get_Pid < 0, "Invalid process id");
end Test_No_Process;
-- ------------------------------
-- Test executing a process
-- ------------------------------
procedure Test_Spawn (T : in out Test) is
P : Process;
begin
-- Launch the test process => exit code 2
P.Spawn ("bin/util_test_process");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status");
-- Launch the test process => exit code 0
P.Spawn ("bin/util_test_process 0 write b c d e f");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Spawn;
-- ------------------------------
-- Test output pipe redirection: read the process standard output
-- ------------------------------
procedure Test_Output_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 write b c d e f test_marker");
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (null, P'Unchecked_Access, 19);
Buffer.Read (Content);
P.Close;
Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Output_Pipe;
-- ------------------------------
-- Test input pipe redirection: write the process standard input
-- At the same time, read the process standard output.
-- ------------------------------
procedure Test_Input_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 read -", READ_WRITE);
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
Print : Util.Streams.Texts.Print_Stream;
begin
-- Write on the process input stream.
Print.Initialize (P'Unchecked_Access);
Print.Write ("Write test on the input pipe");
Print.Close;
-- Read the output.
Buffer.Initialize (null, P'Unchecked_Access, 19);
Buffer.Read (Content);
-- Wait for the process to finish.
P.Close;
Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Input_Pipe;
-- ------------------------------
-- Test launching several processes through pipes in several threads.
-- ------------------------------
procedure Test_Multi_Spawn (T : in out Test) is
Task_Count : constant Natural := 8;
Count_By_Task : constant Natural := 10;
type State_Array is array (1 .. Task_Count) of Boolean;
States : State_Array;
begin
declare
task type Worker is
entry Start (Count : in Natural);
entry Result (Status : out Boolean);
end Worker;
task body Worker is
Cnt : Natural;
State : Boolean := True;
begin
accept Start (Count : in Natural) do
Cnt := Count;
end Start;
declare
type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream;
Pipes : Pipe_Array;
begin
-- Launch the processes.
-- They will print their arguments on stdout, one by one on each line.
-- The expected exit status is the first argument.
for I in 1 .. Cnt loop
Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker");
end loop;
-- Read their output
for I in 1 .. Cnt loop
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (null, Pipes (I)'Unchecked_Access, 19);
Buffer.Read (Content);
Pipes (I).Close;
-- Check status and output.
State := State and Pipes (I).Get_Exit_Status = 0;
State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception raised", E);
State := False;
end;
accept Result (Status : out Boolean) do
Status := State;
end Result;
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
for I in Tasks'Range loop
Tasks (I).Start (Count_By_Task);
end loop;
-- Get the results (do not raise any assertion here because we have to call
-- 'Result' to ensure the thread terminates.
for I in Tasks'Range loop
Tasks (I).Result (States (I));
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
for I in States'Range loop
T.Assert (States (I), "Task " & Natural'Image (I) & " failed");
end loop;
end Test_Multi_Spawn;
-- ------------------------------
-- Test output file redirection.
-- ------------------------------
procedure Test_Output_Redirect (T : in out Test) is
P : Process;
Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt");
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Processes.Set_Output_Stream (P, Path);
Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker");
Util.Processes.Wait (P);
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed");
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*test_marker", Content,
"Invalid content");
Util.Processes.Set_Output_Stream (P, Path, True);
Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text");
Util.Processes.Wait (P);
Content := Ada.Strings.Unbounded.Null_Unbounded_String;
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*appended_text", Content,
"Invalid content");
Util.Tests.Assert_Matches (T, ".*test_marker.*", Content,
"Invalid content");
end Test_Output_Redirect;
end Util.Processes.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c503cfa8fb8dd2102a98c3cbc9850647e1417ef6
|
src/asf-applications-main-configs.adb
|
src/asf-applications-main-configs.adb
|
-----------------------------------------------------------------------
-- applications-main-configs -- Configuration support for ASF Applications
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Navigations;
with ASF.Navigations.Mappers;
with ASF.Servlets.Mappers;
with ASF.Beans.Mappers;
package body ASF.Applications.Main.Configs is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs");
-- ------------------------------
-- Save in the application config object the value associated with the given field.
-- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition
-- in the application.
-- ------------------------------
procedure Set_Member (N : in out Application_Config;
Field : in Application_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when TAG_MESSAGE_VAR =>
N.Name := Value;
when TAG_MESSAGE_BUNDLE =>
declare
Bundle : constant String := Util.Beans.Objects.To_String (Value);
Name : constant String := Util.Beans.Objects.To_String (N.Name);
begin
if Name'Length = 0 then
N.App.Register (Name => Bundle & "Msg",
Bundle => Bundle);
else
N.App.Register (Name => Name,
Bundle => Bundle);
end if;
end;
end case;
end Set_Member;
AMapper : aliased Application_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the managed bean definitions.
-- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings
-- to read the servlet, managed beans and navigation rules.
-- ------------------------------
package body Reader_Config is
-- Get the navigation handler for the Navigation_Config instantiation
-- GNAT crashes if the call is made in the instantation part.
Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler;
package Bean_Config is
new ASF.Beans.Mappers.Reader_Config (Reader, App.Factory'Access,
Context.all'Access);
package Navigation_Config is
new ASF.Navigations.Mappers.Reader_Config (Reader, Nav, Context.all'Access);
package Servlet_Config is
new ASF.Servlets.Mappers.Reader_Config (Reader, App.all'Access,
Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Navigation_Config);
pragma Warnings (Off, Servlet_Config);
Config : aliased Application_Config;
begin
-- Install the property context that gives access
-- to the application configuration properties
Prop_Context.Set_Properties (App.Conf);
Context.Set_Resolver (Prop_Context'Unchecked_Access);
Reader.Add_Mapping ("faces-config", AMapper'Access);
Reader.Add_Mapping ("module", AMapper'Access);
Reader.Add_Mapping ("web-app", AMapper'Access);
Config.App := App;
Application_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
-- ------------------------------
-- Read the configuration file associated with the application. This includes:
-- <ul>
-- <li>The servlet and filter mappings</li>
-- <li>The managed bean definitions</li>
-- <li>The navigation rules</li>
-- </ul>
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String) is
Reader : Util.Serialize.IO.XML.Parser;
Context : aliased EL.Contexts.Default.Default_Context;
-- Setup the <b>Reader</b> to parse and build the configuration for managed beans,
-- navigation rules, servlet rules. Each package instantiation creates a local variable
-- used while parsing the XML file.
package Config is
new Reader_Config (Reader, App'Unchecked_Access, Context'Unchecked_Access);
pragma Warnings (Off, Config);
begin
Log.Info ("Reading module configuration file {0}", File);
-- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end Read_Configuration;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access,
Default => PARAM_VALUE'Access);
-- ------------------------------
-- Returns the configuration parameter.
-- ------------------------------
function P return Config_Param is
begin
return Param;
end P;
end Parameter;
begin
AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR);
AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE);
end ASF.Applications.Main.Configs;
|
-----------------------------------------------------------------------
-- applications-main-configs -- Configuration support for ASF Applications
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Navigations;
with ASF.Navigations.Mappers;
with ASF.Servlets.Mappers;
with ASF.Beans.Mappers;
package body ASF.Applications.Main.Configs is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs");
-- ------------------------------
-- Save in the application config object the value associated with the given field.
-- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition
-- in the application.
-- ------------------------------
procedure Set_Member (N : in out Application_Config;
Field : in Application_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when TAG_MESSAGE_VAR =>
N.Name := Value;
when TAG_MESSAGE_BUNDLE =>
declare
Bundle : constant String := Util.Beans.Objects.To_String (Value);
begin
if Util.Beans.Objects.Is_Null (N.Name) then
N.App.Register (Name => Bundle & "Msg",
Bundle => Bundle);
else
N.App.Register (Name => Util.Beans.Objects.To_String (N.Name),
Bundle => Bundle);
end if;
N.Name := Util.Beans.Objects.Null_Object;
end;
end case;
end Set_Member;
AMapper : aliased Application_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the managed bean definitions.
-- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings
-- to read the servlet, managed beans and navigation rules.
-- ------------------------------
package body Reader_Config is
-- Get the navigation handler for the Navigation_Config instantiation
-- GNAT crashes if the call is made in the instantation part.
Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler;
package Bean_Config is
new ASF.Beans.Mappers.Reader_Config (Reader, App.Factory'Access,
Context.all'Access);
package Navigation_Config is
new ASF.Navigations.Mappers.Reader_Config (Reader, Nav, Context.all'Access);
package Servlet_Config is
new ASF.Servlets.Mappers.Reader_Config (Reader, App.all'Access,
Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Navigation_Config);
pragma Warnings (Off, Servlet_Config);
Config : aliased Application_Config;
begin
-- Install the property context that gives access
-- to the application configuration properties
Prop_Context.Set_Properties (App.Conf);
Context.Set_Resolver (Prop_Context'Unchecked_Access);
Reader.Add_Mapping ("faces-config", AMapper'Access);
Reader.Add_Mapping ("module", AMapper'Access);
Reader.Add_Mapping ("web-app", AMapper'Access);
Config.App := App;
Application_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
-- ------------------------------
-- Read the configuration file associated with the application. This includes:
-- <ul>
-- <li>The servlet and filter mappings</li>
-- <li>The managed bean definitions</li>
-- <li>The navigation rules</li>
-- </ul>
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String) is
Reader : Util.Serialize.IO.XML.Parser;
Context : aliased EL.Contexts.Default.Default_Context;
-- Setup the <b>Reader</b> to parse and build the configuration for managed beans,
-- navigation rules, servlet rules. Each package instantiation creates a local variable
-- used while parsing the XML file.
package Config is
new Reader_Config (Reader, App'Unchecked_Access, Context'Unchecked_Access);
pragma Warnings (Off, Config);
begin
Log.Info ("Reading module configuration file {0}", File);
-- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end Read_Configuration;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access,
Default => PARAM_VALUE'Access);
-- ------------------------------
-- Returns the configuration parameter.
-- ------------------------------
function P return Config_Param is
begin
return Param;
end P;
end Parameter;
begin
AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR);
AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE);
end ASF.Applications.Main.Configs;
|
Fix reading configuration and setup of application bundles
|
Fix reading configuration and setup of application bundles
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
a2a0d0daf446dcb2a410270f5ed6974b28fbe6aa
|
src/natools-web-string_tables.adb
|
src/natools-web-string_tables.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Containers.Doubly_Linked_Lists;
package body Natools.Web.String_Tables is
package Row_Lists is new Ada.Containers.Doubly_Linked_Lists
(Containers.Atom_Array_Refs.Immutable_Reference,
Containers.Atom_Array_Refs."=");
------------------
-- Constructors --
------------------
not overriding function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return String_Table is
begin
return String_Table'(Ref => Create (Expression));
end Create;
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Table_References.Immutable_Reference
is
List : Row_Lists.List;
Event : S_Expressions.Events.Event := Expression.Current_Event;
Lock : S_Expressions.Lockable.Lock_State;
begin
Read_Expression :
loop
case Event is
when S_Expressions.Events.Close_List
| S_Expressions.Events.End_Of_Input
| S_Expressions.Events.Error
=>
exit Read_Expression;
when S_Expressions.Events.Add_Atom => null;
when S_Expressions.Events.Open_List =>
Expression.Lock (Lock);
begin
Expression.Next (Event);
if Event in S_Expressions.Events.Add_Atom
| S_Expressions.Events.Open_List
then
List.Append (Containers.Create (Expression));
end if;
Expression.Unlock (Lock);
exception
when others =>
Expression.Unlock (Lock, False);
raise;
end;
end case;
Expression.Next (Event);
end loop Read_Expression;
if Row_Lists.Is_Empty (List) then
return Table_References.Null_Immutable_Reference;
end if;
Build_Table :
declare
Data : constant Table_References.Data_Access
:= new Table (1 .. S_Expressions.Count (Row_Lists.Length (List)));
Ref : constant Table_References.Immutable_Reference
:= Table_References.Create (Data);
Cursor : Row_Lists.Cursor := Row_Lists.First (List);
begin
for I in Data.all'Range loop
Data (I) := Row_Lists.Element (Cursor);
Row_Lists.Next (Cursor);
end loop;
pragma Assert (not Row_Lists.Has_Element (Cursor));
return Ref;
end Build_Table;
end Create;
---------------
-- Renderers --
---------------
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in String_Table;
Expression : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Exchange);
pragma Unreferenced (Object);
pragma Unreferenced (Expression);
begin
raise Program_Error with "Not implemented yet";
end Render;
end Natools.Web.String_Tables;
|
------------------------------------------------------------------------------
-- Copyright (c) 2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Containers.Doubly_Linked_Lists;
with Natools.S_Expressions.Interpreter_Loop;
package body Natools.Web.String_Tables is
package Row_Lists is new Ada.Containers.Doubly_Linked_Lists
(Containers.Atom_Array_Refs.Immutable_Reference,
Containers.Atom_Array_Refs."=");
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Containers.Atom_Array_Refs.Immutable_Reference;
Data : in S_Expressions.Atom);
procedure Execute
(Exchange : in out Sites.Exchange;
Row : in Containers.Atom_Array_Refs.Immutable_Reference;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render_Row is new S_Expressions.Interpreter_Loop
(Sites.Exchange, Containers.Atom_Array_Refs.Immutable_Reference,
Execute, Append);
------------------------
-- Renderer Fragments --
------------------------
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Containers.Atom_Array_Refs.Immutable_Reference;
Data : in S_Expressions.Atom)
is
pragma Unreferenced (Context);
begin
Exchange.Append (Data);
end Append;
procedure Execute
(Exchange : in out Sites.Exchange;
Row : in Containers.Atom_Array_Refs.Immutable_Reference;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Arguments);
Column : S_Expressions.Offset;
S_Name : constant String := S_Expressions.To_String (Name);
begin
To_Column :
begin
if S_Name'Length > 6
and then S_Name (S_Name'First .. S_Name'First + 5) = "value-"
then
Column := S_Expressions.Offset'Value
(S_Name (S_Name'First + 6 .. S_Name'Last));
else
Column := S_Expressions.Offset'Value (S_Name);
end if;
exception
when Constraint_Error =>
Log (Severities.Error, "Invalid row command """ & S_Name & '"');
return;
end To_Column;
declare
Atoms : constant Containers.Atom_Array_Refs.Accessor := Row.Query;
begin
if Column in Atoms.Data'Range then
Exchange.Append (Atoms (Column).Query);
else
Log
(Severities.Error,
"Column"
& S_Expressions.Offset'Image (Column)
& " not in row range"
& S_Expressions.Offset'Image (Atoms.Data'First)
& " .."
& S_Expressions.Offset'Image (Atoms.Data'Last));
end if;
end;
end Execute;
------------------
-- Constructors --
------------------
not overriding function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return String_Table is
begin
return String_Table'(Ref => Create (Expression));
end Create;
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Table_References.Immutable_Reference
is
List : Row_Lists.List;
Event : S_Expressions.Events.Event := Expression.Current_Event;
Lock : S_Expressions.Lockable.Lock_State;
begin
Read_Expression :
loop
case Event is
when S_Expressions.Events.Close_List
| S_Expressions.Events.End_Of_Input
| S_Expressions.Events.Error
=>
exit Read_Expression;
when S_Expressions.Events.Add_Atom => null;
when S_Expressions.Events.Open_List =>
Expression.Lock (Lock);
begin
Expression.Next (Event);
if Event in S_Expressions.Events.Add_Atom
| S_Expressions.Events.Open_List
then
List.Append (Containers.Create (Expression));
end if;
Expression.Unlock (Lock);
exception
when others =>
Expression.Unlock (Lock, False);
raise;
end;
end case;
Expression.Next (Event);
end loop Read_Expression;
if Row_Lists.Is_Empty (List) then
return Table_References.Null_Immutable_Reference;
end if;
Build_Table :
declare
Data : constant Table_References.Data_Access
:= new Table (1 .. S_Expressions.Count (Row_Lists.Length (List)));
Ref : constant Table_References.Immutable_Reference
:= Table_References.Create (Data);
Cursor : Row_Lists.Cursor := Row_Lists.First (List);
begin
for I in Data.all'Range loop
Data (I) := Row_Lists.Element (Cursor);
Row_Lists.Next (Cursor);
end loop;
pragma Assert (not Row_Lists.Has_Element (Cursor));
return Ref;
end Build_Table;
end Create;
---------------
-- Renderers --
---------------
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in String_Table;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
for Row of Object.Ref.Query.Data.all loop
Render_Row (Expression, Exchange, Row);
end loop;
end Render;
end Natools.Web.String_Tables;
|
implement row rendering
|
string_tables: implement row rendering
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
46a8e1365a5b9150f41f6b29f908f8f5a776ab11
|
src/gl/interface/gl-objects-queries.ads
|
src/gl/interface/gl-objects-queries.ads
|
--------------------------------------------------------------------------------
-- Copyright (c) 2016 onox <[email protected]>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
with GL.Low_Level;
package GL.Objects.Queries is
pragma Preelaborate;
type Query_Type is (Time_Elapsed,
Samples_Passed, Any_Samples_Passed,
Primitives_Generated,
Transform_Feedback_Primitives_Written,
Any_Samples_Passed_Conservative,
Timestamp);
-- Has to be defined here because of the subtype declaration below
for Query_Type use (Time_Elapsed => 16#88BF#,
Samples_Passed => 16#8914#,
Any_Samples_Passed => 16#8C2F#,
Primitives_Generated => 16#8C87#,
Transform_Feedback_Primitives_Written => 16#8C88#,
Any_Samples_Passed_Conservative => 16#8D6A#,
Timestamp => 16#8E28#);
for Query_Type'Size use Low_Level.Enum'Size;
subtype Async_Query_Type is Query_Type range Time_Elapsed .. Any_Samples_Passed_Conservative;
subtype Timestamp_Query_Type is Query_Type range Timestamp .. Timestamp;
subtype Primitive_Query_Type is Query_Type
with Static_Predicate =>
Primitive_Query_Type in Primitives_Generated | Transform_Feedback_Primitives_Written;
subtype Occlusion_Query_Type is Query_Type
with Static_Predicate =>
Occlusion_Query_Type in Samples_Passed | Any_Samples_Passed | Any_Samples_Passed_Conservative;
subtype Time_Query_Type is Query_Type
with Static_Predicate => Time_Query_Type = Time_Elapsed;
type Query_Mode is (Wait, No_Wait, By_Region_Wait, By_Region_No_Wait);
type Query_Param is (Result, Result_Available, Result_No_Wait);
type Target_Param is (Counter_Bits, Current_Query);
type Query is new GL_Object with private;
overriding
procedure Initialize_Id (Object : in out Query);
overriding
procedure Delete_Id (Object : in out Query);
type Active_Query is limited new Ada.Finalization.Limited_Controlled with private;
type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with private;
function Begin_Primitive_Query (Object : in out Query;
Target : in Primitive_Query_Type;
Index : in Natural := 0)
return Active_Query'Class;
-- Start a primitive query. The value returned is of a controlled
-- type, meaning you must assign it to some local variable, so that
-- the query will be automatically ended when the variable goes out
-- of scope.
--
-- Primitive queries support multiple query operations; one for each
-- index. The index represents the vertex output stream used in a
-- Geometry Shader. If the target type is
-- Transform_Feedback_Primitives_Written, then the query should be
-- issued while within a transform feedback scope.
function Begin_Occlusion_Query (Object : in out Query;
Target : in Occlusion_Query_Type)
return Active_Query'Class;
-- Start an occlusion query. The value returned is of a controlled
-- type, meaning you must assign it to some local variable, so that
-- the query will be automatically ended when the variable goes out
-- of scope.
function Begin_Timer_Query (Object : in out Query;
Target : in Time_Query_Type)
return Active_Query'Class;
-- Start a timer query. The value returned is of a controlled
-- type, meaning you must assign it to some local variable, so that
-- the query will be automatically ended when the variable goes out
-- of scope.
--
-- This function is used only for queries of type Time_Elapsed.
-- Queries of type Timestamp are not used within a scope. For such
-- a query you can record the time into the query object by calling
-- Record_Current_Time.
function Begin_Conditional_Render (Object : in out Query;
Mode : in Query_Mode)
return Conditional_Render'Class;
-- Start a conditional rendering. The value returned is of a controlled
-- type, meaning you must assign it to some local variable, so that
-- the rendering will be automatically ended when the variable goes
-- out of scope.
function Result_Available (Object : in out Query) return Boolean;
-- Return true if a result is available, false otherwise. This function
-- can be used to avoid calling Result (and thereby stalling the CPU)
-- when the result is not yet available.
function Result_If_Available (Object : in out Query; Default_Value : Boolean)
return Boolean;
-- Return the result if available, otherwise return the default value
function Result_If_Available (Object : in out Query; Default_Value : Natural)
return Natural;
-- Return the result if available, otherwise return the default value
function Result (Object : in out Query) return Boolean;
-- Return the result. If the result is not yet available, then the
-- CPU will stall until the result becomes available. This means
-- that if you do not call Result_Available, then this function call
-- will make the query synchronous.
function Result (Object : in out Query) return Natural;
-- Return the result. If the result is not yet available, then the
-- CPU will stall until the result becomes available. This means
-- that if you do not call Result_Available, then this function call
-- will make the query synchronous.
function Result_Bits (Target : in Query_Type) return Natural;
procedure Record_Current_Time (Object : in out Query);
-- Record the time when the GPU has completed all previous commands
-- in a query object. The result must be retrieved asynchronously using
-- one of the Result functions.
function Get_Current_Time return Long;
-- Return the time when the GPU has received (but not necessarily
-- completed) all previous commands. Calling this function stalls the CPU.
private
for Query_Mode use (Wait => 16#8E13#,
No_Wait => 16#8E14#,
By_Region_Wait => 16#8E15#,
By_Region_No_Wait => 16#8E16#);
for Query_Mode'Size use Low_Level.Enum'Size;
for Target_Param use (Counter_Bits => 16#8864#,
Current_Query => 16#8865#);
for Target_Param'Size use Low_Level.Enum'Size;
for Query_Param use (Result => 16#8866#,
Result_Available => 16#8867#,
Result_No_Wait => 16#9194#);
for Query_Param'Size use Low_Level.Enum'Size;
type Query is new GL_Object with null record;
type Active_Query is limited new Ada.Finalization.Limited_Controlled with record
Target : Query_Type;
Index : Natural;
Finalized : Boolean := True;
end record;
overriding
procedure Finalize (Object : in out Active_Query);
type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with record
Finalized : Boolean := True;
end record;
overriding
procedure Finalize (Object : in out Conditional_Render);
end GL.Objects.Queries;
|
--------------------------------------------------------------------------------
-- Copyright (c) 2016 onox <[email protected]>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
with GL.Low_Level;
package GL.Objects.Queries is
pragma Preelaborate;
type Query_Type is (Time_Elapsed,
Samples_Passed, Any_Samples_Passed,
Primitives_Generated,
Transform_Feedback_Primitives_Written,
Any_Samples_Passed_Conservative,
Timestamp);
-- Has to be defined here because of the subtype declaration below
for Query_Type use (Time_Elapsed => 16#88BF#,
Samples_Passed => 16#8914#,
Any_Samples_Passed => 16#8C2F#,
Primitives_Generated => 16#8C87#,
Transform_Feedback_Primitives_Written => 16#8C88#,
Any_Samples_Passed_Conservative => 16#8D6A#,
Timestamp => 16#8E28#);
for Query_Type'Size use Low_Level.Enum'Size;
subtype Async_Query_Type is Query_Type range Time_Elapsed .. Any_Samples_Passed_Conservative;
subtype Timestamp_Query_Type is Query_Type range Timestamp .. Timestamp;
subtype Primitive_Query_Type is Query_Type
with Static_Predicate =>
Primitive_Query_Type in Primitives_Generated | Transform_Feedback_Primitives_Written;
subtype Occlusion_Query_Type is Query_Type
with Static_Predicate =>
Occlusion_Query_Type in Samples_Passed | Any_Samples_Passed | Any_Samples_Passed_Conservative;
subtype Time_Query_Type is Query_Type
with Static_Predicate => Time_Query_Type = Time_Elapsed;
type Query_Mode is (Wait, No_Wait, By_Region_Wait, By_Region_No_Wait,
Wait_Inverted, No_Wait_Inverted, By_Region_Wait_Inverted,
By_Region_No_Wait_Inverted);
type Query_Param is (Result, Result_Available, Result_No_Wait);
type Target_Param is (Counter_Bits, Current_Query);
type Query is new GL_Object with private;
overriding
procedure Initialize_Id (Object : in out Query);
overriding
procedure Delete_Id (Object : in out Query);
type Active_Query is limited new Ada.Finalization.Limited_Controlled with private;
type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with private;
function Begin_Primitive_Query (Object : in out Query;
Target : in Primitive_Query_Type;
Index : in Natural := 0)
return Active_Query'Class;
-- Start a primitive query. The value returned is of a controlled
-- type, meaning you must assign it to some local variable, so that
-- the query will be automatically ended when the variable goes out
-- of scope.
--
-- Primitive queries support multiple query operations; one for each
-- index. The index represents the vertex output stream used in a
-- Geometry Shader. If the target type is
-- Transform_Feedback_Primitives_Written, then the query should be
-- issued while within a transform feedback scope.
function Begin_Occlusion_Query (Object : in out Query;
Target : in Occlusion_Query_Type)
return Active_Query'Class;
-- Start an occlusion query. The value returned is of a controlled
-- type, meaning you must assign it to some local variable, so that
-- the query will be automatically ended when the variable goes out
-- of scope.
function Begin_Timer_Query (Object : in out Query;
Target : in Time_Query_Type)
return Active_Query'Class;
-- Start a timer query. The value returned is of a controlled
-- type, meaning you must assign it to some local variable, so that
-- the query will be automatically ended when the variable goes out
-- of scope.
--
-- This function is used only for queries of type Time_Elapsed.
-- Queries of type Timestamp are not used within a scope. For such
-- a query you can record the time into the query object by calling
-- Record_Current_Time.
function Begin_Conditional_Render (Object : in out Query;
Mode : in Query_Mode)
return Conditional_Render'Class;
-- Start a conditional rendering. The value returned is of a controlled
-- type, meaning you must assign it to some local variable, so that
-- the rendering will be automatically ended when the variable goes
-- out of scope.
--
-- If Mode is (By_Region_)Wait, then OpenGL will wait until the result
-- becomes available and uses the value of the result to determine
-- whether to execute or discard rendering commands.
--
-- If Mode is *_Inverted, then the condition is inverted, meaning it
-- will execute rendering commands if the query result is zero/false.
--
-- If Mode is (By_Region_)No_Wait(_Inverted), then OpenGL may choose
-- to execute rendering commands while the result of the query is not
-- available.
function Result_Available (Object : in out Query) return Boolean;
-- Return true if a result is available, false otherwise. This function
-- can be used to avoid calling Result (and thereby stalling the CPU)
-- when the result is not yet available.
function Result_If_Available (Object : in out Query; Default_Value : Boolean)
return Boolean;
-- Return the result if available, otherwise return the default value
function Result_If_Available (Object : in out Query; Default_Value : Natural)
return Natural;
-- Return the result if available, otherwise return the default value
function Result (Object : in out Query) return Boolean;
-- Return the result. If the result is not yet available, then the
-- CPU will stall until the result becomes available. This means
-- that if you do not call Result_Available, then this function call
-- will make the query synchronous.
function Result (Object : in out Query) return Natural;
-- Return the result. If the result is not yet available, then the
-- CPU will stall until the result becomes available. This means
-- that if you do not call Result_Available, then this function call
-- will make the query synchronous.
function Result_Bits (Target : in Query_Type) return Natural;
procedure Record_Current_Time (Object : in out Query);
-- Record the time when the GPU has completed all previous commands
-- in a query object. The result must be retrieved asynchronously using
-- one of the Result functions.
function Get_Current_Time return Long;
-- Return the time when the GPU has received (but not necessarily
-- completed) all previous commands. Calling this function stalls the CPU.
private
for Query_Mode use (Wait => 16#8E13#,
No_Wait => 16#8E14#,
By_Region_Wait => 16#8E15#,
By_Region_No_Wait => 16#8E16#,
Wait_Inverted => 16#8E17#,
No_Wait_Inverted => 16#8E18#,
By_Region_Wait_Inverted => 16#8E19#,
By_Region_No_Wait_Inverted => 16#8E1A#);
for Query_Mode'Size use Low_Level.Enum'Size;
for Target_Param use (Counter_Bits => 16#8864#,
Current_Query => 16#8865#);
for Target_Param'Size use Low_Level.Enum'Size;
for Query_Param use (Result => 16#8866#,
Result_Available => 16#8867#,
Result_No_Wait => 16#9194#);
for Query_Param'Size use Low_Level.Enum'Size;
type Query is new GL_Object with null record;
type Active_Query is limited new Ada.Finalization.Limited_Controlled with record
Target : Query_Type;
Index : Natural;
Finalized : Boolean := True;
end record;
overriding
procedure Finalize (Object : in out Active_Query);
type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with record
Finalized : Boolean := True;
end record;
overriding
procedure Finalize (Object : in out Conditional_Render);
end GL.Objects.Queries;
|
Support inverted query condition for conditional rendering
|
gl: Support inverted query condition for conditional rendering
* Extension ARB_conditional_render_inverted (OpenGL 4.5)
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
3ca5804313cbb26aeec800a91ceb42c117cf0ac0
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- It was moved to a separate project so that it can easyly be used with AWS.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies (yellow). The framework defines a simple role based security policy and an URL
-- security policy intended to provide security in web applications. The security policy manager
-- reads some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth 2.0 OpenID Connect.
--
-- [images/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending
-- on the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
--
-- == Principal ==
-- A principal is created by using either the [Security_Auth OpenID],
-- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces
-- an object that must implement the <tt>Principal</tt> interface. For example:
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth);
--
-- or
--
-- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token
--
-- The principal is then stored in a security context.
--
-- @include security-contexts.ads
--
-- [Security_Policies Security Policies]
-- [Security_Auth OpenID]
-- [Security_OAuth OAuth]
--
package Security is
pragma Preelaborate;
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- = Security =
-- The `Security` package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- It was moved to a separate project so that it can easyly be used with AWS.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- * **Policy and policy manager**:
-- The `Policy` defines and implements the set of security rules that specify how to
-- protect the system or resources. The `Policy_Manager` maintains the security policies.
--
-- * **Principal**:
-- The `Principal` 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 `Permission` represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The `Security_Context` holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies (yellow). The framework defines a simple role based security policy and an URL
-- security policy intended to provide security in web applications. The security policy manager
-- reads some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a `Principal`
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth 2.0 OpenID Connect.
--
-- [images/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- `Principal` instance (blue). Additional security policy context can be added depending
-- on the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
--
-- == Principal ==
-- A principal is created by using either the [Security_Auth OpenID],
-- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces
-- an object that must implement the `Principal` interface. For example:
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth);
--
-- or
--
-- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token
--
-- The principal is then stored in a security context.
--
-- @include security-contexts.ads
--
-- [Security_Policies Security Policies]
-- [Security_Auth OpenID]
-- [Security_OAuth OAuth]
--
package Security is
pragma Preelaborate;
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
c4dd4cec4f57f07688023541465dabae811164bc
|
src/wiki-attributes.ads
|
src/wiki-attributes.ads
|
-----------------------------------------------------------------------
-- wiki-attributes -- Wiki document attributes
-- 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;
private with Ada.Containers.Vectors;
private with Ada.Finalization;
-- == Attributes ==
-- The <tt>Attributes</tt> package defines a simple management of attributes for
-- the wiki document parser. Attribute lists are described by the <tt>Attribute_List_Type</tt>
-- with some operations to append or query for an attribute.
package Wiki.Attributes is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Cursor is private;
-- Get the attribute name.
function Get_Name (Position : in Cursor) return String;
-- Get the attribute value.
function Get_Value (Position : in Cursor) return String;
-- Get the attribute wide value.
function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String;
-- Get the attribute wide value.
function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String;
-- Returns True if the cursor has a valid attribute.
function Has_Element (Position : in Cursor) return Boolean;
-- Move the cursor to the next attribute.
procedure Next (Position : in out Cursor);
-- A list of attributes.
type Attribute_List_Type is limited private;
-- Find the attribute with the given name.
function Find (List : in Attribute_List_Type;
Name : in String) return Cursor;
-- Find the attribute with the given name and return its value.
function Get_Attribute (List : in Attribute_List_Type;
Name : in String) return Unbounded_Wide_Wide_String;
-- Append the attribute to the attribute list.
procedure Append (List : in out Attribute_List_Type;
Name : in Wide_Wide_String;
Value : in Wide_Wide_String);
-- Append the attribute to the attribute list.
procedure Append (List : in out Attribute_List_Type;
Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Get the cursor to get access to the first attribute.
function First (List : in Attribute_List_Type) return Cursor;
-- Get the number of attributes in the list.
function Length (List : in Attribute_List_Type) return Natural;
-- Clear the list and remove all existing attributes.
procedure Clear (List : in out Attribute_List_Type);
private
type Attribute (Name_Length, Value_Length : Natural) is limited record
Name : String (1 .. Name_Length);
Value : Wide_Wide_String (1 .. Value_Length);
end record;
type Attribute_Access is access all Attribute;
package Attribute_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Attribute_Access);
subtype Attribute_Vector is Attribute_Vectors.Vector;
type Cursor is record
Pos : Attribute_Vectors.Cursor;
end record;
type Attribute_List_Type is limited new Ada.Finalization.Limited_Controlled with record
List : Attribute_Vector;
end record;
-- Finalize the attribute list releasing any storage.
overriding
procedure Finalize (List : in out Attribute_List_Type);
end Wiki.Attributes;
|
-----------------------------------------------------------------------
-- wiki-attributes -- Wiki document attributes
-- 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;
private with Ada.Containers.Vectors;
private with Ada.Finalization;
-- == Attributes ==
-- The <tt>Attributes</tt> package defines a simple management of attributes for
-- the wiki document parser. Attribute lists are described by the <tt>Attribute_List_Type</tt>
-- with some operations to append or query for an attribute.
package Wiki.Attributes is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Cursor is private;
-- Get the attribute name.
function Get_Name (Position : in Cursor) return String;
-- Get the attribute value.
function Get_Value (Position : in Cursor) return String;
-- Get the attribute wide value.
function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String;
-- Get the attribute wide value.
function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String;
-- Returns True if the cursor has a valid attribute.
function Has_Element (Position : in Cursor) return Boolean;
-- Move the cursor to the next attribute.
procedure Next (Position : in out Cursor);
-- A list of attributes.
type Attribute_List_Type is private;
-- Find the attribute with the given name.
function Find (List : in Attribute_List_Type;
Name : in String) return Cursor;
-- Find the attribute with the given name and return its value.
function Get_Attribute (List : in Attribute_List_Type;
Name : in String) return Unbounded_Wide_Wide_String;
-- Append the attribute to the attribute list.
procedure Append (List : in out Attribute_List_Type;
Name : in Wide_Wide_String;
Value : in Wide_Wide_String);
-- Append the attribute to the attribute list.
procedure Append (List : in out Attribute_List_Type;
Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Get the cursor to get access to the first attribute.
function First (List : in Attribute_List_Type) return Cursor;
-- Get the number of attributes in the list.
function Length (List : in Attribute_List_Type) return Natural;
-- Clear the list and remove all existing attributes.
procedure Clear (List : in out Attribute_List_Type);
-- Iterate over the list attributes and call the <tt>Process</tt> procedure.
procedure Iterate (List : in Attribute_List_Type;
Process : not null access procedure (Name : in String;
Value : in Wide_Wide_String));
private
type Attribute (Name_Length, Value_Length : Natural) is limited record
Name : String (1 .. Name_Length);
Value : Wide_Wide_String (1 .. Value_Length);
end record;
type Attribute_Access is access all Attribute;
package Attribute_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Attribute_Access);
subtype Attribute_Vector is Attribute_Vectors.Vector;
type Cursor is record
Pos : Attribute_Vectors.Cursor;
end record;
type Attribute_List_Type is new Ada.Finalization.Controlled with record
List : Attribute_Vector;
end record;
-- Finalize the attribute list releasing any storage.
overriding
procedure Finalize (List : in out Attribute_List_Type);
end Wiki.Attributes;
|
Declare the Iterate procedure to iterate over all attributes
|
Declare the Iterate procedure to iterate over all attributes
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
bc877e985f5ba55cf58b25670dc9e99956880ba8
|
testcases/stored_procs/stored_procs.adb
|
testcases/stored_procs/stored_procs.adb
|
with AdaBase;
with Connect;
with Ada.Text_IO;
with AdaBase.Results.Sets;
procedure Stored_Procs is
package CON renames Connect;
package TIO renames Ada.Text_IO;
package ARS renames AdaBase.Results.Sets;
stmt_acc : CON.Stmt_Type_access;
procedure dump_result;
procedure dump_result
is
function pad (S : String) return String;
function pad (S : String) return String
is
field : String (1 .. 15) := (others => ' ');
len : Natural := S'Length;
begin
field (1 .. len) := S;
return field;
end pad;
row : ARS.Datarow;
numcols : constant Natural := stmt_acc.column_count;
begin
for c in Natural range 1 .. numcols loop
TIO.Put (pad (stmt_acc.column_name (c)));
end loop;
TIO.Put_Line ("");
for c in Natural range 1 .. numcols loop
TIO.Put ("============== ");
end loop;
TIO.Put_Line ("");
loop
row := stmt_acc.fetch_next;
exit when row.data_exhausted;
for c in Natural range 1 .. numcols loop
TIO.Put (pad (row.column (c).as_string));
end loop;
TIO.Put_Line ("");
end loop;
TIO.Put_Line ("");
end dump_result;
sql : constant String := "CALL multiple_rowsets";
set_fetched : Boolean;
set_present : Boolean;
begin
CON.connect_database;
declare
stmt : aliased CON.Stmt_Type :=
CON.DR.call_stored_procedure ("multiple_rowsets", "");
begin
set_fetched := stmt.successful;
stmt_acc := stmt'Unchecked_Access;
loop
if set_fetched then
dump_result;
end if;
stmt.fetch_next_set (set_present, set_fetched);
exit when not set_present;
end loop;
end;
CON.DR.disconnect;
end Stored_Procs;
|
with AdaBase;
with Connect;
with Ada.Text_IO;
with AdaBase.Results.Sets;
procedure Stored_Procs is
package CON renames Connect;
package TIO renames Ada.Text_IO;
package ARS renames AdaBase.Results.Sets;
stmt_acc : CON.Stmt_Type_access;
procedure dump_result;
procedure dump_result
is
function pad (S : String) return String;
function pad (S : String) return String
is
field : String (1 .. 15) := (others => ' ');
len : Natural := S'Length;
begin
field (1 .. len) := S;
return field;
end pad;
row : ARS.Datarow;
numcols : constant Natural := stmt_acc.column_count;
begin
for c in Natural range 1 .. numcols loop
TIO.Put (pad (stmt_acc.column_name (c)));
end loop;
TIO.Put_Line ("");
for c in Natural range 1 .. numcols loop
TIO.Put ("============== ");
end loop;
TIO.Put_Line ("");
loop
row := stmt_acc.fetch_next;
exit when row.data_exhausted;
for c in Natural range 1 .. numcols loop
TIO.Put (pad (row.column (c).as_string));
end loop;
TIO.Put_Line ("");
end loop;
TIO.Put_Line ("");
end dump_result;
set_fetched : Boolean;
set_present : Boolean;
begin
CON.connect_database;
declare
stmt : aliased CON.Stmt_Type :=
CON.DR.call_stored_procedure ("multiple_rowsets", "");
begin
set_fetched := stmt.successful;
stmt_acc := stmt'Unchecked_Access;
loop
if set_fetched then
dump_result;
end if;
stmt.fetch_next_set (set_present, set_fetched);
exit when not set_present;
end loop;
end;
CON.DR.disconnect;
end Stored_Procs;
|
remove obsolete line from stored procs test case
|
remove obsolete line from stored procs test case
|
Ada
|
isc
|
jrmarino/AdaBase
|
55901958995599038cf8c16aa9c5303a241788da
|
matp/src/mat-targets.ads
|
matp/src/mat-targets.ads
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Ada.Finalization;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Events.Targets;
with MAT.Events.Probes;
with MAT.Readers;
with MAT.Readers.Streams;
with MAT.Readers.Streams.Sockets;
with MAT.Consoles;
package MAT.Targets is
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
-- Enable and enter in the interactive TTY console mode.
Interactive : Boolean := True;
-- Try to load the symbol file automatically when a new process is received.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Print the events as they are received.
Print_Events : Boolean := False;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Path : Ada.Strings.Unbounded.Unbounded_String;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols_Ref;
Events : MAT.Events.Targets.Target_Events_Access;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Events.Probes.Reader_List_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Get the console instance.
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access;
-- Set the console instance.
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access);
-- Get the current process instance.
function Process (Target : in Target_Type) return Target_Process_Type_Access;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
overriding
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Find the process instance from the process ID.
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access;
-- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure.
procedure Iterator (Target : in Target_Type;
Process : access procedure (Proc : in Target_Process_Type'Class));
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out Target_Type);
-- 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);
-- Start the server to listen to MAT event socket streams.
procedure Start (Target : in out Target_Type);
-- Stop the server thread.
procedure Stop (Target : in out Target_Type);
-- Convert the string to a socket address. The string can have two forms:
-- port
-- host:port
function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type;
-- Print the application usage.
procedure Usage;
private
-- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id.
-- This map allows to retrieve the information about a process.
use type MAT.Types.Target_Process_Ref;
package Process_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref,
Element_Type => Target_Process_Type_Access);
subtype Process_Map is Process_Maps.Map;
subtype Process_Cursor is Process_Maps.Cursor;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Events.Probes.Reader_List_Type with record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
end record;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Ada.Finalization;
with GNAT.Sockets;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Events.Targets;
with MAT.Events.Probes;
with MAT.Readers;
with MAT.Readers.Streams;
with MAT.Readers.Streams.Sockets;
with MAT.Consoles;
package MAT.Targets is
pragma Preelaborate_Body;
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
-- Enable and enter in the interactive TTY console mode.
Interactive : Boolean := True;
-- Try to load the symbol file automatically when a new process is received.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Print the events as they are received.
Print_Events : Boolean := False;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Path : Ada.Strings.Unbounded.Unbounded_String;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols_Ref;
Events : MAT.Events.Targets.Target_Events_Access;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Events.Probes.Reader_List_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Get the console instance.
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access;
-- Set the console instance.
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access);
-- Get the current process instance.
function Process (Target : in Target_Type) return Target_Process_Type_Access;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
overriding
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Find the process instance from the process ID.
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access;
-- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure.
procedure Iterator (Target : in Target_Type;
Process : access procedure (Proc : in Target_Process_Type'Class));
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out Target_Type);
-- 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);
-- Start the server to listen to MAT event socket streams.
procedure Start (Target : in out Target_Type);
-- Stop the server thread.
procedure Stop (Target : in out Target_Type);
-- Convert the string to a socket address. The string can have two forms:
-- port
-- host:port
function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type;
-- Print the application usage.
procedure Usage;
private
-- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id.
-- This map allows to retrieve the information about a process.
use type MAT.Types.Target_Process_Ref;
package Process_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref,
Element_Type => Target_Process_Type_Access);
subtype Process_Map is Process_Maps.Map;
subtype Process_Cursor is Process_Maps.Cursor;
type Target_Type is new Ada.Finalization.Limited_Controlled
and MAT.Events.Probes.Reader_List_Type with record
Current : Target_Process_Type_Access;
Processes : Process_Map;
Console : MAT.Consoles.Console_Access;
Options : Options_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
end record;
end MAT.Targets;
|
Add pragma Preelaborate
|
Add pragma Preelaborate
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
5d77509e33cd5ab19c3aafb2ce601bf9aaceb394
|
awa/regtests/awa-jobs-services-tests.adb
|
awa/regtests/awa-jobs-services-tests.adb
|
-----------------------------------------------------------------------
-- jobs-tests -- Unit tests for AWA jobs
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Log.Loggers;
with AWA.Jobs.Modules;
with AWA.Services.Contexts;
package body AWA.Jobs.Services.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services.Tests");
package Caller is new Util.Test_Caller (Test, "Jobs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register",
Test_Job_Schedule'Access);
end Add_Tests;
procedure Work_1 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
Msg : constant String := Job.Get_Parameter ("message");
Cnt : constant Natural := Job.Get_Parameter ("count", 0);
begin
Log.Info ("Execute work_1 {0}, count {1}", Msg, Natural'Image (Cnt));
end Work_1;
procedure Work_2 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
begin
null;
end Work_2;
-- ------------------------------
-- Test the job factory.
-- ------------------------------
procedure Test_Job_Schedule (T : in out Test) is
use type AWA.Jobs.Models.Job_Status_Type;
J : AWA.Jobs.Services.Job_Type;
M : AWA.Jobs.Modules.Job_Module_Access := AWA.Jobs.Modules.Get_Job_Module;
Context : AWA.Services.Contexts.Service_Context;
begin
Context.Set_Context (AWA.Tests.Get_Application, null);
M.Register (Definition => Services.Tests.Work_1_Definition.Factory);
J.Set_Parameter ("count", 1);
Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param");
J.Set_Parameter ("message", "Hello");
Util.Tests.Assert_Equals (T, "Hello", J.Get_Parameter ("message"), "Invalid message param");
J.Schedule (Work_1_Definition.Factory);
T.Assert (J.Get_Status = AWA.Jobs.Models.SCHEDULED, "Job is not scheduled");
--
for I in 1 .. 10 loop
delay 0.1;
end loop;
end Test_Job_Schedule;
-- Execute the job. This operation must be implemented and should perform the work
-- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve
-- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result.
overriding
procedure Execute (Job : in out Test_Job) is
begin
null;
end Execute;
end AWA.Jobs.Services.Tests;
|
-----------------------------------------------------------------------
-- jobs-tests -- Unit tests for AWA jobs
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Log.Loggers;
with AWA.Jobs.Modules;
with AWA.Services.Contexts;
package body AWA.Jobs.Services.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services.Tests");
package Caller is new Util.Test_Caller (Test, "Jobs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register",
Test_Job_Schedule'Access);
end Add_Tests;
procedure Work_1 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
Msg : constant String := Job.Get_Parameter ("message");
Cnt : constant Natural := Job.Get_Parameter ("count", 0);
begin
Log.Info ("Execute work_1 {0}, count {1}", Msg, Natural'Image (Cnt));
end Work_1;
procedure Work_2 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
begin
null;
end Work_2;
-- ------------------------------
-- Test the job factory.
-- ------------------------------
procedure Test_Job_Schedule (T : in out Test) is
use type AWA.Jobs.Models.Job_Status_Type;
J : AWA.Jobs.Services.Job_Type;
M : AWA.Jobs.Modules.Job_Module_Access := AWA.Jobs.Modules.Get_Job_Module;
Context : AWA.Services.Contexts.Service_Context;
begin
Context.Set_Context (AWA.Tests.Get_Application, null);
M.Register (Definition => Services.Tests.Work_1_Definition.Factory);
J.Set_Parameter ("count", 1);
Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param");
J.Set_Parameter ("message", "Hello");
Util.Tests.Assert_Equals (T, "Hello", J.Get_Parameter ("message"), "Invalid message param");
J.Schedule (Work_1_Definition.Factory.all);
T.Assert (J.Get_Status = AWA.Jobs.Models.SCHEDULED, "Job is not scheduled");
--
for I in 1 .. 10 loop
delay 0.1;
end loop;
end Test_Job_Schedule;
-- Execute the job. This operation must be implemented and should perform the work
-- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve
-- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result.
overriding
procedure Execute (Job : in out Test_Job) is
begin
null;
end Execute;
end AWA.Jobs.Services.Tests;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
c4567d08cb7b1f331aff1d043a68e5803510c1b2
|
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.Html.Text;
with ASF.Components.Html.Lists;
with ASF.Views.Nodes;
package body ASF.Components.Html.Factory is
function Create_Output return UIComponent_Access;
function Create_Label return UIComponent_Access;
function Create_List 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 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;
use ASF.Views.Nodes;
URI : aliased constant String := "http://java.sun.com/jsf/html";
OUTPUT_TAG : aliased constant String := "output";
LABEL_TAG : aliased constant String := "label";
LIST_TAG : aliased constant String := "list";
Html_Bindings : aliased constant ASF.Factory.Binding_Array
:= (2 => (Name => OUTPUT_TAG'Access,
Component => Create_Output'Access,
Tag => Create_Component_Node'Access),
0 => (Name => LABEL_TAG'Access,
Component => Create_Label'Access,
Tag => Create_Component_Node'Access),
1 => (Name => LIST_TAG'Access,
Component => Create_List'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;
begin
ASF.Factory.Check (Html_Factory);
end ASF.Components.Html.Factory;
|
-----------------------------------------------------------------------
-- 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.Html.Text;
with ASF.Components.Html.Lists;
with ASF.Components.Html.Links;
with ASF.Views.Nodes;
package body ASF.Components.Html.Factory is
function Create_Output return UIComponent_Access;
function Create_Output_Link return UIComponent_Access;
function Create_Label return UIComponent_Access;
function Create_List 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 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;
use ASF.Views.Nodes;
URI : aliased constant String := "http://java.sun.com/jsf/html";
OUTPUT_TEXT_TAG : aliased constant String := "outputText";
OUTPUT_LINK_TAG : aliased constant String := "outputLink";
LABEL_TAG : aliased constant String := "label";
LIST_TAG : aliased constant String := "list";
Html_Bindings : aliased constant ASF.Factory.Binding_Array
:= (4 => (Name => OUTPUT_TEXT_TAG'Access,
Component => Create_Output'Access,
Tag => Create_Component_Node'Access),
1 => (Name => LABEL_TAG'Access,
Component => Create_Label'Access,
Tag => Create_Component_Node'Access),
2 => (Name => LIST_TAG'Access,
Component => Create_List'Access,
Tag => Create_Component_Node'Access),
3 => (Name => OUTPUT_LINK_TAG'Access,
Component => Create_Output_Link'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;
begin
ASF.Factory.Check (Html_Factory);
end ASF.Components.Html.Factory;
|
Update the jsf components factory
|
Update the jsf components factory
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
2c25c8f5c97e070671d00c3448bb318f918abf5a
|
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 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);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
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;
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 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);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
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;
end Event_Collector;
end MAT.Events.Targets;
|
Implement the Get_Time_Range procedure
|
Implement the Get_Time_Range procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
bc8303eec9317e70323e6ed2e8293a4a8b8076c6
|
src/gen-generator.ads
|
src/gen-generator.ads
|
-----------------------------------------------------------------------
-- gen-generator -- Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Ada.Containers.Hashed_Maps;
with Util.Beans.Objects;
with Util.Properties;
with ASF.Applications.Main;
with ASF.Contexts.Faces;
with ASF.Servlets.Files;
with Gen.Model.Packages;
with Gen.Model.Projects;
with Gen.Artifacts.Hibernate;
with Gen.Artifacts.Query;
with Gen.Artifacts.Mappings;
with Gen.Artifacts.Distribs;
with Gen.Artifacts.XMI;
package Gen.Generator is
-- A fatal error that prevents the generator to proceed has occurred.
Fatal_Error : exception;
G_URI : constant String := "http://code.google.com/p/ada-ado/generator";
type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS);
type Mapping_File is record
Path : Ada.Strings.Unbounded.Unbounded_String;
Output : Ada.Text_IO.File_Type;
end record;
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private;
-- Initialize the generator
procedure Initialize (H : in out Handler;
Config_Dir : in Ada.Strings.Unbounded.Unbounded_String;
Debug : in Boolean);
-- Get the configuration properties.
function Get_Properties (H : in Handler) return Util.Properties.Manager;
-- Report an error and set the exit status accordingly
procedure Error (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "");
-- Report an info message.
procedure Info (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
-- Read the XML package file
procedure Read_Package (H : in out Handler;
File : in String);
-- Read the model mapping types and initialize the hibernate artifact.
procedure Read_Mappings (H : in out Handler);
-- Read the XML model file
procedure Read_Model (H : in out Handler;
File : in String;
Silent : in Boolean);
-- Read the model and query files stored in the application directory <b>db</b>.
procedure Read_Models (H : in out Handler;
Dirname : in String);
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (H : in out Handler;
File : in String;
Recursive : in Boolean := False);
-- Prepare the model by checking, verifying and initializing it after it is completely known.
procedure Prepare (H : in out Handler);
-- Finish the generation. Some artifacts could generate other files that take into
-- account files generated previously.
procedure Finish (H : in out Handler);
-- Tell the generator to activate the generation of the given template name.
-- The name is a property name that must be defined in generator.properties to
-- indicate the template file. Several artifacts can trigger the generation
-- of a given template. The template is generated only once.
procedure Add_Generation (H : in out Handler;
Name : in String;
Mode : in Gen.Artifacts.Iteration_Mode;
Mapping : in String);
-- Enable the generation of the Ada package given by the name. By default all the Ada
-- packages found in the model are generated. When called, this enables the generation
-- only for the Ada packages registered here.
procedure Enable_Package_Generation (H : in out Handler;
Name : in String);
-- Save the content generated by the template generator.
procedure Save_Content (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String);
-- Generate the code using the template file
procedure Generate (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
File : in String;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate the code using the template file
procedure Generate (H : in out Handler;
File : in String;
Model : in Gen.Model.Definition_Access;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate all the code for the templates activated through <b>Add_Generation</b>.
procedure Generate_All (H : in out Handler);
-- Generate all the code generation files stored in the directory
procedure Generate_All (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
Name : in String);
-- Set the directory where template files are stored.
procedure Set_Template_Directory (H : in out Handler;
Path : in Ada.Strings.Unbounded.Unbounded_String);
-- Set the directory where results files are generated.
procedure Set_Result_Directory (H : in out Handler;
Path : in String);
-- Get the result directory path.
function Get_Result_Directory (H : in Handler) return String;
-- Get the project plugin directory path.
function Get_Plugin_Directory (H : in Handler) return String;
-- Get the config directory path.
function Get_Config_Directory (H : in Handler) return String;
-- Get the dynamo installation directory path.
function Get_Install_Directory (H : in Handler) return String;
-- Return the search directories that the AWA application can use to find files.
-- The search directories is built by using the project dependencies.
function Get_Search_Directories (H : in Handler) return String;
-- Get the exit status
-- Returns 0 if the generation was successful
-- Returns 1 if there was a generation error
function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in Boolean := False) return Boolean;
-- Set the force-save file mode. When False, if the generated file exists already,
-- an error message is reported.
procedure Set_Force_Save (H : in out Handler;
To : in Boolean);
-- Set the project name.
procedure Set_Project_Name (H : in out Handler;
Name : in String);
-- Get the project name.
function Get_Project_Name (H : in Handler) return String;
-- Set the project property.
procedure Set_Project_Property (H : in out Handler;
Name : in String;
Value : in String);
-- Get the project property identified by the given name. If the project property
-- does not exist, returns the default value. Project properties are loaded
-- by <b>Read_Project</b>.
function Get_Project_Property (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Save the project description and parameters.
procedure Save_Project (H : in out Handler);
-- Get the path of the last generated file.
function Get_Generated_File (H : in Handler) return String;
-- Update the project model through the <b>Process</b> procedure.
procedure Update_Project (H : in out Handler;
Process : not null access
procedure (P : in out Model.Projects.Root_Project_Definition));
-- Scan the dynamo directories and execute the <b>Process</b> procedure with the
-- directory path.
procedure Scan_Directories (H : in Handler;
Process : not null access
procedure (Dir : in String));
private
use Ada.Strings.Unbounded;
use Gen.Artifacts;
type Template_Context is record
Mode : Gen.Artifacts.Iteration_Mode;
Mapping : Unbounded_String;
end record;
package Template_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Template_Context,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record
Conf : ASF.Applications.Config;
-- Config directory.
Config_Dir : Ada.Strings.Unbounded.Unbounded_String;
-- Output base directory.
Output_Dir : Ada.Strings.Unbounded.Unbounded_String;
Model : aliased Gen.Model.Packages.Model_Definition;
Status : Ada.Command_Line.Exit_Status := 0;
-- The file that must be saved (the file attribute in <f:view>.
File : access Util.Beans.Objects.Object;
-- Indicates whether the file must be saved at each generation or only once.
-- This is the mode attribute in <f:view>.
Mode : access Util.Beans.Objects.Object;
-- Indicates whether the file must be ignored after the generation.
-- This is the ignore attribute in <f:view>. It is intended to be used for the package
-- body generation to skip that in some cases when it turns out there is no operation.
Ignore : access Util.Beans.Objects.Object;
-- Whether the AdaMappings.xml file was loaded or not.
Type_Mapping_Loaded : Boolean := False;
-- The root project document.
Project : aliased Gen.Model.Projects.Root_Project_Definition;
-- Hibernate XML artifact
Hibernate : Gen.Artifacts.Hibernate.Artifact;
-- Query generation artifact.
Query : Gen.Artifacts.Query.Artifact;
-- Type mapping artifact.
Mappings : Gen.Artifacts.Mappings.Artifact;
-- The distribution artifact.
Distrib : Gen.Artifacts.Distribs.Artifact;
-- Ada generation from UML-XMI models.
XMI : Gen.Artifacts.XMI.Artifact;
-- The list of templates that must be generated.
Templates : Template_Map.Map;
-- Force the saving of a generated file, even if a file already exist.
Force_Save : Boolean := True;
-- A fake servlet for template evaluation.
Servlet : ASF.Servlets.Servlet_Access;
end record;
-- Execute the lifecycle phases on the faces context.
overriding
procedure Execute_Lifecycle (App : in Handler;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end Gen.Generator;
|
-----------------------------------------------------------------------
-- gen-generator -- Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Ada.Containers.Hashed_Maps;
with Util.Beans.Objects;
with Util.Properties;
with ASF.Applications.Main;
with ASF.Contexts.Faces;
with ASF.Servlets;
with Gen.Model.Packages;
with Gen.Model.Projects;
with Gen.Artifacts.Hibernate;
with Gen.Artifacts.Query;
with Gen.Artifacts.Mappings;
with Gen.Artifacts.Distribs;
with Gen.Artifacts.XMI;
package Gen.Generator is
-- A fatal error that prevents the generator to proceed has occurred.
Fatal_Error : exception;
G_URI : constant String := "http://code.google.com/p/ada-ado/generator";
type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS);
type Mapping_File is record
Path : Ada.Strings.Unbounded.Unbounded_String;
Output : Ada.Text_IO.File_Type;
end record;
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private;
-- Initialize the generator
procedure Initialize (H : in out Handler;
Config_Dir : in Ada.Strings.Unbounded.Unbounded_String;
Debug : in Boolean);
-- Get the configuration properties.
function Get_Properties (H : in Handler) return Util.Properties.Manager;
-- Report an error and set the exit status accordingly
procedure Error (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "");
-- Report an info message.
procedure Info (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
-- Read the XML package file
procedure Read_Package (H : in out Handler;
File : in String);
-- Read the model mapping types and initialize the hibernate artifact.
procedure Read_Mappings (H : in out Handler);
-- Read the XML model file
procedure Read_Model (H : in out Handler;
File : in String;
Silent : in Boolean);
-- Read the model and query files stored in the application directory <b>db</b>.
procedure Read_Models (H : in out Handler;
Dirname : in String);
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (H : in out Handler;
File : in String;
Recursive : in Boolean := False);
-- Prepare the model by checking, verifying and initializing it after it is completely known.
procedure Prepare (H : in out Handler);
-- Finish the generation. Some artifacts could generate other files that take into
-- account files generated previously.
procedure Finish (H : in out Handler);
-- Tell the generator to activate the generation of the given template name.
-- The name is a property name that must be defined in generator.properties to
-- indicate the template file. Several artifacts can trigger the generation
-- of a given template. The template is generated only once.
procedure Add_Generation (H : in out Handler;
Name : in String;
Mode : in Gen.Artifacts.Iteration_Mode;
Mapping : in String);
-- Enable the generation of the Ada package given by the name. By default all the Ada
-- packages found in the model are generated. When called, this enables the generation
-- only for the Ada packages registered here.
procedure Enable_Package_Generation (H : in out Handler;
Name : in String);
-- Save the content generated by the template generator.
procedure Save_Content (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String);
-- Generate the code using the template file
procedure Generate (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
File : in String;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate the code using the template file
procedure Generate (H : in out Handler;
File : in String;
Model : in Gen.Model.Definition_Access;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate all the code for the templates activated through <b>Add_Generation</b>.
procedure Generate_All (H : in out Handler);
-- Generate all the code generation files stored in the directory
procedure Generate_All (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
Name : in String);
-- Set the directory where template files are stored.
procedure Set_Template_Directory (H : in out Handler;
Path : in Ada.Strings.Unbounded.Unbounded_String);
-- Set the directory where results files are generated.
procedure Set_Result_Directory (H : in out Handler;
Path : in String);
-- Get the result directory path.
function Get_Result_Directory (H : in Handler) return String;
-- Get the project plugin directory path.
function Get_Plugin_Directory (H : in Handler) return String;
-- Get the config directory path.
function Get_Config_Directory (H : in Handler) return String;
-- Get the dynamo installation directory path.
function Get_Install_Directory (H : in Handler) return String;
-- Return the search directories that the AWA application can use to find files.
-- The search directories is built by using the project dependencies.
function Get_Search_Directories (H : in Handler) return String;
-- Get the exit status
-- Returns 0 if the generation was successful
-- Returns 1 if there was a generation error
function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in Boolean := False) return Boolean;
-- Set the force-save file mode. When False, if the generated file exists already,
-- an error message is reported.
procedure Set_Force_Save (H : in out Handler;
To : in Boolean);
-- Set the project name.
procedure Set_Project_Name (H : in out Handler;
Name : in String);
-- Get the project name.
function Get_Project_Name (H : in Handler) return String;
-- Set the project property.
procedure Set_Project_Property (H : in out Handler;
Name : in String;
Value : in String);
-- Get the project property identified by the given name. If the project property
-- does not exist, returns the default value. Project properties are loaded
-- by <b>Read_Project</b>.
function Get_Project_Property (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Save the project description and parameters.
procedure Save_Project (H : in out Handler);
-- Get the path of the last generated file.
function Get_Generated_File (H : in Handler) return String;
-- Update the project model through the <b>Process</b> procedure.
procedure Update_Project (H : in out Handler;
Process : not null access
procedure (P : in out Model.Projects.Root_Project_Definition));
-- Scan the dynamo directories and execute the <b>Process</b> procedure with the
-- directory path.
procedure Scan_Directories (H : in Handler;
Process : not null access
procedure (Dir : in String));
private
use Ada.Strings.Unbounded;
use Gen.Artifacts;
type Template_Context is record
Mode : Gen.Artifacts.Iteration_Mode;
Mapping : Unbounded_String;
end record;
package Template_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Template_Context,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record
Conf : ASF.Applications.Config;
-- Config directory.
Config_Dir : Ada.Strings.Unbounded.Unbounded_String;
-- Output base directory.
Output_Dir : Ada.Strings.Unbounded.Unbounded_String;
Model : aliased Gen.Model.Packages.Model_Definition;
Status : Ada.Command_Line.Exit_Status := 0;
-- The file that must be saved (the file attribute in <f:view>.
File : access Util.Beans.Objects.Object;
-- Indicates whether the file must be saved at each generation or only once.
-- This is the mode attribute in <f:view>.
Mode : access Util.Beans.Objects.Object;
-- Indicates whether the file must be ignored after the generation.
-- This is the ignore attribute in <f:view>. It is intended to be used for the package
-- body generation to skip that in some cases when it turns out there is no operation.
Ignore : access Util.Beans.Objects.Object;
-- Whether the AdaMappings.xml file was loaded or not.
Type_Mapping_Loaded : Boolean := False;
-- The root project document.
Project : aliased Gen.Model.Projects.Root_Project_Definition;
-- Hibernate XML artifact
Hibernate : Gen.Artifacts.Hibernate.Artifact;
-- Query generation artifact.
Query : Gen.Artifacts.Query.Artifact;
-- Type mapping artifact.
Mappings : Gen.Artifacts.Mappings.Artifact;
-- The distribution artifact.
Distrib : Gen.Artifacts.Distribs.Artifact;
-- Ada generation from UML-XMI models.
XMI : Gen.Artifacts.XMI.Artifact;
-- The list of templates that must be generated.
Templates : Template_Map.Map;
-- Force the saving of a generated file, even if a file already exist.
Force_Save : Boolean := True;
-- A fake servlet for template evaluation.
Servlet : ASF.Servlets.Servlet_Access;
end record;
-- Execute the lifecycle phases on the faces context.
overriding
procedure Execute_Lifecycle (App : in Handler;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end Gen.Generator;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
71a444700ccc44883e493d313c0eaba55979aaa4
|
matp/regtests/mat-expressions-tests.adb
|
matp/regtests/mat-expressions-tests.adb
|
-----------------------------------------------------------------------
-- mat-expressions-tests -- Unit tests for MAT expressions
-- 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.Directories;
with Util.Test_Caller;
with Util.Assertions;
package body MAT.Expressions.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Expressions");
procedure Assert_Equals_Kind is
new Util.Assertions.Assert_Equals_T (Value_Type => Kind_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Expressions.Parse",
Test_Parse_Expression'Access);
end Add_Tests;
-- ------------------------------
-- Test parsing simple expressions
-- ------------------------------
procedure Test_Parse_Expression (T : in out Test) is
Result : MAT.Expressions.Expression_Type;
begin
Result := MAT.Expressions.Parse ("by foo");
T.Assert (Result.Node /= null, "Parse 'by foo' must return a expression");
Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("by direct foo");
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("after foo");
T.Assert (Result.Node /= null, "Parse 'after foo' must return a expression");
-- Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("before foo");
T.Assert (Result.Node /= null, "Parse 'before foo' must return a expression");
-- Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("with size in [10,100]");
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_RANGE_SIZE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("with size in [10..100]");
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_RANGE_SIZE, Result.Node.Kind, "Invalid node kind");
end Test_Parse_Expression;
end MAT.Expressions.Tests;
|
-----------------------------------------------------------------------
-- mat-expressions-tests -- Unit tests for MAT expressions
-- 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.Directories;
with Util.Test_Caller;
with Util.Assertions;
package body MAT.Expressions.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Expressions");
procedure Assert_Equals_Kind is
new Util.Assertions.Assert_Equals_T (Value_Type => Kind_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Expressions.Parse",
Test_Parse_Expression'Access);
end Add_Tests;
-- ------------------------------
-- Test parsing simple expressions
-- ------------------------------
procedure Test_Parse_Expression (T : in out Test) is
Result : MAT.Expressions.Expression_Type;
begin
Result := MAT.Expressions.Parse ("by foo", null);
T.Assert (Result.Node /= null, "Parse 'by foo' must return a expression");
Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("by direct foo", null);
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("after foo", null);
T.Assert (Result.Node /= null, "Parse 'after foo' must return a expression");
-- Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("before foo", null);
T.Assert (Result.Node /= null, "Parse 'before foo' must return a expression");
-- Assert_Equals_Kind (T, N_INSIDE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("with size in [10,100]", null);
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_RANGE_SIZE, Result.Node.Kind, "Invalid node kind");
Result := MAT.Expressions.Parse ("with size in [10..100]", null);
T.Assert (Result.Node /= null, "Parse 'by direct foo' must return a expression");
Assert_Equals_Kind (T, N_RANGE_SIZE, Result.Node.Kind, "Invalid node kind");
end Test_Parse_Expression;
end MAT.Expressions.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
02c391cb997970487b30ecf622cb58628bcbdf90
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
with Wiki.Render.Links;
-- === HTML Renderer ===
-- The `Html_Renderer` allows to render a wiki document into an HTML content.
--
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Wiki.Render.Links.Link_Renderer_Access);
-- Set the render TOC flag that controls the TOC rendering.
procedure Set_Render_TOC (Engine : in out Html_Renderer;
State : in Boolean);
-- Set the no-newline mode to avoid emitting newlines (disabled by default).
procedure Set_No_Newline (Engine : in out Html_Renderer;
Enable : in Boolean);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Get the current section number.
function Get_Section_Number (Engine : in Html_Renderer;
Prefix : in Wiki.Strings.WString;
Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString;
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Render a table component such as N_TABLE, N_ROW or N_COLUMN.
procedure Render_Table (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type;
Tag : in String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document);
private
procedure Close_Paragraph (Engine : in out Html_Renderer);
procedure Open_Paragraph (Engine : in out Html_Renderer);
type Toc_Number_Array is array (1 .. 6) of Natural;
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Wiki.Render.Links.Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Enable_Render_TOC : Boolean := False;
TOC_Rendered : Boolean := False;
No_Newline : Boolean := False;
Current_Level : Natural := 0;
Html_Tag : Wiki.Html_Tag := BODY_TAG;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
Current_Section : Toc_Number_Array := (others => 0);
Section_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render the table of content.
procedure Render_TOC (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Level : in Natural);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Returns true if the HTML element being included is already contained in a paragraph.
-- This include: a, em, strong, small, b, i, u, s, span, ins, del, sub, sup.
function Has_Html_Paragraph (Engine : in Html_Renderer) return Boolean;
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
with Wiki.Render.Links;
-- === HTML Renderer ===
-- The `Html_Renderer` allows to render a wiki document into an HTML content.
--
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Wiki.Render.Links.Link_Renderer_Access);
-- Set the render TOC flag that controls the TOC rendering.
procedure Set_Render_TOC (Engine : in out Html_Renderer;
State : in Boolean);
-- Set the no-newline mode to avoid emitting newlines (disabled by default).
procedure Set_No_Newline (Engine : in out Html_Renderer;
Enable : in Boolean);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Get the current section number.
function Get_Section_Number (Engine : in Html_Renderer;
Prefix : in Wiki.Strings.WString;
Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString;
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Render a table component such as N_TABLE, N_ROW or N_COLUMN.
procedure Render_Table (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type;
Tag : in String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document);
private
procedure Close_Paragraph (Engine : in out Html_Renderer);
procedure Open_Paragraph (Engine : in out Html_Renderer);
type Toc_Number_Array is array (1 .. 6) of Natural;
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Wiki.Render.Links.Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Enable_Render_TOC : Boolean := False;
TOC_Rendered : Boolean := False;
No_Newline : Boolean := False;
Current_Level : Natural := 0;
Html_Tag : Wiki.Html_Tag := BODY_TAG;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
Current_Section : Toc_Number_Array := (others => 0);
Section_Level : Natural := 0;
Column : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render the table of content.
procedure Render_TOC (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Level : in Natural);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Returns true if the HTML element being included is already contained in a paragraph.
-- This include: a, em, strong, small, b, i, u, s, span, ins, del, sub, sup.
function Has_Html_Paragraph (Engine : in Html_Renderer) return Boolean;
procedure Newline (Engine : in out Html_Renderer);
end Wiki.Render.Html;
|
Add Newline procedure to emit newlines
|
Add Newline procedure to emit newlines
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
480139730e54d30609a8c93e6d21d5fa3e73b286
|
src/wiki-render-text.ads
|
src/wiki-render-text.ads
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams;
-- == Text 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.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a section header in the document.
procedure Add_Header (Document : in out Text_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- 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 Text_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 Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_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 Text_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 Text_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 (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
procedure Start_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Text_Renderer);
private
-- Emit a new line.
procedure New_Line (Document : in out Text_Renderer);
procedure Close_Paragraph (Document : in out Text_Renderer);
procedure Open_Paragraph (Document : in out Text_Renderer);
type Text_Renderer is new Wiki.Render.Renderer with record
Output : Streams.Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams;
-- == Text 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.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- 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 Text_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 Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_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 Text_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 Text_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 (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
procedure Start_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Text_Renderer);
private
-- Emit a new line.
procedure New_Line (Document : in out Text_Renderer);
procedure Close_Paragraph (Document : in out Text_Renderer);
procedure Open_Paragraph (Document : in out Text_Renderer);
type Text_Renderer is new Wiki.Render.Renderer with record
Output : Streams.Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
Remove the Add_Header procedure
|
Remove the Add_Header procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
794c696c277f8df91ceec5a77bc0a373af2224ea
|
regtests/regtests.ads
|
regtests/regtests.ads
|
-----------------------------------------------------------------------
-- ADO Tests -- Database sequence generator
-- Copyright (C) 2009, 2010, 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 ADO.Sessions.Sources;
package Regtests is
-- ------------------------------
-- Get the database manager to be used for the unit tests
-- ------------------------------
function Get_Controller return ADO.Sessions.Sources.Data_Source'Class;
-- ------------------------------
-- Get the readonly connection database to be used for the unit tests
-- ------------------------------
function Get_Database return ADO.Sessions.Session;
-- ------------------------------
-- Get the writeable connection database to be used for the unit tests
-- ------------------------------
function Get_Master_Database return ADO.Sessions.Master_Session;
-- ------------------------------
-- Initialize the test database
-- ------------------------------
procedure Initialize (Name : in String);
end Regtests;
|
-----------------------------------------------------------------------
-- regtests -- Support for unit tests
-- Copyright (C) 2009, 2010, 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 ADO.Audits;
with ADO.Sessions;
with ADO.Sessions.Sources;
package Regtests is
-- Get the database manager to be used for the unit tests
function Get_Controller return ADO.Sessions.Sources.Data_Source'Class;
-- Get the readonly connection database to be used for the unit tests
function Get_Database return ADO.Sessions.Session;
-- Get the writeable connection database to be used for the unit tests
function Get_Master_Database return ADO.Sessions.Master_Session;
-- Set the audit manager on the factory.
procedure Set_Audit_Manager (Manager : in ADO.Audits.Audit_Manager_Access);
-- Initialize the test database
procedure Initialize (Name : in String);
end Regtests;
|
Declare the Set_Audit_Manager procedure
|
Declare the Set_Audit_Manager procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
d3de25c3dba5635b6373bce432c78192917409ae
|
src/util-serialize-io-csv.ads
|
src/util-serialize-io-csv.ads
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Vectors;
with Util.Streams.Texts;
-- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files.
--
-- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files
package Util.Serialize.IO.CSV is
type Row_Type is new Natural;
type Column_Type is new Positive;
-- ------------------------------
-- CSV Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a CSV output stream.
-- The stream object takes care of the CSV escape rules.
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private;
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new row.
procedure New_Row (Stream : in out Output_Stream);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the entity value.
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- CSV Parser
-- ------------------------------
-- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly
-- in Ada records.
type Parser is new Serialize.IO.Parser with private;
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String;
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type);
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the field separator.
function Get_Field_Separator (Handler : in Parser) return Character;
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
function Get_Comment_Separator (Handler : in Parser) return Character;
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True);
-- Parse the stream using the CSV parser.
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class);
-- Get the current location (file and line) to report an error message.
overriding
function Get_Location (Handler : in Parser) return String;
private
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record
Max_Columns : Column_Type := 1;
Column : Column_Type := 1;
Row : Row_Type := 0;
end record;
type Parser is new Util.Serialize.IO.Parser with record
Has_Header : Boolean := True;
Line_Number : Natural := 1;
Row : Row_Type := 0;
Headers : Util.Strings.Vectors.Vector;
Separator : Character := ',';
Comment : Character := ASCII.NUL;
Use_Default_Headers : Boolean := False;
end record;
end Util.Serialize.IO.CSV;
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Vectors;
with Util.Streams.Texts;
-- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files.
--
-- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files
package Util.Serialize.IO.CSV is
type Row_Type is new Natural;
type Column_Type is new Positive;
-- ------------------------------
-- CSV Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a CSV output stream.
-- The stream object takes care of the CSV escape rules.
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private;
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character);
-- Enable or disable the double quotes by default for strings.
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean);
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new row.
procedure New_Row (Stream : in out Output_Stream);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the entity value.
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- CSV Parser
-- ------------------------------
-- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly
-- in Ada records.
type Parser is new Serialize.IO.Parser with private;
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String;
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type);
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the field separator.
function Get_Field_Separator (Handler : in Parser) return Character;
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
function Get_Comment_Separator (Handler : in Parser) return Character;
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True);
-- Parse the stream using the CSV parser.
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class);
-- Get the current location (file and line) to report an error message.
overriding
function Get_Location (Handler : in Parser) return String;
private
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record
Max_Columns : Column_Type := 1;
Column : Column_Type := 1;
Row : Row_Type := 0;
Separator : Character := ',';
Quote : Boolean := True;
end record;
type Parser is new Util.Serialize.IO.Parser with record
Has_Header : Boolean := True;
Line_Number : Natural := 1;
Row : Row_Type := 0;
Headers : Util.Strings.Vectors.Vector;
Separator : Character := ',';
Comment : Character := ASCII.NUL;
Use_Default_Headers : Boolean := False;
end record;
end Util.Serialize.IO.CSV;
|
Declare Set_Field_Separator and Set_Quotes to configure the CSV output writer
|
Declare Set_Field_Separator and Set_Quotes to configure the CSV output writer
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
655ba249590761c2098b4e32dcc1ec3ca1ac0617
|
src/util-beans.ads
|
src/util-beans.ads
|
-----------------------------------------------------------------------
-- Util.Beans -- Interface Definition with Getter and Setters
-- 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.
-----------------------------------------------------------------------
package Util.Beans is
pragma Preelaborate;
end Util.Beans;
|
-----------------------------------------------------------------------
-- util-beans -- Interface Definition with Getter and Setters
-- Copyright (C) 2009, 2010, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Util.Beans is
pragma Preelaborate;
end Util.Beans;
|
Fix header style
|
Fix header style
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
91331b561ab2cba03e9d853ea312abb4fa8018c5
|
src/sys/os-windows/util-processes-os.ads
|
src/sys/os-windows/util-processes-os.ads
|
-----------------------------------------------------------------------
-- util-processes-os -- Windows specific and low level operations
-- Copyright (C) 2011, 2012, 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.Streams.Raw;
with Util.Systems.Os;
with Interfaces.C;
private package Util.Processes.Os is
use Util.Systems.Os;
SHELL : constant String := "";
type Wchar_Ptr is access all Interfaces.C.wchar_array;
type System_Process is new Util.Processes.System_Process with record
Process_Info : aliased Util.Systems.Os.PROCESS_INFORMATION;
Command : Wchar_Ptr := null;
Pos : Interfaces.C.size_t := 0;
To_Close : File_Type_Array_Access;
end record;
-- Wait for the process to exit.
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration);
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE);
-- 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);
-- Append the argument to the process argument list.
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String);
-- 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);
-- Deletes the storage held by the system process.
overriding
procedure Finalize (Sys : in out System_Process);
-- Build the output pipe redirection to read the process output.
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
-- Build the input pipe redirection to write the process standard input.
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
private
-- 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 Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access;
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- Windows specific and low level operations
-- Copyright (C) 2011, 2012, 2016, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Raw;
with Util.Systems.Os;
with Interfaces.C;
private package Util.Processes.Os is
use Util.Systems.Os;
SHELL : constant String := "";
type Wchar_Ptr is access all Interfaces.C.wchar_array;
type System_Process is new Util.Processes.System_Process with record
Process_Info : aliased Util.Systems.Os.PROCESS_INFORMATION;
Command : Wchar_Ptr := null;
Pos : Interfaces.C.size_t := 0;
In_File : Wchar_Ptr := null;
Out_File : Wchar_Ptr := null;
Err_File : Wchar_Ptr := null;
Dir : Wchar_Ptr := null;
To_Close : File_Type_Array_Access;
Out_Append : Boolean := False;
Err_Append : Boolean := False;
end record;
-- Wait for the process to exit.
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration);
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE);
-- 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);
-- Append the argument to the process argument list.
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String);
-- 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);
-- Deletes the storage held by the system process.
overriding
procedure Finalize (Sys : in out System_Process);
-- Build the output pipe redirection to read the process output.
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
-- Build the input pipe redirection to write the process standard input.
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
private
-- 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 Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access;
end Util.Processes.Os;
|
Add support to redirect to/from a file and set the process working directory
|
Add support to redirect to/from a file and set the process working directory
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
bea375106da24b7c7cb8af2fb789fd15ccafe787
|
mat/src/mat-formats.ads
|
mat/src/mat-formats.ads
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
package MAT.Formats is
-- Format the address into a string.
function Addr (Value : in MAT.Types.Target_Addr) return String;
-- Format the size into a string.
function Size (Value : in MAT.Types.Target_Size) return String;
end MAT.Formats;
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
package MAT.Formats is
-- Format the address into a string.
function Addr (Value : in MAT.Types.Target_Addr) return String;
-- Format the size into a string.
function Size (Value : in MAT.Types.Target_Size) return String;
-- Format a file, line, function information into a string.
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String;
end MAT.Formats;
|
Declare the Location function to format a file,line,function code location
|
Declare the Location function to format a file,line,function code location
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
e85aaa0ad82e8145bcb76b674325bff92349ab2f
|
awa/plugins/awa-setup/src/awa-setup-applications.adb
|
awa/plugins/awa-setup/src/awa-setup-applications.adb
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Directories;
with Util.Files;
with Util.Processes;
with Util.Log.Loggers;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Strings;
with ASF.Events.Faces.Actions;
with ASF.Applications.Main.Configs;
with AWA.Applications;
package body AWA.Setup.Applications is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications");
package Save_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Save,
Name => "save");
package Finish_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Finish,
Name => "finish");
package Configure_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Configure_Database,
Name => "configure_database");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Save_Binding.Proxy'Access,
Finish_Binding.Proxy'Access,
Configure_Binding.Proxy'Access);
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
Context_Path : constant String := Request.Get_Context_Path;
begin
Response.Send_Redirect (Context_Path & "/setup/install.html");
end Do_Get;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "database_name" then
return Util.Beans.Objects.To_Object (From.Database.Get_Database);
elsif Name = "database_server" then
return Util.Beans.Objects.To_Object (From.Database.Get_Server);
elsif Name = "database_port" then
return Util.Beans.Objects.To_Object (From.Database.Get_Port);
elsif Name = "database_user" then
return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user"));
elsif Name = "database_password" then
return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password"));
elsif Name = "database_driver" then
return From.Driver; -- Util.Beans.Objects.To_Object (From.Database.Get_Driver);
elsif Name = "database_root_user" then
return From.Root_User;
elsif Name = "database_root_password" then
return From.Root_Passwd;
elsif Name = "result" then
return From.Result;
end if;
if From.Changed.Exists (Name) then
return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name)));
end if;
declare
Param : constant String := From.Config.Get (Name);
begin
return Util.Beans.Objects.To_Object (Param);
end;
exception
when others =>
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "database_name" then
From.Database.Set_Database (Util.Beans.Objects.To_String (Value));
elsif Name = "database_server" then
From.Database.Set_Server (Util.Beans.Objects.To_String (Value));
elsif Name = "database_port" then
From.Database.Set_Port (Util.Beans.Objects.To_Integer (Value));
elsif Name = "database_user" then
From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value));
elsif Name = "database_password" then
From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value));
elsif Name = "database_driver" then
From.Driver := Value;
elsif Name = "database_root_user" then
From.Root_User := Value;
elsif Name = "database_root_password" then
From.Root_Passwd := Value;
elsif Name = "callback_url" then
From.Changed.Set (Name, Util.Beans.Objects.To_String (Value));
From.Changed.Set ("facebook.callback_url",
Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify");
From.Changed.Set ("google-plus.callback_url",
Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify");
else
From.Changed.Set (Name, Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Get the database connection string to be used by the application.
-- ------------------------------
function Get_Database_URL (From : in Application) return String is
use Ada.Strings.Unbounded;
Result : Ada.Strings.Unbounded.Unbounded_String;
Driver : constant String := Util.Beans.Objects.To_String (From.Driver);
User : constant String := From.Database.Get_Property ("user");
begin
if Driver = "" then
Append (Result, "mysql");
else
Append (Result, Driver);
end if;
Append (Result, "://");
if Driver /= "sqlite" then
Append (Result, From.Database.Get_Server);
if From.Database.Get_Port /= 0 then
Append (Result, ":");
Append (Result, Util.Strings.Image (From.Database.Get_Port));
end if;
end if;
Append (Result, "/");
Append (Result, From.Database.Get_Database);
if User /= "" then
Append (Result, "?user=");
Append (Result, User);
if From.Database.Get_Property ("password") /= "" then
Append (Result, "&password=");
Append (Result, From.Database.Get_Property ("password"));
end if;
end if;
if Driver = "sqlite" then
if User /= "" then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, "synchronous=OFF&encoding=UTF-8");
end if;
return To_String (Result);
end Get_Database_URL;
-- ------------------------------
-- Get the command to configure the database.
-- ------------------------------
function Get_Configure_Command (From : in Application) return String is
Driver : constant String := Util.Beans.Objects.To_String (From.Driver);
Database : constant String := From.Get_Database_URL;
Command : constant String := "dynamo create-database db '" & Database & "'";
Root : constant String := Util.Beans.Objects.To_String (From.Root_User);
Passwd : constant String := Util.Beans.Objects.To_String (From.Root_Passwd);
begin
if Root = "" then
return Command;
elsif Passwd = "" then
return Command & " " & Root;
else
return Command & " " & Root & " " & Passwd;
end if;
end Get_Configure_Command;
-- ------------------------------
-- Configure the database.
-- ------------------------------
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
Command : constant String := From.Get_Configure_Command;
begin
Log.Info ("Configure database with {0}", Command);
Pipe.Open (Command, Util.Processes.READ);
Buffer.Initialize (null, Pipe'Unchecked_Access, 64*1024);
Buffer.Read (Content);
Pipe.Close;
From.Result := Util.Beans.Objects.To_Object (Content);
end Configure_Database;
-- ------------------------------
-- Save the configuration.
-- ------------------------------
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Path : constant String := Ada.Strings.Unbounded.To_String (From.Path);
New_File : constant String := Path & ".tmp";
Output : Ada.Text_IO.File_Type;
procedure Read_Property (Line : in String) is
Pos : constant Natural := Util.Strings.Index (Line, '=');
begin
if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then
Ada.Text_IO.Put_Line (Output, Line);
return;
end if;
Ada.Text_IO.Put (Output, Line (Line'First .. Pos));
Ada.Text_IO.Put_Line (Output, From.Changed.Get (Line (Line'First .. Pos - 1)));
end Read_Property;
begin
Log.Info ("Saving configuration file {0}", Path);
From.Changed.Set ("database", From.Get_Database_URL);
Ada.Text_IO.Create (File => Output, Name => New_File);
Util.Files.Read_File (Path, Read_Property'Access);
Ada.Text_IO.Close (Output);
Ada.Directories.Delete_File (Path);
Ada.Directories.Rename (Old_Name => New_File,
New_Name => Path);
end Save;
-- Finish the setup and exit the setup.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Log.Info ("Finish configuration");
From.Done := True;
end Finish;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access is
begin
return Binding_Array'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Enter in the application setup
-- ------------------------------
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class) is
begin
Log.Info ("Entering configuration for {0}", Config);
App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config);
begin
App.Config.Load_Properties (Config);
Util.Log.Loggers.Initialize (Config);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file: {0}", Config);
end;
App.Initialize (App.Config, App.Factory);
App.Set_Error_Page (ASF.Responses.SC_NOT_FOUND, "/setup/install.html");
App.Set_Global ("contextPath", App.Config.Get ("contextPath"));
App.Set_Global ("setup",
Util.Beans.Objects.To_Object (App'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Add_Servlet (Name => "redirect",
Server => App.Redirect'Unchecked_Access);
App.Add_Servlet (Name => "faces",
Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files",
Server => App.Files'Unchecked_Access);
App.Add_Mapping (Pattern => "*.html",
Name => "redirect");
App.Add_Mapping (Pattern => "/setup/*.html",
Name => "faces");
App.Add_Mapping (Pattern => "*.css",
Name => "files");
App.Add_Mapping (Pattern => "*.js",
Name => "files");
declare
Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P);
Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths);
begin
ASF.Applications.Main.Configs.Read_Configuration (App, Path);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Setup configuration file '{0}' does not exist", Path);
end;
declare
URL : constant String := App.Config.Get ("google-plus.callback_url", "");
Pos : constant Natural := Util.Strings.Index (URL, '#');
begin
if Pos > 0 then
App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1));
else
App.Changed.Set ("callback_url", "http://mydomain.com/oauth");
end if;
end;
App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db"));
App.Driver := Util.Beans.Objects.To_Object (App.Database.Get_Driver);
Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access);
while not App.Done loop
delay 5.0;
end loop;
Server.Remove_Application (App'Unchecked_Access);
end Setup;
end AWA.Setup.Applications;
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Directories;
with Util.Files;
with Util.Processes;
with Util.Log.Loggers;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Strings;
with ASF.Events.Faces.Actions;
with ASF.Contexts.Faces;
with ASF.Applications.Main.Configs;
with ASF.Applications.Messages.Factory;
with AWA.Applications;
package body AWA.Setup.Applications is
use ASF.Applications;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications");
package Save_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Save,
Name => "save");
package Finish_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Finish,
Name => "finish");
package Configure_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application,
Method => Configure_Database,
Name => "configure_database");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Save_Binding.Proxy'Access,
Finish_Binding.Proxy'Access,
Configure_Binding.Proxy'Access);
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
Context_Path : constant String := Request.Get_Context_Path;
begin
Response.Send_Redirect (Context_Path & "/setup/install.html");
end Do_Get;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "database_name" then
return Util.Beans.Objects.To_Object (From.Database.Get_Database);
elsif Name = "database_server" then
return From.Db_Host;
elsif Name = "database_port" then
return From.Db_Port;
elsif Name = "database_user" then
return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user"));
elsif Name = "database_password" then
return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password"));
elsif Name = "database_driver" then
return From.Driver;
elsif Name = "database_root_user" then
return From.Root_User;
elsif Name = "database_root_password" then
return From.Root_Passwd;
elsif Name = "result" then
return From.Result;
end if;
if From.Changed.Exists (Name) then
return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name)));
end if;
declare
Param : constant String := From.Config.Get (Name);
begin
return Util.Beans.Objects.To_Object (Param);
end;
exception
when others =>
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "database_name" then
From.Database.Set_Database (Util.Beans.Objects.To_String (Value));
elsif Name = "database_server" then
From.Db_Host := Value;
elsif Name = "database_port" then
From.Db_Port := Value;
elsif Name = "database_user" then
From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value));
elsif Name = "database_password" then
From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value));
elsif Name = "database_driver" then
From.Driver := Value;
elsif Name = "database_root_user" then
From.Root_User := Value;
elsif Name = "database_root_password" then
From.Root_Passwd := Value;
elsif Name = "callback_url" then
From.Changed.Set (Name, Util.Beans.Objects.To_String (Value));
From.Changed.Set ("facebook.callback_url",
Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify");
From.Changed.Set ("google-plus.callback_url",
Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify");
else
From.Changed.Set (Name, Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Get the database connection string to be used by the application.
-- ------------------------------
function Get_Database_URL (From : in Application) return String is
use Ada.Strings.Unbounded;
Result : Ada.Strings.Unbounded.Unbounded_String;
Driver : constant String := Util.Beans.Objects.To_String (From.Driver);
User : constant String := From.Database.Get_Property ("user");
begin
if Driver = "" then
Append (Result, "mysql");
else
Append (Result, Driver);
end if;
Append (Result, "://");
if Driver /= "sqlite" then
Append (Result, From.Database.Get_Server);
if From.Database.Get_Port /= 0 then
Append (Result, ":");
Append (Result, Util.Strings.Image (From.Database.Get_Port));
end if;
end if;
Append (Result, "/");
Append (Result, From.Database.Get_Database);
if User /= "" then
Append (Result, "?user=");
Append (Result, User);
if From.Database.Get_Property ("password") /= "" then
Append (Result, "&password=");
Append (Result, From.Database.Get_Property ("password"));
end if;
end if;
if Driver = "sqlite" then
if User /= "" then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, "synchronous=OFF&encoding=UTF-8");
end if;
return To_String (Result);
end Get_Database_URL;
-- ------------------------------
-- Get the command to configure the database.
-- ------------------------------
function Get_Configure_Command (From : in Application) return String is
Driver : constant String := Util.Beans.Objects.To_String (From.Driver);
Database : constant String := From.Get_Database_URL;
Command : constant String := "dynamo create-database db '" & Database & "'";
Root : constant String := Util.Beans.Objects.To_String (From.Root_User);
Passwd : constant String := Util.Beans.Objects.To_String (From.Root_Passwd);
begin
if Root = "" then
return Command;
elsif Passwd = "" then
return Command & " " & Root;
else
return Command & " " & Root & " " & Passwd;
end if;
end Get_Configure_Command;
-- ------------------------------
-- Validate the database configuration parameters.
-- ------------------------------
procedure Validate (From : in out Application) is
Driver : constant String := Util.Beans.Objects.To_String (From.Driver);
begin
From.Has_Error := False;
if Driver = "sqlite" then
return;
end if;
begin
From.Database.Set_Port (Util.Beans.Objects.To_Integer (From.Db_Port));
exception
when others =>
From.Has_Error := True;
Messages.Factory.Add_Field_Message ("db-port", "setup.setup_database_port_error",
Messages.ERROR);
end;
begin
From.Database.Set_Server (Util.Beans.Objects.To_String (From.Db_Host));
exception
when others =>
From.Has_Error := True;
Messages.Factory.Add_Field_Message ("db-server", "setup.setup_database_host_error",
Messages.ERROR);
end;
end Validate;
-- ------------------------------
-- Configure the database.
-- ------------------------------
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
From.Validate;
if From.Has_Error then
Ada.Strings.Unbounded.Set_Unbounded_String (Outcome, "failure");
return;
end if;
declare
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
Command : constant String := From.Get_Configure_Command;
begin
Log.Info ("Configure database with {0}", Command);
Pipe.Open (Command, Util.Processes.READ);
Buffer.Initialize (null, Pipe'Unchecked_Access, 64*1024);
Buffer.Read (Content);
Pipe.Close;
From.Result := Util.Beans.Objects.To_Object (Content);
From.Has_Error := Pipe.Get_Exit_Status /= 0;
if From.Has_Error then
Messages.Factory.Add_Message ("setup.database_setup_error", Messages.ERROR);
end if;
end;
end Configure_Database;
-- ------------------------------
-- Save the configuration.
-- ------------------------------
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Path : constant String := Ada.Strings.Unbounded.To_String (From.Path);
New_File : constant String := Path & ".tmp";
Output : Ada.Text_IO.File_Type;
procedure Read_Property (Line : in String) is
Pos : constant Natural := Util.Strings.Index (Line, '=');
begin
if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then
Ada.Text_IO.Put_Line (Output, Line);
return;
end if;
Ada.Text_IO.Put (Output, Line (Line'First .. Pos));
Ada.Text_IO.Put_Line (Output, From.Changed.Get (Line (Line'First .. Pos - 1)));
end Read_Property;
begin
Log.Info ("Saving configuration file {0}", Path);
From.Changed.Set ("database", From.Get_Database_URL);
Ada.Text_IO.Create (File => Output, Name => New_File);
Util.Files.Read_File (Path, Read_Property'Access);
Ada.Text_IO.Close (Output);
Ada.Directories.Delete_File (Path);
Ada.Directories.Rename (Old_Name => New_File,
New_Name => Path);
end Save;
-- Finish the setup and exit the setup.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Log.Info ("Finish configuration");
From.Done := True;
end Finish;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access is
begin
return Binding_Array'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Enter in the application setup
-- ------------------------------
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class) is
begin
Log.Info ("Entering configuration for {0}", Config);
App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config);
begin
App.Config.Load_Properties (Config);
Util.Log.Loggers.Initialize (Config);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file: {0}", Config);
end;
App.Initialize (App.Config, App.Factory);
App.Set_Error_Page (ASF.Responses.SC_NOT_FOUND, "/setup/install.html");
App.Set_Global ("contextPath", App.Config.Get ("contextPath"));
App.Set_Global ("setup",
Util.Beans.Objects.To_Object (App'Unchecked_Access,
Util.Beans.Objects.STATIC));
App.Add_Servlet (Name => "redirect",
Server => App.Redirect'Unchecked_Access);
App.Add_Servlet (Name => "faces",
Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files",
Server => App.Files'Unchecked_Access);
App.Add_Mapping (Pattern => "*.html",
Name => "redirect");
App.Add_Mapping (Pattern => "/setup/*.html",
Name => "faces");
App.Add_Mapping (Pattern => "*.css",
Name => "files");
App.Add_Mapping (Pattern => "*.js",
Name => "files");
declare
Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P);
Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths);
begin
ASF.Applications.Main.Configs.Read_Configuration (App, Path);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Setup configuration file '{0}' does not exist", Path);
end;
declare
URL : constant String := App.Config.Get ("google-plus.callback_url", "");
Pos : constant Natural := Util.Strings.Index (URL, '#');
begin
if Pos > 0 then
App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1));
else
App.Changed.Set ("callback_url", "http://mydomain.com/oauth");
end if;
end;
App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db"));
App.Driver := Util.Beans.Objects.To_Object (App.Database.Get_Driver);
if App.Database.Get_Driver = "mysql" then
App.Db_Host := Util.Beans.Objects.To_Object (App.Database.Get_Server);
App.Db_Port := Util.Beans.Objects.To_Object (App.Database.Get_Port);
else
App.Db_Host := Util.Beans.Objects.To_Object (String '("localhost"));
App.Db_Port := Util.Beans.Objects.To_Object (Integer (3306));
end if;
Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access);
while not App.Done loop
delay 5.0;
end loop;
Server.Remove_Application (App'Unchecked_Access);
end Setup;
end AWA.Setup.Applications;
|
Implement the Validate procedure to check the database connection parameters Call the Validate procedure before doing the database configuration
|
Implement the Validate procedure to check the database connection parameters
Call the Validate procedure before doing the database configuration
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
bf99dd9fe3b257bbdfcac2b6dbf00e3b1d486cfe
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for 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 ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Send_Invitation (Bean);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
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 Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (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 Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Master_Session := Into.Module.Get_Master_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
AWA.Workspaces.Modules.Get_Workspace (Session, Ctx, WS);
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
Count_Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for 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 ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Ref (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Send_Invitation (Bean);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
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 Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (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 Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Master_Session := Into.Module.Get_Master_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
AWA.Workspaces.Modules.Get_Workspace (Session, Ctx, WS);
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
Count_Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
Implement the Get_Value function and get the inviter when we load the invitation
|
Implement the Get_Value function and get the inviter when we load the invitation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
31676915bd45a463dbd2f8d65f404ec700e3c67d
|
src/http/util-http-clients-mockups.ads
|
src/http/util-http-clients-mockups.ads
|
-----------------------------------------------------------------------
-- util-http-clients-mockups -- HTTP Clients mockups
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Http.Clients;
with Ada.Strings.Unbounded;
package Util.Http.Clients.Mockups is
-- Register the Http manager.
procedure Register;
-- Set the path of the file that contains the response for the next
-- <b>Do_Get</b> and <b>Do_Post</b> calls.
procedure Set_File (Path : in String);
private
type File_Http_Manager is new Http_Manager with record
File : Ada.Strings.Unbounded.Unbounded_String;
end record;
type File_Http_Manager_Access is access all File_Http_Manager'Class;
procedure Create (Manager : in File_Http_Manager;
Http : in out Client'Class);
procedure Do_Get (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
procedure Do_Post (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
end Util.Http.Clients.Mockups;
|
-----------------------------------------------------------------------
-- util-http-clients-mockups -- HTTP Clients mockups
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Http.Clients;
with Ada.Strings.Unbounded;
package Util.Http.Clients.Mockups is
-- Register the Http manager.
procedure Register;
-- Set the path of the file that contains the response for the next
-- <b>Do_Get</b> and <b>Do_Post</b> calls.
procedure Set_File (Path : in String);
private
type File_Http_Manager is new Http_Manager with record
File : Ada.Strings.Unbounded.Unbounded_String;
end record;
type File_Http_Manager_Access is access all File_Http_Manager'Class;
procedure Create (Manager : in File_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
end Util.Http.Clients.Mockups;
|
Declare and override the Do_Put procedure
|
Declare and override the Do_Put procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
378e5dc75b85743e6de69d9d2eaf48c166b4e3ac
|
src/http/aws/util-http-clients-web.ads
|
src/http/aws/util-http-clients-web.ads
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
private with AWS.Headers;
private with AWS.Response;
package Util.Http.Clients.Web is
-- Register the Http manager.
procedure Register;
private
type AWS_Http_Manager is new Http_Manager with null record;
type AWS_Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
type AWS_Http_Request is new Http_Request with record
Headers : AWS.Headers.List;
end record;
type AWS_Http_Request_Access is access all AWS_Http_Request'Class;
-- Returns a boolean indicating whether the named request header has already
-- been set.
overriding
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean;
-- 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;
-- 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);
-- 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);
-- 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));
type AWS_Http_Response is new Http_Response with record
Data : AWS.Response.Data;
end record;
type AWS_Http_Response_Access is access all AWS_Http_Response'Class;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String;
-- 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);
-- 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);
-- 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));
-- Get the response body as a string.
function Get_Body (Reply : in AWS_Http_Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural;
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.
-----------------------------------------------------------------------
private with AWS.Headers;
private with AWS.Response;
package Util.Http.Clients.Web is
-- Register the Http manager.
procedure Register;
private
type AWS_Http_Manager is new Http_Manager with null record;
type AWS_Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
-- Set the timeout for the connection.
overriding
procedure Set_Timeout (Manager : in AWS_Http_Manager;
Http : in Client'Class;
Timeout : in Duration);
type AWS_Http_Request is new Http_Request with record
Headers : AWS.Headers.List;
end record;
type AWS_Http_Request_Access is access all AWS_Http_Request'Class;
-- Returns a boolean indicating whether the named request header has already
-- been set.
overriding
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean;
-- 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;
-- 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);
-- 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);
-- 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));
type AWS_Http_Response is new Http_Response with record
Data : AWS.Response.Data;
end record;
type AWS_Http_Response_Access is access all AWS_Http_Response'Class;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String;
-- 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);
-- 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);
-- 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));
-- Get the response body as a string.
function Get_Body (Reply : in AWS_Http_Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural;
end Util.Http.Clients.Web;
|
Declare the Set_Timeout procedure
|
Declare the Set_Timeout procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
560eff37d2893ed598e42721e862521e5b653bf5
|
mat/src/mat-formats.adb
|
mat/src/mat-formats.adb
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Formats is
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value);
begin
return Hex;
end Addr;
end MAT.Formats;
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Formats is
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value);
begin
return Hex;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
end MAT.Formats;
|
Implement the Size function to format sizes
|
Implement the Size function to format sizes
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
134947f63f082a4bf188d07ac3a1d9aa2ac02630
|
mat/src/mat-targets.adb
|
mat/src/mat-targets.adb
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- 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.Readers;
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Targets.Readers.Initialize (Target => Target,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Process : out Target_Process_Type_Access) is
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create;
Target.Processes.Insert (Pid, Process);
end if;
if Target.Current = null then
Target.Current := Process;
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- 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.Readers;
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Set the console instance.
-- ------------------------------
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access) is
begin
Target.Console := Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Targets.Readers.Initialize (Target => Target,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Process : out Target_Process_Type_Access) is
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create;
Target.Processes.Insert (Pid, Process);
end if;
if Target.Current = null then
Target.Current := Process;
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
end MAT.Targets;
|
Implement the Console procedure
|
Implement the Console procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
3f325a91c54c3725c18fc7b6026523be993748f1
|
src/wiki-plugins.ads
|
src/wiki-plugins.ads
|
-----------------------------------------------------------------------
-- wiki-plugins -- Wiki plugins
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
-- == 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 Wiki_Plugin is limited interface;
-- Expand the plugin configured with the parameters for the document.
procedure Expand (Plugin : in out Wiki_Plugin;
Document : in out Wiki.Documents.Document_Reader'Class;
Params : in out Wiki.Attributes.Attribute_List_Type) is abstract;
end Wiki.Plugins;
|
-----------------------------------------------------------------------
-- wiki-plugins -- Wiki plugins
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
-- == 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 Wiki_Plugin is limited interface;
type Wiki_Plugin_Access is access all Wiki_Plugin'Class;
-- Expand the plugin configured with the parameters for the document.
procedure Expand (Plugin : in out Wiki_Plugin;
Document : in out Wiki.Documents.Document_Reader'Class;
Params : in out Wiki.Attributes.Attribute_List_Type) is abstract;
end Wiki.Plugins;
|
Declare Wiki_Plugin_Access access type
|
Declare Wiki_Plugin_Access access type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
c3772c462ab30f53c16ee2e646c026fe54a6fa70
|
src/wiki-streams.ads
|
src/wiki-streams.ads
|
-----------------------------------------------------------------------
-- wiki-streams -- Wiki input and output streams
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
-- == Input and Output streams {#wiki-streams} ==
-- The `Wiki.Streams` package defines the interfaces used by
-- the parser or renderer to read and write their outputs.
--
-- The `Input_Stream` interface defines the interface that must be implemented to
-- read the source Wiki content. The `Read` procedure is called by the parser
-- repeatedly while scanning the Wiki content.
--
-- The `Output_Stream` interface is the interface used by the renderer
-- to write their outputs. It defines the `Write` procedure to write
-- a single character or a string.
--
-- @include wiki-streams-html.ads
-- @include wiki-streams-builders.ads
-- @include wiki-streams-html-builders.ads
-- @include wiki-streams-text_io.ads
-- @include wiki-streams-html-text_io.ads
package Wiki.Streams is
pragma Preelaborate;
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- 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 Wiki.Strings.WChar;
Eof : out Boolean) is abstract;
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the string to the output stream.
procedure Write (Stream : in out Output_Stream;
Content : in Wiki.Strings.WString) is abstract;
-- Write a single character to the output stream.
procedure Write (Stream : in out Output_Stream;
Char : in Wiki.Strings.WChar) is abstract;
end Wiki.Streams;
|
-----------------------------------------------------------------------
-- wiki-streams -- Wiki input and output streams
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
-- == Input and Output streams {#wiki-streams} ==
-- The `Wiki.Streams` package defines the interfaces used by
-- the parser or renderer to read and write their outputs.
--
-- The `Input_Stream` interface defines the interface that must be implemented to
-- read the source Wiki content. The `Read` procedure is called by the parser
-- repeatedly while scanning the Wiki content.
--
-- The `Output_Stream` interface is the interface used by the renderer
-- to write their outputs. It defines the `Write` procedure to write
-- a single character or a string.
--
-- @include wiki-streams-html.ads
-- @include wiki-streams-builders.ads
-- @include wiki-streams-html-builders.ads
-- @include wiki-streams-text_io.ads
-- @include wiki-streams-html-text_io.ads
package Wiki.Streams is
pragma Preelaborate;
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- Read the input stream and fill the `Into` buffer until either it is full or
-- we reach the end of line. Returns in `Last` the last valid position in the
-- `Into` buffer. When there is no character to read, return True in
-- the `Eof` indicator.
procedure Read (Input : in out Input_Stream;
Into : in out Wiki.Strings.WString;
Last : out Natural;
Eof : out Boolean) is abstract;
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the string to the output stream.
procedure Write (Stream : in out Output_Stream;
Content : in Wiki.Strings.WString) is abstract;
-- Write a single character to the output stream.
procedure Write (Stream : in out Output_Stream;
Char : in Wiki.Strings.WChar) is abstract;
end Wiki.Streams;
|
Change the Read procedure to read in a text builder and read a complete line
|
Change the Read procedure to read in a text builder and read a complete line
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
258c841c65d5415e178634e2110875a9791de904
|
regtests/wiki-tests.adb
|
regtests/wiki-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- Copyright (C) 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Ada.Characters.Conversions;
with Util.Files;
with Util.Measures;
with Wiki.Render.Wiki;
with Wiki.Filters.Html;
with Wiki.Streams.Html.Builders;
with Wiki.Streams.Builders;
with Wiki.Utils;
with Wiki.Documents;
with Wiki.Parsers;
package body Wiki.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
function To_Wide (Item : in String) return Wide_Wide_String
renames Ada.Characters.Conversions.To_Wide_Wide_String;
Result_File : constant String := To_String (T.Result);
Content : Unbounded_String;
begin
Util.Files.Read_File (Path => To_String (T.File),
Into => Content,
Max_Size => 10000);
declare
Time : Util.Measures.Stamp;
begin
if T.Source = Wiki.SYNTAX_HTML then
declare
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Writer : aliased Wiki.Streams.Builders.Output_Builder_Stream;
Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer;
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
begin
Renderer.Set_Output_Stream (Writer'Unchecked_Access, T.Format);
Engine.Add_Filter (Html_Filter'Unchecked_Access);
Engine.Set_Syntax (Wiki.SYNTAX_HTML);
Engine.Parse (To_Wide (To_String (Content)), Doc);
Renderer.Render (Doc);
Content := To_Unbounded_String (Writer.To_String);
end;
elsif T.Is_Html then
Content := To_Unbounded_String
(Utils.To_Html (To_Wide (To_String (Content)), T.Format));
else
Content := To_Unbounded_String
(Utils.To_Text (To_Wide (To_String (Content)), T.Format));
end if;
Util.Measures.Report (Time, "Render " & To_String (T.Name));
end;
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Render");
end Test_Render;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : in Test) return Util.Tests.Message_String is
begin
if T.Source = Wiki.SYNTAX_HTML then
return Util.Tests.Format ("Test IMPORT " & To_String (T.Name));
elsif T.Is_Html then
return Util.Tests.Format ("Test HTML " & To_String (T.Name));
else
return Util.Tests.Format ("Test TEXT " & To_String (T.Name));
end if;
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Render;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
procedure Add_Import_Tests;
procedure Add_Wiki_Tests;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Expect_Dir : constant String := "regtests/expect";
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access is
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path);
Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name);
Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name);
Tst.Format := Format;
Tst.Source := Format;
return Tst;
end Create_Test;
procedure Add_Wiki_Tests is
Dir : constant String := "regtests/files/wiki";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Ext : constant String := Ada.Directories.Extension (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
else
Format := Wiki.SYNTAX_MIX;
end if;
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Wiki_Tests;
procedure Add_Import_Tests is
Dir : constant String := "regtests/files/html";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when others =>
Tst := null;
end case;
if Tst /= null then
Tst.Source := Wiki.SYNTAX_HTML;
Suite.Add_Test (Tst.all'Access);
end if;
end loop;
end if;
end;
end loop;
end Add_Import_Tests;
begin
Add_Wiki_Tests;
Add_Import_Tests;
end Add_Tests;
end Wiki.Tests;
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for AWA Wiki rendering
-- Copyright (C) 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Ada.Characters.Conversions;
with Util.Measures;
with Wiki.Render.Wiki;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Plugins.Templates;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
with Wiki.Documents;
with Wiki.Parsers;
package body Wiki.Tests is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Test rendering a wiki text in HTML or text.
-- ------------------------------
procedure Test_Render (T : in out Test) is
use Ada.Directories;
Result_File : constant String := To_String (T.Result);
Dir : constant String := Containing_Directory (Result_File);
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter;
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream;
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Input.Open (Path => To_String (T.File),
Form => "WCEM=8");
Output.Create (Result_File, "WCEM=8");
Template.Set_Template_Path (Containing_Directory (To_String (T.File)));
declare
Time : Util.Measures.Stamp;
begin
Engine.Set_Syntax (T.Source);
Engine.Set_Plugin_Factory (Template'Unchecked_Access);
Engine.Add_Filter (Toc_Filter'Unchecked_Access);
Engine.Add_Filter (Html_Filter'Unchecked_Access);
Engine.Parse (Input'Unchecked_Access, Doc);
Util.Measures.Report (Time, "Parse " & To_String (T.Name));
if T.Source = Wiki.SYNTAX_HTML then
declare
Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name));
end;
elsif T.Is_Html then
declare
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render HTML " & To_String (T.Name));
end;
else
declare
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
Output.Close;
Util.Measures.Report (Time, "Render Text " & To_String (T.Name));
end;
end if;
end;
Input.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Render");
end Test_Render;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : in Test) return Util.Tests.Message_String is
begin
if T.Source = Wiki.SYNTAX_HTML then
return Util.Tests.Format ("Test IMPORT " & To_String (T.Name));
elsif T.Is_Html then
return Util.Tests.Format ("Test HTML " & To_String (T.Name));
else
return Util.Tests.Format ("Test TEXT " & To_String (T.Name));
end if;
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Render;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
procedure Add_Import_Tests;
procedure Add_Wiki_Tests;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access;
Result_Dir : constant String := "regtests/result";
Expect_Dir : constant String := "regtests/expect";
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
function Create_Test (Name : in String;
Path : in String;
Format : in Wiki.Wiki_Syntax;
Prefix : in String;
Is_Html : in Boolean) return Test_Case_Access is
Tst : Test_Case_Access;
begin
Tst := new Test;
Tst.Is_Html := Is_Html;
Tst.Name := To_Unbounded_String (Name);
Tst.File := To_Unbounded_String (Path);
Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name);
Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name);
Tst.Format := Format;
Tst.Source := Format;
return Tst;
end Create_Test;
procedure Add_Wiki_Tests is
Dir : constant String := "regtests/files/wiki";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Ext : constant String := Ada.Directories.Extension (Simple);
Tst : Test_Case_Access;
Format : Wiki.Wiki_Syntax;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
if Ext = "wiki" then
Format := Wiki.SYNTAX_GOOGLE;
elsif Ext = "dotclear" then
Format := Wiki.SYNTAX_DOTCLEAR;
elsif Ext = "creole" then
Format := Wiki.SYNTAX_CREOLE;
elsif Ext = "phpbb" then
Format := Wiki.SYNTAX_PHPBB;
elsif Ext = "mediawiki" then
Format := Wiki.SYNTAX_MEDIA_WIKI;
else
Format := Wiki.SYNTAX_MIX;
end if;
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True);
Suite.Add_Test (Tst.all'Access);
Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Wiki_Tests;
procedure Add_Import_Tests is
Dir : constant String := "regtests/files/html";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Name : constant String := Base_Name (Simple);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" and then Simple (Simple'Last) /= '~'
then
for Syntax in Wiki.Wiki_Syntax'Range loop
case Syntax is
when Wiki.SYNTAX_CREOLE =>
Tst := Create_Test (Name & ".creole", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_DOTCLEAR =>
Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when Wiki.SYNTAX_MEDIA_WIKI =>
Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple,
Syntax, "/wiki-import/", True);
when others =>
Tst := null;
end case;
if Tst /= null then
Tst.Source := Wiki.SYNTAX_HTML;
Suite.Add_Test (Tst.all'Access);
end if;
end loop;
end if;
end;
end loop;
end Add_Import_Tests;
begin
Add_Wiki_Tests;
Add_Import_Tests;
end Add_Tests;
end Wiki.Tests;
|
Update the unit test to use the Text_IO streams to read and write the result
|
Update the unit test to use the Text_IO streams to read and write the result
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
5b68835cd191eadd348e3ed00f984b4b1aaac98d
|
orka_transforms/src/orka-transforms-simd_quaternions.adb
|
orka_transforms/src/orka-transforms-simd_quaternions.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics.Generic_Elementary_Functions;
package body Orka.Transforms.SIMD_Quaternions is
package EF is new Ada.Numerics.Generic_Elementary_Functions (Vectors.Element_Type);
function Vector_Part (Elements : Quaternion) return Vector4 is
begin
return Result : Vector4 := Vector4 (Elements) do
Result (W) := 0.0;
end return;
end Vector_Part;
function "+" (Left, Right : Quaternion) return Quaternion is
use Vectors;
begin
return Quaternion (Vector4 (Left) + Vector4 (Right));
end "+";
function "*" (Left, Right : Quaternion) return Quaternion is
use Vectors;
Lv : constant Vector4 := Vector_Part (Left);
Rv : constant Vector4 := Vector_Part (Right);
Ls : constant Vectors.Element_Type := Left (W);
Rs : constant Vectors.Element_Type := Right (W);
V : constant Vector4 := Ls * Rv + Rs * Lv + Vectors.Cross (Lv, Rv);
S : constant Element_Type := Ls * Rs - Vectors.Dot (Lv, Rv);
begin
return Result : Quaternion := Quaternion (V) do
Result (W) := S;
end return;
end "*";
function "*" (Left : Vectors.Element_Type; Right : Quaternion) return Quaternion is
use Vectors;
begin
return Quaternion (Left * Vector4 (Right));
end "*";
function "*" (Left : Quaternion; Right : Vectors.Element_Type) return Quaternion is
(Right * Left);
-- Scalar multiplication is commutative
function Conjugate (Elements : Quaternion) return Quaternion is
Element_W : constant Vectors.Element_Type := Elements (W);
use Vectors;
begin
return Result : Quaternion := Quaternion (-Vector4 (Elements)) do
Result (W) := Element_W;
end return;
end Conjugate;
function Inverse (Elements : Quaternion) return Quaternion is
Length : constant Vectors.Element_Type := Vectors.Magnitude2 (Vector4 (Elements));
begin
return Quaternion (Vectors.Divide_Or_Zero
(Vector4 (Conjugate (Elements)), (Length, Length, Length, Length)));
end Inverse;
function Norm (Elements : Quaternion) return Vectors.Element_Type is
(Vectors.Magnitude (Vector4 (Elements)));
function Normalize (Elements : Quaternion) return Quaternion is
(Quaternion (Vectors.Normalize (Vector4 (Elements))));
function Normalized (Elements : Quaternion) return Boolean is
(Vectors.Normalized (Vector4 (Elements)));
function To_Axis_Angle (Elements : Quaternion) return Axis_Angle is
use type Vectors.Element_Type;
Angle : constant Vectors.Element_Type := EF.Arccos (Elements (W)) * 2.0;
SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0);
begin
if SA /= 0.0 then
declare
use Vectors;
Axis : Vector4 := Vector4 (Elements) * (1.0 / SA);
begin
Axis (W) := 0.0;
return (Axis => Axis, Angle => Angle);
end;
else
-- Singularity occurs when angle is 0. Return an arbitrary axis
return (Axis => (1.0, 0.0, 0.0, 0.0), Angle => 0.0);
end if;
end To_Axis_Angle;
function R
(Axis : Vector4;
Angle : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
CA : constant Vectors.Element_Type := EF.Cos (Angle / 2.0);
SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0);
use Vectors;
begin
return Result : Quaternion := Quaternion (Axis * SA) do
Result (W) := CA;
end return;
end R;
function R (Left, Right : Vector4) return Quaternion is
use type Vectors.Element_Type;
S : constant Vector4 := Vectors.Normalize (Left);
T : constant Vector4 := Vectors.Normalize (Right);
E : constant Vectors.Element_Type := Vectors.Dot (S, T);
SRE : constant Vectors.Element_Type := EF.Sqrt (2.0 * (1.0 + E));
use Vectors;
begin
-- Division by zero if Left and Right are in opposite direction.
-- Use rotation axis perpendicular to s and angle of 180 degrees
if SRE /= 0.0 then
-- Equation 4.53 from chapter 4.3 Quaternions from Real-Time Rendering
-- (third edition, 2008)
declare
Result : Quaternion := Quaternion ((1.0 / SRE) * Vectors.Cross (S, T));
begin
Result (W) := SRE / 2.0;
return Normalize (Result);
end;
else
if abs S (Z) < abs S (X) then
return R ((S (Y), -S (X), 0.0, 0.0), Ada.Numerics.Pi);
else
return R ((0.0, -S (Z), S (Y), 0.0), Ada.Numerics.Pi);
end if;
end if;
end R;
function Difference (Left, Right : Quaternion) return Quaternion is
begin
return Right * Conjugate (Left);
end Difference;
procedure Rotate_At_Origin
(Vector : in out Vector4;
Elements : Quaternion)
is
Result : Vectors.Vector_Type;
begin
Result := Vectors.Vector_Type (Elements * Quaternion (Vector) * Conjugate (Elements));
Vector := Result;
end Rotate_At_Origin;
function Lerp
(Left, Right : Quaternion;
Time : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
begin
return Normalize ((1.0 - Time) * Left + Time * Right);
end Lerp;
function Slerp
(Left, Right : Quaternion;
Time : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
Cos_Angle : constant Vectors.Element_Type := Vectors.Dot (Vector4 (Left), Vector4 (Right));
Angle : constant Vectors.Element_Type := EF.Arccos (Cos_Angle);
SA : constant Vectors.Element_Type := EF.Sin (Angle);
SL : constant Vectors.Element_Type := EF.Sin ((1.0 - Time) * Angle);
SR : constant Vectors.Element_Type := EF.Sin (Time * Angle);
use Vectors;
begin
return Normalize ((SL / SA) * Left + (SR / SA) * Right);
end Slerp;
end Orka.Transforms.SIMD_Quaternions;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics.Generic_Elementary_Functions;
package body Orka.Transforms.SIMD_Quaternions is
package EF is new Ada.Numerics.Generic_Elementary_Functions (Vectors.Element_Type);
function Vector_Part (Elements : Quaternion) return Vector4 is
begin
return Result : Vector4 := Vector4 (Elements) do
Result (W) := 0.0;
end return;
end Vector_Part;
function "+" (Left, Right : Quaternion) return Quaternion is
use Vectors;
begin
return Quaternion (Vector4 (Left) + Vector4 (Right));
end "+";
function "*" (Left, Right : Quaternion) return Quaternion is
use Vectors;
Lv : constant Vector4 := Vector_Part (Left);
Rv : constant Vector4 := Vector_Part (Right);
Ls : constant Vectors.Element_Type := Left (W);
Rs : constant Vectors.Element_Type := Right (W);
V : constant Vector4 := Ls * Rv + Rs * Lv + Vectors.Cross (Lv, Rv);
S : constant Element_Type := Ls * Rs - Vectors.Dot (Lv, Rv);
begin
return Result : Quaternion := Quaternion (V) do
Result (W) := S;
end return;
end "*";
function "*" (Left : Vectors.Element_Type; Right : Quaternion) return Quaternion is
use Vectors;
begin
return Quaternion (Left * Vector4 (Right));
end "*";
function "*" (Left : Quaternion; Right : Vectors.Element_Type) return Quaternion is
(Right * Left);
-- Scalar multiplication is commutative
function Conjugate (Elements : Quaternion) return Quaternion is
Element_W : constant Vectors.Element_Type := Elements (W);
use Vectors;
begin
return Result : Quaternion := Quaternion (-Vector4 (Elements)) do
Result (W) := Element_W;
end return;
end Conjugate;
function Inverse (Elements : Quaternion) return Quaternion is
Length : constant Vectors.Element_Type := Vectors.Magnitude2 (Vector4 (Elements));
begin
return Quaternion (Vectors.Divide_Or_Zero
(Vector4 (Conjugate (Elements)), (Length, Length, Length, Length)));
end Inverse;
function Norm (Elements : Quaternion) return Vectors.Element_Type is
(Vectors.Magnitude (Vector4 (Elements)));
function Normalize (Elements : Quaternion) return Quaternion is
(Quaternion (Vectors.Normalize (Vector4 (Elements))));
function Normalized (Elements : Quaternion) return Boolean is
(Vectors.Normalized (Vector4 (Elements)));
function To_Axis_Angle (Elements : Quaternion) return Axis_Angle is
use type Vectors.Element_Type;
Angle : constant Vectors.Element_Type := EF.Arccos (Elements (W)) * 2.0;
SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0);
begin
if SA /= 0.0 then
declare
use Vectors;
Axis : Vector4 := Vector4 (Elements) * (1.0 / SA);
begin
Axis (W) := 0.0;
return (Axis => Axis, Angle => Angle);
end;
else
-- Singularity occurs when angle is 0. Return an arbitrary axis
return (Axis => (1.0, 0.0, 0.0, 0.0), Angle => 0.0);
end if;
end To_Axis_Angle;
function R
(Axis : Vector4;
Angle : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
CA : constant Vectors.Element_Type := EF.Cos (Angle / 2.0);
SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0);
use Vectors;
Result : Quaternion := Quaternion (Axis * SA);
begin
Result (W) := CA;
return Normalize (Result);
end R;
function R (Left, Right : Vector4) return Quaternion is
use type Vectors.Element_Type;
S : constant Vector4 := Vectors.Normalize (Left);
T : constant Vector4 := Vectors.Normalize (Right);
E : constant Vectors.Element_Type := Vectors.Dot (S, T);
SRE : constant Vectors.Element_Type := EF.Sqrt (2.0 * (1.0 + E));
use Vectors;
begin
-- Division by zero if Left and Right are in opposite direction.
-- Use rotation axis perpendicular to s and angle of 180 degrees
if SRE /= 0.0 then
-- Equation 4.53 from chapter 4.3 Quaternions from Real-Time Rendering
-- (third edition, 2008)
declare
Result : Quaternion := Quaternion ((1.0 / SRE) * Vectors.Cross (S, T));
begin
Result (W) := SRE / 2.0;
return Normalize (Result);
end;
else
if abs S (Z) < abs S (X) then
return R ((S (Y), -S (X), 0.0, 0.0), Ada.Numerics.Pi);
else
return R ((0.0, -S (Z), S (Y), 0.0), Ada.Numerics.Pi);
end if;
end if;
end R;
function Difference (Left, Right : Quaternion) return Quaternion is
begin
return Right * Conjugate (Left);
end Difference;
procedure Rotate_At_Origin
(Vector : in out Vector4;
Elements : Quaternion)
is
Result : Vectors.Vector_Type;
begin
Result := Vectors.Vector_Type (Elements * Quaternion (Vector) * Conjugate (Elements));
Vector := Result;
end Rotate_At_Origin;
function Lerp
(Left, Right : Quaternion;
Time : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
begin
return Normalize ((1.0 - Time) * Left + Time * Right);
end Lerp;
function Slerp
(Left, Right : Quaternion;
Time : Vectors.Element_Type) return Quaternion
is
use type Vectors.Element_Type;
Cos_Angle : constant Vectors.Element_Type := Vectors.Dot (Vector4 (Left), Vector4 (Right));
Angle : constant Vectors.Element_Type := EF.Arccos (Cos_Angle);
SA : constant Vectors.Element_Type := EF.Sin (Angle);
SL : constant Vectors.Element_Type := EF.Sin ((1.0 - Time) * Angle);
SR : constant Vectors.Element_Type := EF.Sin (Time * Angle);
use Vectors;
begin
return Normalize ((SL / SA) * Left + (SR / SA) * Right);
end Slerp;
end Orka.Transforms.SIMD_Quaternions;
|
Normalize result in function R to satisfy post condition
|
transforms: Normalize result in function R to satisfy post condition
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
319f41e7cdaa7314b4ec6ee640272e297eb4a89f
|
awa/awaunit/awa-tests.adb
|
awa/awaunit/awa-tests.adb
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
with AWA.Tests.Helpers.Users;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
-- ------------------------------
-- Cleanup after the test execution.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
pragma Unreferenced (T);
begin
AWA.Tests.Helpers.Users.Tear_Down;
end Tear_Down;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Application.Close;
Free (Application);
end if;
ASF.Tests.Finish (Status);
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
pragma Unreferenced (Add_Modules);
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
Application.Start;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access);
end Initialize_Filters;
end AWA.Tests;
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
with AWA.Tests.Helpers.Users;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
-- ------------------------------
-- Cleanup after the test execution.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
pragma Unreferenced (T);
begin
AWA.Tests.Helpers.Users.Tear_Down;
end Tear_Down;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Application.Close;
Free (Application);
end if;
ASF.Tests.Finish (Status);
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
pragma Unreferenced (Add_Modules);
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
Application.Start;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access);
end Initialize_Filters;
end AWA.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
64577003ca72fa84e85b6292b54c5845f0f5d310
|
matp/src/mat-types.adb
|
matp/src/mat-types.adb
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- 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.Types is
-- ------------------------------
-- Return an hexadecimal string representation of the value.
-- ------------------------------
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String is
use type Interfaces.Unsigned_32;
Conversion : constant String (1 .. 16) := "0123456789ABCDEF";
S : String (1 .. Length) := (others => '0');
P : Uint32 := Value;
N : Uint32;
I : Positive := Length;
begin
while P /= 0 loop
N := P mod 16;
P := P / 16;
S (I) := Conversion (Natural (N + 1));
exit when I = 1;
I := I - 1;
end loop;
return S;
end Hex_Image;
-- ------------------------------
-- Return an hexadecimal string representation of the value.
-- ------------------------------
function Hex_Image (Value : in Uint64;
Length : in Positive := 16) return String is
use type Interfaces.Unsigned_64;
Conversion : constant String (1 .. 16) := "0123456789ABCDEF";
S : String (1 .. Length) := (others => '0');
P : Uint64 := Value;
N : Uint64;
I : Positive := Length;
begin
while P /= 0 loop
N := P mod 16;
P := P / 16;
S (I) := Conversion (Natural (N + 1));
exit when I = 1;
I := I - 1;
end loop;
return S;
end Hex_Image;
-- ------------------------------
-- Format the target time to a printable representation.
-- ------------------------------
function Tick_Image (Value : in Target_Tick_Ref) return String is
use Interfaces;
Sec : constant Unsigned_32 := Unsigned_32 (Interfaces.Shift_Right (Uint64 (Value), 32));
Usec : constant Unsigned_32 := Interfaces.Unsigned_32 (Value and 16#0ffffffff#);
Frac : constant String := Interfaces.Unsigned_32'Image (Usec);
Img : String (1 .. 6) := (others => '0');
begin
Img (Img'Last - Frac'Length + 2 .. Img'Last) := Frac (Frac'First + 1 .. Frac'Last);
return Interfaces.Unsigned_32'Image (Sec) & "." & Img;
end Tick_Image;
function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref is
use Interfaces;
Res : Target_Tick_Ref := Target_Tick_Ref (Uint64 (Left) - Uint64 (Right));
Usec1 : constant Unsigned_32 := Interfaces.Unsigned_32 (Left and 16#0ffffffff#);
Usec2 : constant Unsigned_32 := Interfaces.Unsigned_32 (Right and 16#0ffffffff#);
begin
if Usec1 < Usec2 then
Res := Res and 16#ffffffff00000000#;
Res := Target_Tick_Ref (Uint64 (Res) - 16#100000000#);
Res := Res or Target_Tick_Ref (1000000 - (Usec2 - Usec1));
end if;
return Res;
end "-";
-- ------------------------------
-- Convert the hexadecimal string into an unsigned integer.
-- ------------------------------
function Hex_Value (Value : in String) return Uint64 is
use type Interfaces.Unsigned_64;
Result : Uint64 := 0;
begin
if Value'Length = 0 then
raise Constraint_Error with "Empty string";
end if;
for I in Value'Range loop
declare
C : constant Character := Value (I);
begin
if C >= '0' and C <= '9' then
Result := (Result * 16) + (Character'Pos (C) - Character'Pos ('0'));
elsif C >= 'A' and C <= 'F' then
Result := (Result * 16) + (Character'Pos (C) - Character'Pos ('A') + 10);
elsif C >= 'a' and C <= 'f' then
Result := (Result * 16) + (Character'Pos (C) - Character'Pos ('a') + 10);
else
raise Constraint_Error with "Invalid character: " & C;
end if;
end;
end loop;
return Result;
end Hex_Value;
end MAT.Types;
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- 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.Types is
-- ------------------------------
-- Return an hexadecimal string representation of the value.
-- ------------------------------
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String is
use type Interfaces.Unsigned_32;
Conversion : constant String (1 .. 16) := "0123456789ABCDEF";
S : String (1 .. Length) := (others => '0');
P : Uint32 := Value;
N : Uint32;
I : Positive := Length;
begin
while P /= 0 loop
N := P mod 16;
P := P / 16;
S (I) := Conversion (Natural (N + 1));
exit when I = 1;
I := I - 1;
end loop;
return S;
end Hex_Image;
-- ------------------------------
-- Return an hexadecimal string representation of the value.
-- ------------------------------
function Hex_Image (Value : in Uint64;
Length : in Positive := 16) return String is
use type Interfaces.Unsigned_64;
Conversion : constant String (1 .. 16) := "0123456789ABCDEF";
S : String (1 .. Length) := (others => '0');
P : Uint64 := Value;
N : Uint64;
I : Positive := Length;
begin
while P /= 0 loop
N := P mod 16;
P := P / 16;
S (I) := Conversion (Natural (N + 1));
exit when I = 1;
I := I - 1;
end loop;
return S;
end Hex_Image;
-- ------------------------------
-- Format the target time to a printable representation.
-- ------------------------------
function Tick_Image (Value : in Target_Tick_Ref) return String is
use Interfaces;
Sec : constant Unsigned_32 := Unsigned_32 (Interfaces.Shift_Right (Uint64 (Value), 32));
Usec : constant Unsigned_32 := Interfaces.Unsigned_32 (Value and 16#0ffffffff#);
Frac : constant String := Interfaces.Unsigned_32'Image (Usec);
Img : String (1 .. 6) := (others => '0');
begin
Img (Img'Last - Frac'Length + 2 .. Img'Last) := Frac (Frac'First + 1 .. Frac'Last);
return Interfaces.Unsigned_32'Image (Sec) & "." & Img;
end Tick_Image;
-- ------------------------------
-- Convert the hexadecimal string into an unsigned integer.
-- ------------------------------
function Hex_Value (Value : in String) return Uint64 is
use type Interfaces.Unsigned_64;
Result : Uint64 := 0;
begin
if Value'Length = 0 then
raise Constraint_Error with "Empty string";
end if;
for I in Value'Range loop
declare
C : constant Character := Value (I);
begin
if C >= '0' and C <= '9' then
Result := (Result * 16) + (Character'Pos (C) - Character'Pos ('0'));
elsif C >= 'A' and C <= 'F' then
Result := (Result * 16) + (Character'Pos (C) - Character'Pos ('A') + 10);
elsif C >= 'a' and C <= 'f' then
Result := (Result * 16) + (Character'Pos (C) - Character'Pos ('a') + 10);
else
raise Constraint_Error with "Invalid character: " & C;
end if;
end;
end loop;
return Result;
end Hex_Value;
end MAT.Types;
|
Remove the "-" function
|
Remove the "-" function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
8982769b18f1839639b13854c2e96e73d0c928b4
|
src/asf-components-widgets-factory.adb
|
src/asf-components-widgets-factory.adb
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- 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.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
-- -------------------------
-- ------------------------------
-- Create a UIFile component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
INPUT_TEXT_TAG : aliased constant String := "inputText";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- 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.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Complete return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_TEXT_TAG : aliased constant String := "inputText";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
Add the autocomplete component
|
Add the autocomplete component
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
783abdcb5fb4bb2dd10a2e621b98889d0fe05f7c
|
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;
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;
|
-----------------------------------------------------------------------
-- 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 out 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 out 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);
Slot.Size := Item.Size;
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;
|
Change Probe_Free to update the Allocation slot and return the size information
|
Change Probe_Free to update the Allocation slot and return the size information
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ba9333799495e4d8bc4e07fb712f7a824e40b742
|
src/util-properties.adb
|
src/util-properties.adb
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties.Factories;
with Ada.Strings.Unbounded.Text_IO;
package body Util.Properties is
use Ada.Text_IO;
use Ada.Strings.Unbounded.Text_IO;
use Interface_P;
function Exists (Self : in Manager'Class;
Name : in String) return Boolean is
begin
-- There is not yet an implementation, no property
if Self.Impl = null then
return False;
end if;
return Exists (Self.Impl.all, +Name);
end Exists;
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean is
begin
-- There is not yet an implementation, no property
if Self.Impl = null then
return False;
end if;
return Exists (Self.Impl.all, Name);
end Exists;
function Get (Self : in Manager'Class;
Name : in String) return Value is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return Get (Self.Impl.all, +Name);
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return Value is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & To_String (Name) & "'";
end if;
return Get (Self.Impl.all, Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return -Get (Self.Impl.all, +Name);
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
return -Get (Self.Impl.all, Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String is
Prop_Name : constant Value := +Name;
begin
if Exists (Self, Prop_Name) then
return Get (Self, Prop_Name);
else
return Default;
end if;
end Get;
procedure Check_And_Create_Impl (Self : in out Manager) is
begin
if Self.Impl = null then
Util.Properties.Factories.Initialize (Self);
Self.Impl.Count := 1;
elsif Self.Impl.Count > 1 then
Self.Impl := Create_Copy (Self.Impl.all);
end if;
end Check_And_Create_Impl;
procedure Insert (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Check_And_Create_Impl (Self);
Insert (Self.Impl.all, +Name, +Item);
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Check_And_Create_Impl (Self);
Set (Self.Impl.all, +Name, +Item);
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value) is
begin
Check_And_Create_Impl (Self);
Set (Self.Impl.all, +Name, Item);
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value) is
begin
Check_And_Create_Impl (Self);
Set (Self.Impl.all, Name, Item);
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in String) is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
Remove (Self.Impl.all, +Name);
end Remove;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in Value) is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
Remove (Self.Impl.all, Name);
end Remove;
-- ------------------------------
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
-- ------------------------------
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array is
begin
if Self.Impl = null then
declare
Empty : Name_Array (1 .. 0);
begin
return Empty;
end;
else
return Get_Names (Self.Impl.all, Prefix);
end if;
end Get_Names;
procedure Adjust (Object : in out Manager) is
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count + 1;
end if;
end Adjust;
procedure Finalize (Object : in out Manager) is
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count - 1;
if Object.Impl.Count = 0 then
Delete (Object.Impl.all, Object.Impl);
end if;
end if;
end Finalize;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access) is
begin
if Self.Impl = null then
Self.Impl := Impl;
Self.Impl.Count := 1;
end if;
end Set_Property_Implementation;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type) is
Line : Unbounded_String;
Pos : Natural;
Len : Natural;
begin
while not End_Of_File (File) loop
Line := Get_Line (File);
Len := Length (Line);
if Len /= 0 and then Element (Line, 1) /= '#' then
Pos := Index (Line, "=");
if Pos > 0 then
Name := Head (Line, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
end if;
end if;
end loop;
Name := Null_Unbounded_String;
Value := Null_Unbounded_String;
end Load_Property;
procedure Load_Properties (Self : in out Manager'Class;
File : in File_Type) is
Name, Value : Unbounded_String;
begin
loop
Load_Property (Name, Value, File);
exit when Name = Null_Unbounded_String;
Set (Self, To_String (Name), To_String (Value));
end loop;
exception
when End_Error =>
return;
end Load_Properties;
procedure Load_Properties (Self : in out Manager'Class;
Path : in String) is
F : File_Type;
begin
Open (F, In_File, Path);
Load_Properties (Self, F);
Close (F);
end Load_Properties;
-- ------------------------------
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied.
-- ------------------------------
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "") is
Names : constant Name_Array := From.Get_Names;
begin
for I in Names'Range loop
declare
Name : Unbounded_String renames Names (I);
begin
if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then
Self.Set (Name, From.Get (Name));
end if;
end;
end loop;
end Copy;
end Util.Properties;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties.Factories;
with Ada.Strings.Unbounded.Text_IO;
package body Util.Properties is
use Ada.Text_IO;
use Ada.Strings.Unbounded.Text_IO;
use Interface_P;
function Exists (Self : in Manager'Class;
Name : in String) return Boolean is
begin
-- There is not yet an implementation, no property
if Self.Impl = null then
return False;
end if;
return Exists (Self.Impl.all, +Name);
end Exists;
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean is
begin
-- There is not yet an implementation, no property
if Self.Impl = null then
return False;
end if;
return Exists (Self.Impl.all, Name);
end Exists;
function Get (Self : in Manager'Class;
Name : in String) return Value is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return Get (Self.Impl.all, +Name);
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return Value is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & To_String (Name) & "'";
end if;
return Get (Self.Impl.all, Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return -Get (Self.Impl.all, +Name);
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
return -Get (Self.Impl.all, Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String is
Prop_Name : constant Value := +Name;
begin
if Exists (Self, Prop_Name) then
return Get (Self, Prop_Name);
else
return Default;
end if;
end Get;
procedure Check_And_Create_Impl (Self : in out Manager) is
begin
if Self.Impl = null then
Util.Properties.Factories.Initialize (Self);
Self.Impl.Count := 1;
elsif Self.Impl.Count > 1 then
declare
Old : Interface_P.Manager_Access := Self.Impl;
begin
Self.Impl := Create_Copy (Self.Impl.all);
Self.Impl.Count := 1;
Old.Count := Old.Count - 1;
end;
end if;
end Check_And_Create_Impl;
procedure Insert (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Check_And_Create_Impl (Self);
Insert (Self.Impl.all, +Name, +Item);
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Check_And_Create_Impl (Self);
Set (Self.Impl.all, +Name, +Item);
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value) is
begin
Check_And_Create_Impl (Self);
Set (Self.Impl.all, +Name, Item);
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value) is
begin
Check_And_Create_Impl (Self);
Set (Self.Impl.all, Name, Item);
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in String) is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
Remove (Self.Impl.all, +Name);
end Remove;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in Value) is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
Remove (Self.Impl.all, Name);
end Remove;
-- ------------------------------
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
-- ------------------------------
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array is
begin
if Self.Impl = null then
declare
Empty : Name_Array (1 .. 0);
begin
return Empty;
end;
else
return Get_Names (Self.Impl.all, Prefix);
end if;
end Get_Names;
procedure Adjust (Object : in out Manager) is
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count + 1;
end if;
end Adjust;
procedure Finalize (Object : in out Manager) is
begin
if Object.Impl /= null then
Object.Impl.Count := Object.Impl.Count - 1;
if Object.Impl.Count = 0 then
Delete (Object.Impl.all, Object.Impl);
end if;
end if;
end Finalize;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access) is
begin
if Self.Impl = null then
Self.Impl := Impl;
Self.Impl.Count := 1;
end if;
end Set_Property_Implementation;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type) is
Line : Unbounded_String;
Pos : Natural;
Len : Natural;
begin
while not End_Of_File (File) loop
Line := Get_Line (File);
Len := Length (Line);
if Len /= 0 and then Element (Line, 1) /= '#' then
Pos := Index (Line, "=");
if Pos > 0 then
Name := Head (Line, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
end if;
end if;
end loop;
Name := Null_Unbounded_String;
Value := Null_Unbounded_String;
end Load_Property;
procedure Load_Properties (Self : in out Manager'Class;
File : in File_Type) is
Name, Value : Unbounded_String;
begin
loop
Load_Property (Name, Value, File);
exit when Name = Null_Unbounded_String;
Set (Self, To_String (Name), To_String (Value));
end loop;
exception
when End_Error =>
return;
end Load_Properties;
procedure Load_Properties (Self : in out Manager'Class;
Path : in String) is
F : File_Type;
begin
Open (F, In_File, Path);
Load_Properties (Self, F);
Close (F);
end Load_Properties;
-- ------------------------------
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied.
-- ------------------------------
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "") is
Names : constant Name_Array := From.Get_Names;
begin
for I in Names'Range loop
declare
Name : Unbounded_String renames Names (I);
begin
if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then
Self.Set (Name, From.Get (Name));
end if;
end;
end loop;
end Copy;
end Util.Properties;
|
Fix copy of property manager
|
Fix copy of property manager
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
7a8701c70ead740345e01e01e3d5bbde3672a52f
|
regtests/asf-navigations-tests.adb
|
regtests/asf-navigations-tests.adb
|
-----------------------------------------------------------------------
-- asf-navigations-tests - Tests for ASF navigation
-- 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.Test_Caller;
with Util.Beans.Objects;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Applications.Tests;
package body ASF.Navigations.Tests is
use Util.Beans.Objects;
use ASF.Tests;
package Caller is new Util.Test_Caller (Test, "Navigations");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test navigation exact match (view, outcome, action)",
Test_Exact_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation partial match (view, outcome)",
Test_Partial_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation exception match (view, outcome)",
Test_Exception_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation wildcard match (view, outcome)",
Test_Wildcard_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation condition match (view, outcome)",
Test_Conditional_Navigation'Access);
end Add_Tests;
-- ------------------------------
-- Initialize the test application
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
use type ASF.Applications.Main.Application_Access;
Fact : ASF.Applications.Main.Application_Factory;
begin
if ASF.Tests.Get_Application = null then
ASF.Tests.Initialize (Util.Tests.Get_Properties, Factory => Fact);
end if;
end Set_Up;
-- ------------------------------
-- Check the navigation for an URI and expect the result to match the regular expression.
-- ------------------------------
procedure Check_Navigation (T : in out Test;
Name : in String;
Match : in String;
Raise_Flag : in Boolean := False) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased ASF.Applications.Tests.Form_Bean;
File : constant String := Util.Tests.Get_Path ("regtests/config/test-navigations.xml");
begin
Form.Perm_Error := Raise_Flag;
ASF.Applications.Main.Configs.Read_Configuration (ASF.Tests.Get_Application.all, File);
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/tests/" & Name & ".html", Name & ".txt");
Request.Set_Parameter ("formText", "1");
Request.Set_Parameter ("name", "John");
Request.Set_Parameter ("password", "12345");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("ok", "1");
Do_Post (Request, Reply, "/tests/" & Name & ".html", Name & "form-navigation-exact.txt");
Assert_Matches (T, Match,
Reply, "Wrong generated content");
end Check_Navigation;
-- ------------------------------
-- Test a form navigation with an exact match (view, outcome, action).
-- ------------------------------
procedure Test_Exact_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav", ".*success.*");
end Test_Exact_Navigation;
-- ------------------------------
-- Test a form navigation with a partial match (view, outcome).
-- ------------------------------
procedure Test_Partial_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-partial", ".*success partial.*");
end Test_Partial_Navigation;
-- ------------------------------
-- Test a form navigation with a exception match (view, outcome).
-- ------------------------------
procedure Test_Exception_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-exception", ".*success exception.*", True);
end Test_Exception_Navigation;
-- ------------------------------
-- Test a form navigation with a wildcard match on the URI (view, outcome).
-- ------------------------------
procedure Test_Wildcard_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-wildcard", ".*success wildcard.*", False);
end Test_Wildcard_Navigation;
-- ------------------------------
-- Test a form navigation with a condition (view, outcome, condition).
-- ------------------------------
procedure Test_Conditional_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-condition", ".*success condition.*", False);
end Test_Conditional_Navigation;
end ASF.Navigations.Tests;
|
-----------------------------------------------------------------------
-- asf-navigations-tests - Tests for ASF navigation
-- Copyright (C) 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Beans.Objects;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Applications.Tests;
package body ASF.Navigations.Tests is
use Util.Beans.Objects;
use ASF.Tests;
package Caller is new Util.Test_Caller (Test, "Navigations");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test navigation exact match (view, outcome, action)",
Test_Exact_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation partial match (view, outcome)",
Test_Partial_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation exception match (view, outcome)",
Test_Exception_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation wildcard match (view, outcome)",
Test_Wildcard_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation condition match (view, outcome)",
Test_Conditional_Navigation'Access);
Caller.Add_Test (Suite, "Test navigation with status",
Test_Status_Navigation'Access);
end Add_Tests;
-- ------------------------------
-- Initialize the test application
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
use type ASF.Applications.Main.Application_Access;
Fact : ASF.Applications.Main.Application_Factory;
begin
if ASF.Tests.Get_Application = null then
ASF.Tests.Initialize (Util.Tests.Get_Properties, Factory => Fact);
end if;
end Set_Up;
-- ------------------------------
-- Check the navigation for an URI and expect the result to match the regular expression.
-- ------------------------------
procedure Check_Navigation (T : in out Test;
Name : in String;
Match : in String;
Raise_Flag : in Boolean := False;
Status : in Natural := 200) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased ASF.Applications.Tests.Form_Bean;
File : constant String := Util.Tests.Get_Path ("regtests/config/test-navigations.xml");
begin
Form.Perm_Error := Raise_Flag;
ASF.Applications.Main.Configs.Read_Configuration (ASF.Tests.Get_Application.all, File);
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/tests/" & Name & ".html", Name & ".txt");
Request.Set_Parameter ("formText", "1");
Request.Set_Parameter ("name", "John");
Request.Set_Parameter ("password", "12345");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("ok", "1");
Do_Post (Request, Reply, "/tests/" & Name & ".html", Name & "form-navigation-exact.txt");
Assert_Matches (T, Match,
Reply, "Wrong generated content", Status);
end Check_Navigation;
-- ------------------------------
-- Test a form navigation with an exact match (view, outcome, action).
-- ------------------------------
procedure Test_Exact_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav", ".*success.*");
end Test_Exact_Navigation;
-- ------------------------------
-- Test a form navigation with a partial match (view, outcome).
-- ------------------------------
procedure Test_Partial_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-partial", ".*success partial.*");
end Test_Partial_Navigation;
-- ------------------------------
-- Test a form navigation with a exception match (view, outcome).
-- ------------------------------
procedure Test_Exception_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-exception", ".*success exception.*", True);
end Test_Exception_Navigation;
-- ------------------------------
-- Test a form navigation with a wildcard match on the URI (view, outcome).
-- ------------------------------
procedure Test_Wildcard_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-wildcard", ".*success wildcard.*", False);
end Test_Wildcard_Navigation;
-- ------------------------------
-- Test a form navigation with a condition (view, outcome, condition).
-- ------------------------------
procedure Test_Conditional_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-condition", ".*success condition.*", False);
end Test_Conditional_Navigation;
-- ------------------------------
-- Test a navigation rule with a status.
-- ------------------------------
procedure Test_Status_Navigation (T : in out Test) is
begin
T.Check_Navigation ("form-nav-status", ".*success status.*", False, 400);
end Test_Status_Navigation;
end ASF.Navigations.Tests;
|
Add new unit test Test_Status_Navigation to test the <status> configuration of a navigation rule
|
Add new unit test Test_Status_Navigation to test the <status> configuration of a navigation rule
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b05183e3ddfb8c9ac64221fd5ee00fac329659da
|
samples/xmlrd.adb
|
samples/xmlrd.adb
|
-----------------------------------------------------------------------
-- xrds -- XRDS parser example
-- 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.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Containers;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Beans;
with Util.Beans.Objects;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.Mappers.Vector_Mapper;
with Util.Serialize.IO.XML;
procedure Xmlrd is
use Ada.Containers;
use Util.Streams.Buffered;
use Ada.Strings.Unbounded;
Reader : Util.Serialize.IO.XML.Parser;
Count : constant Natural := Ada.Command_Line.Argument_Count;
type Service_Fields is (FIELD_PRIORITY, FIELD_TYPE, FIELD_URI, FIELD_LOCAL_ID, FIELD_DELEGATE);
type Service is record
Priority : Integer;
URI : Ada.Strings.Unbounded.Unbounded_String;
RDS_Type : Ada.Strings.Unbounded.Unbounded_String;
Delegate : Ada.Strings.Unbounded.Unbounded_String;
Local_Id : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Service_Access is access all Service;
package Service_Vector is
new Ada.Containers.Vectors (Element_Type => Service,
Index_Type => Natural);
procedure Print (P : in Service_Vector.Cursor);
procedure Print (P : in Service);
procedure Set_Member (P : in out Service;
Field : in Service_Fields;
Value : in Util.Beans.Objects.Object);
function Get_Member (P : in Service;
Field : in Service_Fields) return Util.Beans.Objects.Object;
procedure Set_Member (P : in out Service;
Field : in Service_Fields;
Value : in Util.Beans.Objects.Object) is
begin
Ada.Text_IO.Put_Line ("Set member " & Service_Fields'Image (Field)
& " to " & Util.Beans.Objects.To_String (Value));
case Field is
when FIELD_PRIORITY =>
P.Priority := Util.Beans.Objects.To_Integer (Value);
when FIELD_TYPE =>
P.RDS_Type := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_URI =>
P.URI := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_LOCAL_ID =>
P.Local_Id := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_DELEGATE =>
P.Delegate := Util.Beans.Objects.To_Unbounded_String (Value);
end case;
end Set_Member;
function Get_Member (P : in Service;
Field : in Service_Fields) return Util.Beans.Objects.Object is
begin
case Field is
when FIELD_PRIORITY =>
return Util.Beans.Objects.To_Object (P.Priority);
when FIELD_TYPE =>
return Util.Beans.Objects.To_Object (P.RDS_Type);
when FIELD_URI =>
return Util.Beans.Objects.To_Object (P.URI);
when FIELD_LOCAL_ID =>
return Util.Beans.Objects.To_Object (P.Local_Id);
when FIELD_DELEGATE =>
return Util.Beans.Objects.To_Object (P.Delegate);
end case;
end Get_Member;
package Service_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Service,
Element_Type_Access => Service_Access,
Fields => Service_Fields,
Set_Member => Set_Member);
package Service_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Service_Vector,
Element_Mapper => Service_Mapper);
procedure Print (P : in Service) is
begin
Ada.Text_IO.Put_Line (" URI: " & To_String (P.URI));
Ada.Text_IO.Put_Line (" Priority: " & Integer'Image (P.Priority));
Ada.Text_IO.Put_Line ("Type (last): " & To_String (P.RDS_Type));
Ada.Text_IO.Put_Line (" Delegate: " & To_String (P.Delegate));
Ada.Text_IO.New_Line;
end Print;
procedure Print (P : in Service_Vector.Cursor) is
begin
Print (Service_Vector.Element (P));
end Print;
Service_Mapping : aliased Service_Mapper.Mapper;
Service_Vector_Mapping : aliased Service_Vector_Mapper.Mapper;
begin
Util.Log.Loggers.Initialize ("samples/log4j.properties");
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: xmlrd file...");
return;
end if;
Service_Mapping.Add_Mapping ("Type", FIELD_TYPE);
Service_Mapping.Add_Mapping ("URI", FIELD_URI);
Service_Mapping.Add_Mapping ("Delegate", FIELD_DELEGATE);
Service_Mapping.Add_Mapping ("@priority", FIELD_PRIORITY);
Service_Mapping.Bind (Get_Member'Access);
Service_Vector_Mapping.Set_Mapping (Service_Mapping'Unchecked_Access);
Reader.Add_Mapping ("XRDS/XRD/Service", Service_Vector_Mapping'Unchecked_Access);
for I in 1 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
List : aliased Service_Vector_Mapper.Vector;
begin
Service_Vector_Mapper.Set_Context (Reader, List'Unchecked_Access);
Reader.Parse (S);
Ada.Text_IO.Put_Line ("Rule count: " & Count_Type'Image (List.Length));
-- The list now contains our elements.
List.Iterate (Process => Print'Access);
declare
Output : Util.Serialize.IO.XML.Output_Stream;
begin
Output.Initialize (Size => 10000);
Output.Start_Entity ("XRDS");
Service_Vector_Mapping.Write (Output, List);
Output.End_Entity ("XRDS");
Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Buffered_Stream (Output)));
end;
end;
end loop;
end Xmlrd;
|
-----------------------------------------------------------------------
-- xrds -- XRDS parser example
-- 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.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Containers;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Beans;
with Util.Beans.Objects;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.Mappers.Vector_Mapper;
with Util.Serialize.IO.XML;
procedure Xmlrd is
use Ada.Containers;
use Util.Streams.Buffered;
use Ada.Strings.Unbounded;
Reader : Util.Serialize.IO.XML.Parser;
Count : constant Natural := Ada.Command_Line.Argument_Count;
type Service_Fields is (FIELD_PRIORITY, FIELD_TYPE, FIELD_URI, FIELD_LOCAL_ID, FIELD_DELEGATE);
type Service is record
Priority : Integer;
URI : Ada.Strings.Unbounded.Unbounded_String;
RDS_Type : Ada.Strings.Unbounded.Unbounded_String;
Delegate : Ada.Strings.Unbounded.Unbounded_String;
Local_Id : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Service_Access is access all Service;
package Service_Vector is
new Ada.Containers.Vectors (Element_Type => Service,
Index_Type => Natural);
procedure Print (P : in Service_Vector.Cursor);
procedure Print (P : in Service);
procedure Set_Member (P : in out Service;
Field : in Service_Fields;
Value : in Util.Beans.Objects.Object);
function Get_Member (P : in Service;
Field : in Service_Fields) return Util.Beans.Objects.Object;
procedure Set_Member (P : in out Service;
Field : in Service_Fields;
Value : in Util.Beans.Objects.Object) is
begin
Ada.Text_IO.Put_Line ("Set member " & Service_Fields'Image (Field)
& " to " & Util.Beans.Objects.To_String (Value));
case Field is
when FIELD_PRIORITY =>
P.Priority := Util.Beans.Objects.To_Integer (Value);
when FIELD_TYPE =>
P.RDS_Type := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_URI =>
P.URI := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_LOCAL_ID =>
P.Local_Id := Util.Beans.Objects.To_Unbounded_String (Value);
when FIELD_DELEGATE =>
P.Delegate := Util.Beans.Objects.To_Unbounded_String (Value);
end case;
end Set_Member;
function Get_Member (P : in Service;
Field : in Service_Fields) return Util.Beans.Objects.Object is
begin
case Field is
when FIELD_PRIORITY =>
return Util.Beans.Objects.To_Object (P.Priority);
when FIELD_TYPE =>
return Util.Beans.Objects.To_Object (P.RDS_Type);
when FIELD_URI =>
return Util.Beans.Objects.To_Object (P.URI);
when FIELD_LOCAL_ID =>
return Util.Beans.Objects.To_Object (P.Local_Id);
when FIELD_DELEGATE =>
return Util.Beans.Objects.To_Object (P.Delegate);
end case;
end Get_Member;
package Service_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Service,
Element_Type_Access => Service_Access,
Fields => Service_Fields,
Set_Member => Set_Member);
package Service_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Service_Vector,
Element_Mapper => Service_Mapper);
procedure Print (P : in Service) is
begin
Ada.Text_IO.Put_Line (" URI: " & To_String (P.URI));
Ada.Text_IO.Put_Line (" Priority: " & Integer'Image (P.Priority));
Ada.Text_IO.Put_Line ("Type (last): " & To_String (P.RDS_Type));
Ada.Text_IO.Put_Line (" Delegate: " & To_String (P.Delegate));
Ada.Text_IO.New_Line;
end Print;
procedure Print (P : in Service_Vector.Cursor) is
begin
Print (Service_Vector.Element (P));
end Print;
Service_Mapping : aliased Service_Mapper.Mapper;
Service_Vector_Mapping : aliased Service_Vector_Mapper.Mapper;
Mapper : Util.Serialize.Mappers.Processing;
begin
Util.Log.Loggers.Initialize ("samples/log4j.properties");
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: xmlrd file...");
return;
end if;
Service_Mapping.Add_Mapping ("Type", FIELD_TYPE);
Service_Mapping.Add_Mapping ("URI", FIELD_URI);
Service_Mapping.Add_Mapping ("Delegate", FIELD_DELEGATE);
Service_Mapping.Add_Mapping ("@priority", FIELD_PRIORITY);
Service_Mapping.Bind (Get_Member'Access);
Service_Vector_Mapping.Set_Mapping (Service_Mapping'Unchecked_Access);
Mapper.Add_Mapping ("XRDS/XRD/Service", Service_Vector_Mapping'Unchecked_Access);
for I in 1 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
List : aliased Service_Vector_Mapper.Vector;
begin
Service_Vector_Mapper.Set_Context (Mapper, List'Unchecked_Access);
Reader.Parse (S, Mapper);
Ada.Text_IO.Put_Line ("Rule count: " & Count_Type'Image (List.Length));
-- The list now contains our elements.
List.Iterate (Process => Print'Access);
declare
Output : Util.Serialize.IO.XML.Output_Stream;
begin
Output.Initialize (Size => 10000);
Output.Start_Entity ("XRDS");
Service_Vector_Mapping.Write (Output, List);
Output.End_Entity ("XRDS");
Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Buffered_Stream (Output)));
end;
end;
end loop;
end Xmlrd;
|
Update example
|
Update example
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c23734508e40874bede023fa832e4b66d01cd570
|
src/display.adb
|
src/display.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with JohnnyText;
package body Display is
package JT renames JohnnyText;
----------------------
-- launch_monitor --
----------------------
function launch_monitor (num_builders : builders) return Boolean is
begin
TIC.Init_Screen;
if not TIC.Has_Colors then
TIC.End_Windows;
return False;
end if;
TIC.Set_Echo_Mode (False);
TIC.Set_Raw_Mode (True);
TIC.Set_Cbreak_Mode (True);
TIC.Set_Cursor_Visibility (Visibility => cursor_vis);
establish_colors;
launch_summary_zone;
launch_builders_zone (num_builders);
launch_actions_zone (num_builders);
return True;
end launch_monitor;
-------------------------
-- terminate_monitor --
-------------------------
procedure terminate_monitor is
begin
TIC.Delete (Win => zone_actions);
TIC.Delete (Win => zone_builders);
TIC.Delete (Win => zone_summary);
TIC.End_Windows;
end terminate_monitor;
---------------------------
-- launch_summary_zone --
---------------------------
procedure launch_summary_zone
is
line1 : String := "Total 0 Built 0 Ignored 0 " &
"Load 0.00 Pkg/hour 0 ";
line2 : String := " Left 0 Failed 0 skipped 0 " &
"swap 0.0% Impulse 0 00:00:00";
begin
zone_summary := TIC.Create (Number_Of_Lines => 2,
Number_Of_Columns => app_width,
First_Line_Position => 0,
First_Column_Position => 0);
TIC.Set_Character_Attributes (Win => zone_summary,
Attr => bright_bold,
Color => TIC.Color_Pair (c_sumlabel));
TIC.Move_Cursor (Win => zone_summary, Line => 0, Column => 0);
TIC.Add (Win => zone_summary, Str => line1);
TIC.Move_Cursor (Win => zone_summary, Line => 1, Column => 0);
TIC.Add (Win => zone_summary, Str => line2);
TIC.Refresh (Win => zone_summary);
end launch_summary_zone;
----------------------------
-- launch_builders_zone --
----------------------------
procedure launch_builders_zone (num_builders : builders)
is
hghtint : constant Integer := 4 + Integer (num_builders);
height : constant TIC.Line_Position := TIC.Line_Position (hghtint);
lastrow : constant TIC.Line_Position := inc (height, -1);
dashes : constant String (1 .. 79) := (others => '=');
header : String (1 .. 79) := (others => ' ');
headtxt : constant String := " ID Elapsed Build Phase " &
"Origin Lines";
begin
header (1 .. headtxt'Length) := headtxt;
zone_builders := TIC.Create (Number_Of_Lines => height,
Number_Of_Columns => app_width,
First_Line_Position => 2,
First_Column_Position => 0);
TIC.Set_Character_Attributes (Win => zone_builders,
Attr => bright,
Color => TIC.Color_Pair (c_dashes));
TIC.Move_Cursor (Win => zone_builders, Line => 0, Column => 0);
TIC.Add (Win => zone_builders, Str => dashes);
TIC.Move_Cursor (Win => zone_builders, Line => 2, Column => 0);
TIC.Add (Win => zone_builders, Str => dashes);
TIC.Move_Cursor (Win => zone_builders, Line => lastrow, Column => 0);
TIC.Add (Win => zone_builders, Str => dashes);
TIC.Set_Character_Attributes (Win => zone_builders,
Attr => dimmed_bold,
Color => TIC.Color_Pair (c_tableheader));
TIC.Move_Cursor (Win => zone_builders, Line => 1, Column => 0);
TIC.Add (Win => zone_builders, Str => header);
TIC.Refresh (Win => zone_builders);
end launch_builders_zone;
---------------------------
-- launch_actions_zone --
---------------------------
procedure launch_actions_zone (num_builders : builders)
is
consumed : constant Integer := Integer (num_builders) + 4 + 2;
difference : constant Integer := 0 - consumed;
viewheight : constant TIC.Line_Position := inc (TIC.Lines, difference);
viewpos : constant TIC.Line_Position := TIC.Line_Position (consumed);
begin
zone_actions := TIC.Create (Number_Of_Lines => viewheight,
Number_Of_Columns => app_width,
First_Line_Position => viewpos,
First_Column_Position => 0);
end launch_actions_zone;
-----------
-- inc --
-----------
function inc (X : TIC.Line_Position; by : Integer) return TIC.Line_Position
is
use type TIC.Line_Position;
begin
return X + TIC.Line_Position (by);
end inc;
-----------------
-- summarize --
-----------------
procedure summarize (data : summary_rec)
is
function pad (S : String; amount : Positive := 5) return String;
function fmtpc (f : Float; percent : Boolean) return String;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False);
remaining : constant Integer := data.Initially - data.Built -
data.Failed - data.Ignored - data.Skipped;
function pad (S : String; amount : Positive := 5) return String
is
result : String (1 .. amount) := (others => ' ');
slen : constant Natural := S'Length;
begin
result (1 .. slen) := S;
return result;
end pad;
function fmtpc (f : Float; percent : Boolean) return String
is
type loadtype is delta 0.01 digits 3;
result : String (1 .. 5) := (others => ' ');
raw1 : constant loadtype := loadtype (f);
raw2 : constant String := raw1'Img;
rlen : constant Natural := raw2'Length;
start : constant Natural := 6 - rlen;
begin
result (start .. 5) := raw2;
if percent then
result (5) := '%';
end if;
return result;
end fmtpc;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False)
is
attribute : TIC.Character_Attribute_Set := bright_bold;
begin
if dim then
attribute := dimmed;
end if;
TIC.Set_Character_Attributes (Win => zone_summary,
Attr => attribute,
Color => color);
TIC.Move_Cursor (Win => zone_summary, Line => row, Column => col);
TIC.Add (Win => zone_summary, Str => S);
end colorado;
L1F1 : constant String := pad (JT.int2str (data.Initially));
L1F2 : constant String := pad (JT.int2str (data.Built));
L1F3 : constant String := pad (JT.int2str (data.Ignored));
L1F4 : constant String := fmtpc (data.load, False);
L1F5 : constant String := pad (JT.int2str (data.pkg_hour), 4);
L2F1 : constant String := pad (JT.int2str (remaining));
L2F2 : constant String := pad (JT.int2str (data.Failed));
L2F3 : constant String := pad (JT.int2str (data.Skipped));
L2F4 : constant String := fmtpc (data.swap, True);
L2F5 : constant String := pad (JT.int2str (data.impulse), 4);
begin
colorado (L1F1, c_standard, 6, 0);
colorado (L1F2, c_success, 20, 0);
colorado (L1F3, c_ignored, 35, 0);
colorado (L1F4, c_standard, 47, 0, True);
colorado (L1F5, c_standard, 63, 0, True);
colorado (L2F1, c_standard, 6, 1);
colorado (L2F2, c_failure, 20, 1);
colorado (L2F3, c_skipped, 35, 1);
colorado (L2F4, c_standard, 47, 1, True);
colorado (L2F5, c_standard, 63, 1, True);
colorado (data.elapsed, c_elapsed, 69, 1);
TIC.Refresh (Win => zone_summary);
end summarize;
-----------------------
-- update_builder --
-----------------------
procedure update_builder (BR : builder_rec)
is
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False);
procedure print_id;
row : TIC.Line_Position := inc (TIC.Line_Position (BR.id), 2);
procedure print_id is
begin
TIC.Set_Character_Attributes (Win => zone_builders,
Attr => c_slave (BR.id).attribute,
Color => c_slave (BR.id).palette);
TIC.Move_Cursor (Win => zone_builders, Line => row, Column => 1);
TIC.Add (Win => zone_builders, Str => BR.slavid);
end print_id;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False)
is
attribute : TIC.Character_Attribute_Set := bright_bold;
begin
if dim then
attribute := dimmed;
end if;
TIC.Set_Character_Attributes (Win => zone_builders,
Attr => attribute,
Color => color);
TIC.Move_Cursor (Win => zone_builders, Line => row, Column => col);
TIC.Add (Win => zone_builders, Str => S);
end colorado;
begin
print_id;
colorado (BR.Elapsed, c_standard, 5, row, True);
colorado (BR.phase, c_bldphase, 15, row, True);
colorado (BR.origin, c_origin, 32, row, False);
colorado (BR.LLines, c_standard, 71, row, True);
end update_builder;
------------------------------
-- refresh_builder_window --
------------------------------
procedure refresh_builder_window is
begin
TIC.Refresh (Win => zone_builders);
end refresh_builder_window;
------------------------
-- establish_colors --
------------------------
procedure establish_colors is
begin
TIC.Start_Color;
TIC.Init_Pair (TIC.Color_Pair (1), TIC.White, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (2), TIC.Green, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (3), TIC.Red, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (4), TIC.Yellow, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (5), TIC.Black, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (6), TIC.Cyan, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (7), TIC.Blue, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (8), TIC.Magenta, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (9), TIC.Blue, TIC.White);
c_standard := TIC.Color_Pair (1);
c_success := TIC.Color_Pair (2);
c_failure := TIC.Color_Pair (3);
c_ignored := TIC.Color_Pair (4);
c_skipped := TIC.Color_Pair (5);
c_sumlabel := TIC.Color_Pair (6);
c_dashes := TIC.Color_Pair (7);
c_elapsed := TIC.Color_Pair (4);
c_tableheader := TIC.Color_Pair (1);
c_origin := TIC.Color_Pair (6);
c_bldphase := TIC.Color_Pair (4);
c_slave (1).palette := TIC.Color_Pair (1); -- white / Black
c_slave (1).attribute := bright;
c_slave (2).palette := TIC.Color_Pair (2); -- light green / Black
c_slave (2).attribute := bright;
c_slave (3).palette := TIC.Color_Pair (4); -- yellow / Black
c_slave (3).attribute := bright;
c_slave (4).palette := TIC.Color_Pair (3); -- light red / Black
c_slave (4).attribute := bright;
c_slave (5).palette := TIC.Color_Pair (8); -- light magenta / Black
c_slave (5).attribute := bright;
c_slave (6).palette := TIC.Color_Pair (7); -- light blue / Black
c_slave (6).attribute := bright;
c_slave (7).palette := TIC.Color_Pair (6); -- light cyan / Black
c_slave (7).attribute := bright;
c_slave (8).palette := TIC.Color_Pair (5); -- dark grey / Black
c_slave (8).attribute := bright;
c_slave (9).palette := TIC.Color_Pair (1); -- light grey / Black
c_slave (9).attribute := dimmed;
c_slave (10).palette := TIC.Color_Pair (2); -- light green / Black
c_slave (10).attribute := dimmed;
c_slave (11).palette := TIC.Color_Pair (4); -- brown / Black
c_slave (11).attribute := dimmed;
c_slave (12).palette := TIC.Color_Pair (3); -- dark red / Black
c_slave (12).attribute := dimmed;
c_slave (13).palette := TIC.Color_Pair (8); -- dark magenta / Black
c_slave (13).attribute := dimmed;
c_slave (14).palette := TIC.Color_Pair (7); -- dark blue / Black
c_slave (14).attribute := dimmed;
c_slave (15).palette := TIC.Color_Pair (6); -- dark cyan / Black
c_slave (15).attribute := dimmed;
c_slave (16).palette := TIC.Color_Pair (9); -- white / dark blue
c_slave (16).attribute := dimmed;
for bld in builders (17) .. builders (32) loop
c_slave (bld) := c_slave (bld - 16);
c_slave (bld - 16).attribute.Bold_Character := True;
end loop;
for bld in builders (33) .. builders (64) loop
c_slave (bld) := c_slave (bld - 32);
end loop;
end establish_colors;
end Display;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with JohnnyText;
package body Display is
package JT renames JohnnyText;
----------------------
-- launch_monitor --
----------------------
function launch_monitor (num_builders : builders) return Boolean is
begin
TIC.Init_Screen;
if not TIC.Has_Colors then
TIC.End_Windows;
return False;
end if;
TIC.Set_Echo_Mode (False);
TIC.Set_Raw_Mode (True);
TIC.Set_Cbreak_Mode (True);
TIC.Set_Cursor_Visibility (Visibility => cursor_vis);
establish_colors;
launch_summary_zone;
launch_builders_zone (num_builders);
launch_actions_zone (num_builders);
return True;
end launch_monitor;
-------------------------
-- terminate_monitor --
-------------------------
procedure terminate_monitor is
begin
TIC.Delete (Win => zone_actions);
TIC.Delete (Win => zone_builders);
TIC.Delete (Win => zone_summary);
TIC.End_Windows;
end terminate_monitor;
---------------------------
-- launch_summary_zone --
---------------------------
procedure launch_summary_zone
is
line1 : String := "Total 0 Built 0 Ignored 0 " &
"Load 0.00 Pkg/hour 0 ";
line2 : String := " Left 0 Failed 0 skipped 0 " &
"swap 0.0% Impulse 0 00:00:00";
begin
zone_summary := TIC.Create (Number_Of_Lines => 2,
Number_Of_Columns => app_width,
First_Line_Position => 0,
First_Column_Position => 0);
TIC.Set_Character_Attributes (Win => zone_summary,
Attr => bright_bold,
Color => TIC.Color_Pair (c_sumlabel));
TIC.Move_Cursor (Win => zone_summary, Line => 0, Column => 0);
TIC.Add (Win => zone_summary, Str => line1);
TIC.Move_Cursor (Win => zone_summary, Line => 1, Column => 0);
TIC.Add (Win => zone_summary, Str => line2);
TIC.Refresh (Win => zone_summary);
end launch_summary_zone;
----------------------------
-- launch_builders_zone --
----------------------------
procedure launch_builders_zone (num_builders : builders)
is
hghtint : constant Integer := 4 + Integer (num_builders);
height : constant TIC.Line_Position := TIC.Line_Position (hghtint);
lastrow : constant TIC.Line_Position := inc (height, -1);
dashes : constant String (1 .. 79) := (others => '=');
header : String (1 .. 79) := (others => ' ');
headtxt : constant String := " ID Elapsed Build Phase " &
"Origin Lines";
begin
header (1 .. headtxt'Length) := headtxt;
zone_builders := TIC.Create (Number_Of_Lines => height,
Number_Of_Columns => app_width,
First_Line_Position => 2,
First_Column_Position => 0);
TIC.Set_Character_Attributes (Win => zone_builders,
Attr => bright,
Color => TIC.Color_Pair (c_dashes));
TIC.Move_Cursor (Win => zone_builders, Line => 0, Column => 0);
TIC.Add (Win => zone_builders, Str => dashes);
TIC.Move_Cursor (Win => zone_builders, Line => 2, Column => 0);
TIC.Add (Win => zone_builders, Str => dashes);
TIC.Move_Cursor (Win => zone_builders, Line => lastrow, Column => 0);
TIC.Add (Win => zone_builders, Str => dashes);
TIC.Set_Character_Attributes (Win => zone_builders,
Attr => dimmed_bold,
Color => TIC.Color_Pair (c_tableheader));
TIC.Move_Cursor (Win => zone_builders, Line => 1, Column => 0);
TIC.Add (Win => zone_builders, Str => header);
TIC.Refresh (Win => zone_builders);
end launch_builders_zone;
---------------------------
-- launch_actions_zone --
---------------------------
procedure launch_actions_zone (num_builders : builders)
is
consumed : constant Integer := Integer (num_builders) + 4 + 2;
difference : constant Integer := 0 - consumed;
viewheight : constant TIC.Line_Position := inc (TIC.Lines, difference);
viewpos : constant TIC.Line_Position := TIC.Line_Position (consumed);
begin
zone_actions := TIC.Create (Number_Of_Lines => viewheight,
Number_Of_Columns => app_width,
First_Line_Position => viewpos,
First_Column_Position => 0);
end launch_actions_zone;
-----------
-- inc --
-----------
function inc (X : TIC.Line_Position; by : Integer) return TIC.Line_Position
is
use type TIC.Line_Position;
begin
return X + TIC.Line_Position (by);
end inc;
-----------------
-- summarize --
-----------------
procedure summarize (data : summary_rec)
is
function pad (S : String; amount : Positive := 5) return String;
function fmtpc (f : Float; percent : Boolean) return String;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False);
remaining : constant Integer := data.Initially - data.Built -
data.Failed - data.Ignored - data.Skipped;
function pad (S : String; amount : Positive := 5) return String
is
result : String (1 .. amount) := (others => ' ');
slen : constant Natural := S'Length;
begin
result (1 .. slen) := S;
return result;
end pad;
function fmtpc (f : Float; percent : Boolean) return String
is
type loadtype is delta 0.01 digits 3;
result : String (1 .. 5) := (others => ' ');
raw1 : constant loadtype := loadtype (f);
raw2 : constant String := raw1'Img;
rlen : constant Natural := raw2'Length;
start : constant Natural := 6 - rlen;
begin
result (start .. 5) := raw2;
if percent then
result (5) := '%';
end if;
return result;
end fmtpc;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False)
is
attribute : TIC.Character_Attribute_Set := bright_bold;
begin
if dim then
attribute := dimmed;
end if;
TIC.Set_Character_Attributes (Win => zone_summary,
Attr => attribute,
Color => color);
TIC.Move_Cursor (Win => zone_summary, Line => row, Column => col);
TIC.Add (Win => zone_summary, Str => S);
end colorado;
L1F1 : constant String := pad (JT.int2str (data.Initially));
L1F2 : constant String := pad (JT.int2str (data.Built));
L1F3 : constant String := pad (JT.int2str (data.Ignored));
L1F4 : constant String := fmtpc (data.load, False);
L1F5 : constant String := pad (JT.int2str (data.pkg_hour), 4);
L2F1 : constant String := pad (JT.int2str (remaining));
L2F2 : constant String := pad (JT.int2str (data.Failed));
L2F3 : constant String := pad (JT.int2str (data.Skipped));
L2F4 : constant String := fmtpc (data.swap, True);
L2F5 : constant String := pad (JT.int2str (data.impulse), 4);
begin
colorado (L1F1, c_standard, 6, 0);
colorado (L1F2, c_success, 20, 0);
colorado (L1F3, c_ignored, 35, 0);
colorado (L1F4, c_standard, 47, 0, True);
colorado (L1F5, c_standard, 63, 0, True);
colorado (L2F1, c_standard, 6, 1);
colorado (L2F2, c_failure, 20, 1);
colorado (L2F3, c_skipped, 35, 1);
colorado (L2F4, c_standard, 47, 1, True);
colorado (L2F5, c_standard, 63, 1, True);
colorado (data.elapsed, c_elapsed, 69, 1);
TIC.Refresh (Win => zone_summary);
end summarize;
-----------------------
-- update_builder --
-----------------------
procedure update_builder (BR : builder_rec)
is
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False);
procedure print_id;
row : TIC.Line_Position := inc (TIC.Line_Position (BR.id), 2);
procedure print_id is
begin
TIC.Set_Character_Attributes (Win => zone_builders,
Attr => c_slave (BR.id).attribute,
Color => c_slave (BR.id).palette);
TIC.Move_Cursor (Win => zone_builders, Line => row, Column => 1);
TIC.Add (Win => zone_builders, Str => BR.slavid);
end print_id;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False)
is
attribute : TIC.Character_Attribute_Set := bright_bold;
begin
if dim then
attribute := dimmed;
end if;
TIC.Set_Character_Attributes (Win => zone_builders,
Attr => attribute,
Color => color);
TIC.Move_Cursor (Win => zone_builders, Line => row, Column => col);
TIC.Add (Win => zone_builders, Str => S);
end colorado;
begin
print_id;
colorado (BR.Elapsed, c_standard, 5, row, True);
colorado (BR.phase, c_bldphase, 15, row, True);
colorado (BR.origin, c_origin, 32, row, False);
colorado (BR.LLines, c_standard, 71, row, True);
end update_builder;
------------------------------
-- refresh_builder_window --
------------------------------
procedure refresh_builder_window is
begin
TIC.Refresh (Win => zone_builders);
end refresh_builder_window;
------------------------
-- establish_colors --
------------------------
procedure establish_colors is
begin
TIC.Start_Color;
TIC.Init_Pair (TIC.Color_Pair (1), TIC.White, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (2), TIC.Green, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (3), TIC.Red, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (4), TIC.Yellow, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (5), TIC.Black, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (6), TIC.Cyan, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (7), TIC.Blue, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (8), TIC.Magenta, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (9), TIC.Blue, TIC.White);
c_standard := TIC.Color_Pair (1);
c_success := TIC.Color_Pair (2);
c_failure := TIC.Color_Pair (3);
c_ignored := TIC.Color_Pair (4);
c_skipped := TIC.Color_Pair (5);
c_sumlabel := TIC.Color_Pair (6);
c_dashes := TIC.Color_Pair (7);
c_elapsed := TIC.Color_Pair (4);
c_tableheader := TIC.Color_Pair (1);
c_origin := TIC.Color_Pair (6);
c_bldphase := TIC.Color_Pair (4);
c_slave (1).palette := TIC.Color_Pair (1); -- white / Black
c_slave (1).attribute := bright;
c_slave (2).palette := TIC.Color_Pair (2); -- light green / Black
c_slave (2).attribute := bright;
c_slave (3).palette := TIC.Color_Pair (4); -- yellow / Black
c_slave (3).attribute := bright;
c_slave (4).palette := TIC.Color_Pair (8); -- light magenta / Black
c_slave (4).attribute := bright;
c_slave (5).palette := TIC.Color_Pair (3); -- light red / Black
c_slave (5).attribute := bright;
c_slave (6).palette := TIC.Color_Pair (7); -- light blue / Black
c_slave (6).attribute := bright;
c_slave (7).palette := TIC.Color_Pair (6); -- light cyan / Black
c_slave (7).attribute := bright;
c_slave (8).palette := TIC.Color_Pair (5); -- dark grey / Black
c_slave (8).attribute := bright;
c_slave (9).palette := TIC.Color_Pair (1); -- light grey / Black
c_slave (9).attribute := dimmed;
c_slave (10).palette := TIC.Color_Pair (2); -- light green / Black
c_slave (10).attribute := dimmed;
c_slave (11).palette := TIC.Color_Pair (4); -- brown / Black
c_slave (11).attribute := dimmed;
c_slave (12).palette := TIC.Color_Pair (8); -- dark magenta / Black
c_slave (12).attribute := dimmed;
c_slave (13).palette := TIC.Color_Pair (3); -- dark red / Black
c_slave (13).attribute := dimmed;
c_slave (14).palette := TIC.Color_Pair (7); -- dark blue / Black
c_slave (14).attribute := dimmed;
c_slave (15).palette := TIC.Color_Pair (6); -- dark cyan / Black
c_slave (15).attribute := dimmed;
c_slave (16).palette := TIC.Color_Pair (9); -- white / dark blue
c_slave (16).attribute := dimmed;
for bld in builders (17) .. builders (32) loop
c_slave (bld) := c_slave (bld - 16);
c_slave (bld - 16).attribute.Bold_Character := True;
end loop;
for bld in builders (33) .. builders (64) loop
c_slave (bld) := c_slave (bld - 32);
end loop;
end establish_colors;
end Display;
|
Switch magenta and red order again
|
Switch magenta and red order again
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
afec560ae030bb815bf04732ea32a4cb1fdab174
|
src/gen-artifacts-xmi.ads
|
src/gen-artifacts-xmi.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
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;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
Add the <<Version>> stereotype
|
Add the <<Version>> stereotype
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
5efc8998b079a31dbd5dd747fe82aed4b0838a63
|
src/gen-commands-docs.adb
|
src/gen-commands-docs.adb
|
-----------------------------------------------------------------------
-- gen-commands-docs -- Extract and generate documentation for the project
-- 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 GNAT.Command_Line;
with Ada.Text_IO;
package body Gen.Commands.Docs is
use GNAT.Command_Line;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
begin
Generator.Read_Project ("dynamo.xml", True);
-- Setup the target directory where the distribution is created.
declare
Target_Dir : constant String := Get_Argument;
begin
if Target_Dir'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Target_Dir);
end;
-- Read the package description.
declare
Package_File : constant String := Get_Argument;
begin
if Package_File'Length > 0 then
Gen.Generator.Read_Package (Generator, Package_File);
else
Gen.Generator.Read_Package (Generator, "package.xml");
end if;
end;
-- Run the generation.
Gen.Generator.Prepare (Generator);
Gen.Generator.Generate_All (Generator);
Gen.Generator.Finish (Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc");
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
Doc : Gen.Artifacts.Docs.Artifact;
M : Gen.Model.Packages.Model_Definition;
begin
Generator.Read_Project ("dynamo.xml", False);
-- Setup the target directory where the distribution is created.
declare
Target_Dir : constant String := Get_Argument;
begin
if Target_Dir'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Target_Dir);
end;
--
-- -- Read the package description.
-- declare
-- Package_File : constant String := Get_Argument;
-- begin
-- if Package_File'Length > 0 then
-- Gen.Generator.Read_Package (Generator, Package_File);
-- else
-- Gen.Generator.Read_Package (Generator, "package.xml");
-- end if;
-- end;
Doc.Prepare (M, Generator);
-- -- Run the generation.
-- Gen.Generator.Prepare (Generator);
-- Gen.Generator.Generate_All (Generator);
-- Gen.Generator.Finish (Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc");
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;
|
Create the documentation artifact and invoke it for the build-doc command
|
Create the documentation artifact and invoke it for the build-doc command
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
2f168841c94639c4bfe9924d9fdf90661202e8bd
|
src/util-dates.adb
|
src/util-dates.adb
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Dates is
-- ------------------------------
-- Split the date into a date record (See Ada.Calendar.Formatting.Split).
-- ------------------------------
procedure Split (Into : out Date_Record;
Date : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is
begin
Into.Date := Date;
Into.Time_Zone := Time_Zone;
Ada.Calendar.Formatting.Split (Date => Date,
Year => Into.Year,
Month => Into.Month,
Day => Into.Month_Day,
Hour => Into.Hour,
Minute => Into.Minute,
Second => Into.Second,
Sub_Second => Into.Sub_Second,
Leap_Second => Into.Leap_Second,
Time_Zone => Time_Zone);
Into.Day := Ada.Calendar.Formatting.Day_Of_Week (Date);
end Split;
end Util.Dates;
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- Copyright (C) 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar.Arithmetic;
package body Util.Dates is
-- ------------------------------
-- Split the date into a date record (See Ada.Calendar.Formatting.Split).
-- ------------------------------
procedure Split (Into : out Date_Record;
Date : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is
begin
Into.Date := Date;
Into.Time_Zone := Time_Zone;
Ada.Calendar.Formatting.Split (Date => Date,
Year => Into.Year,
Month => Into.Month,
Day => Into.Month_Day,
Hour => Into.Hour,
Minute => Into.Minute,
Second => Into.Second,
Sub_Second => Into.Sub_Second,
Leap_Second => Into.Leap_Second,
Time_Zone => Time_Zone);
Into.Day := Ada.Calendar.Formatting.Day_Of_Week (Date);
end Split;
-- ------------------------------
-- Get a time representing the given date at 00:00:00.
-- ------------------------------
function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Day_Start;
function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_Start (D);
end Get_Day_Start;
-- ------------------------------
-- Get a time representing the beginning of the week at 00:00:00.
-- ------------------------------
function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T);
begin
if Day = Ada.Calendar.Formatting.Monday then
return T;
else
return T - Day_Count (Day_Name'Pos (Day) - Day_Name'Pos (Monday));
end if;
end Get_Week_Start;
function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_Start (D);
end Get_Week_Start;
-- ------------------------------
-- Get a time representing the beginning of the month at 00:00:00.
-- ------------------------------
function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Ada.Calendar.Day_Number'First,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Month_Start;
function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_Start (D);
end Get_Month_Start;
end Util.Dates;
|
Implement the new functions Get_Day_Start, Get_Week_Start and Get_Month_Start
|
Implement the new functions Get_Day_Start, Get_Week_Start and Get_Month_Start
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
bb268ae28cadd4a544552968018a7f99a59a1bf6
|
src/wiki-filters-html.ads
|
src/wiki-filters-html.ads
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML 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.
-----------------------------------------------------------------------
private with Ada.Containers.Vectors;
-- === HTML Filters ===
-- The <b>Wiki.Filters.Html</b> package implements a customizable HTML filter that verifies
-- the HTML content embedded in the Wiki text.
--
-- The HTML filter may be declared and configured as follows:
--
-- F : aliased Wiki.Filters.Html.Html_Filter_Type;
-- ...
-- F.Forbidden (Wiki.Filters.Html.SCRIPT_TAG);
-- F.Forbidden (Wiki.Filters.Html.A_TAG);
--
-- The <tt>Set_Document</tt> operation is used to link the HTML filter to a next filter
-- or to the HTML or text renderer:
--
-- F.Set_Document (Renderer'Access);
--
-- The HTML filter is then either inserted as a document for a previous filter or for
-- the wiki parser:
--
-- Wiki.Parsers.Parse (F'Access, Wiki_Text, Syntax);
--
package Wiki.Filters.Html is
use Wiki.Nodes;
-- ------------------------------
-- Filter type
-- ------------------------------
type Html_Filter_Type is new Filter_Type with private;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
overriding
procedure Add_Node (Filter : in out Html_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.
overriding
procedure Add_Text (Filter : in out Html_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.
overriding
procedure Add_Header (Filter : in out Html_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.
overriding
procedure Push_Node (Filter : in out Html_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.
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type);
-- Add a link.
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document);
-- Mark the HTML tag as being forbidden.
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being allowed.
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being visible.
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Flush the HTML element that have not yet been closed.
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document);
private
use Wiki.Nodes;
type Tag_Boolean_Array is array (Html_Tag_Type) of Boolean;
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Html_Tag_Type);
subtype Tag_Vector is Tag_Vectors.Vector;
subtype Tag_Cursor is Tag_Vectors.Cursor;
type Html_Filter_Type is new Filter_Type with record
Allowed : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => False,
HTML_TAG => False,
HEAD_TAG => False,
BODY_TAG => False,
META_TAG => False,
TITLE_TAG => False,
others => True);
Hidden : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => True,
STYLE_TAG => True,
others => False);
Stack : Tag_Vector;
Hide_Level : Natural := 0;
end record;
end Wiki.Filters.Html;
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML 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.
-----------------------------------------------------------------------
private with Ada.Containers.Vectors;
-- === HTML Filters ===
-- The <b>Wiki.Filters.Html</b> package implements a customizable HTML filter that verifies
-- the HTML content embedded in the Wiki text.
--
-- The HTML filter may be declared and configured as follows:
--
-- F : aliased Wiki.Filters.Html.Html_Filter_Type;
-- ...
-- F.Forbidden (Wiki.Filters.Html.SCRIPT_TAG);
-- F.Forbidden (Wiki.Filters.Html.A_TAG);
--
-- The <tt>Set_Document</tt> operation is used to link the HTML filter to a next filter
-- or to the HTML or text renderer:
--
-- F.Set_Document (Renderer'Access);
--
-- The HTML filter is then either inserted as a document for a previous filter or for
-- the wiki parser:
--
-- Wiki.Parsers.Parse (F'Access, Wiki_Text, Syntax);
--
package Wiki.Filters.Html is
use Wiki.Nodes;
-- ------------------------------
-- Filter type
-- ------------------------------
type Html_Filter_Type is new Filter_Type with private;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
overriding
procedure Add_Node (Filter : in out Html_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.
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
overriding
procedure Add_Header (Filter : in out Html_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.
overriding
procedure Push_Node (Filter : in out Html_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.
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type);
-- Add a link.
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Add an image.
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document);
-- Mark the HTML tag as being forbidden.
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being allowed.
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Mark the HTML tag as being visible.
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag_Type);
-- Flush the HTML element that have not yet been closed.
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Nodes.Document);
private
use Wiki.Nodes;
type Tag_Boolean_Array is array (Html_Tag_Type) of Boolean;
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Html_Tag_Type);
subtype Tag_Vector is Tag_Vectors.Vector;
subtype Tag_Cursor is Tag_Vectors.Cursor;
type Html_Filter_Type is new Filter_Type with record
Allowed : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => False,
HTML_TAG => False,
HEAD_TAG => False,
BODY_TAG => False,
META_TAG => False,
TITLE_TAG => False,
others => True);
Hidden : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => True,
STYLE_TAG => True,
others => False);
Stack : Tag_Vector;
Hide_Level : Natural := 0;
end record;
end Wiki.Filters.Html;
|
Use Wiki.Format_Map type
|
Use Wiki.Format_Map type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
752de104a660f8afe2e123059f1958b2edb72bd0
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
package AWA.Wikis.Beans is
type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record
-- The wiki module instance.
Module : Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_View_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_View_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the information about the wiki page to display it.
overriding
procedure Load (Bean : in out Wiki_View_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_View_Bean bean instance.
function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Page Bean
-- ------------------------------
-- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from
-- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member.
-- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the
-- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether
-- we have to create a new version or not.
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
New_Content : Ada.Strings.Unbounded.Unbounded_String;
New_Comment : Ada.Strings.Unbounded.Unbounded_String;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Returns True if the wiki page has a new text content and requires
-- a new version to be created.
function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
package AWA.Wikis.Beans is
type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record
-- The wiki module instance.
Module : Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_View_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_View_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the information about the wiki page to display it.
overriding
procedure Load (Bean : in out Wiki_View_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_View_Bean bean instance.
function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Page Bean
-- ------------------------------
-- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from
-- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member.
-- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the
-- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether
-- we have to create a new version or not.
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
New_Content : Ada.Strings.Unbounded.Unbounded_String;
New_Comment : Ada.Strings.Unbounded.Unbounded_String;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Returns True if the wiki page has a new text content and requires
-- a new version to be created.
function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Version List Bean
-- ------------------------------
type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean;
Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access;
end record;
type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Version_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Version_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_Version_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
Declare the Wiki_Version_List_Bean type with the Get_Value, Set_Value and Load operations
|
Declare the Wiki_Version_List_Bean type with the Get_Value, Set_Value and Load operations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
833679c338c847be3830e3af4e7935bf3faa0232
|
asfunit/asf-tests.adb
|
asfunit/asf-tests.adb
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Regpat;
with Ada.Strings.Unbounded;
with Ada.Unchecked_Deallocation;
with Util.Files;
with ASF.Streams;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Servlets.Measures;
with ASF.Responses;
with ASF.Responses.Tools;
with ASF.Filters.Dump;
with ASF.Contexts.Faces;
with EL.Variables.Default;
package body ASF.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
type Container_Access is access ASF.Server.Container;
Server : Container_Access;
App_Created : ASF.Applications.Main.Application_Access;
App : ASF.Applications.Main.Application_Access;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- Save the response headers and content in a file
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response);
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
begin
if Application /= null then
App := Application;
else
if App_Created = null then
App_Created := new ASF.Applications.Main.Application;
end if;
App := App_Created;
end if;
Server := new ASF.Server.Container;
Server.Register_Application (CONTEXT_PATH, App.all'Access);
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "files", Server => Files'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
App.Add_Servlet (Name => "measures", Server => Measures'Access);
App.Add_Filter (Name => "dump", Filter => Dump'Access);
App.Add_Filter (Name => "measures", Filter => ASF.Filters.Filter'Class (Measures)'Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.properties");
App.Add_Mapping (Name => "files", Pattern => "*.xhtml");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
App.Add_Mapping (Name => "measures", Pattern => "stats.xml");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*");
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class,
Name => ASF.Applications.Main.Application_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Server.Container,
Name => Container_Access);
begin
Free (App_Created);
Free (Server);
end Finish;
-- ------------------------------
-- Get the server
-- ------------------------------
function Get_Server return access ASF.Server.Container is
begin
return Server;
end Get_Server;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Save the response headers and content in a file
-- ------------------------------
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response) is
use ASF.Responses;
Info : constant String := Tools.To_String (Reply => Response,
Html => False,
Print_Headers => True);
Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result");
Content : Unbounded_String;
Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Response.Read_Content (Content);
Stream.Write (Content);
Insert (Content, 1, Info);
Util.Files.Write_File (Result_Path & "/" & Name, Content);
end Save_Response;
-- ------------------------------
-- Simulate a raw request. The URI and method must have been set on the Request object.
-- ------------------------------
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response) is
begin
-- For the purpose of writing tests, clear the buffer before invoking the service.
Response.Clear;
Server.Service (Request => Request,
Response => Response);
end Do_Req;
-- ------------------------------
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "GET");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI, Split => True);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Get;
-- ------------------------------
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "POST");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI, Split => False);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Post;
-- ------------------------------
-- Check that the response body contains the string
-- ------------------------------
procedure Assert_Contains (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Index (Content, Value) > 0,
Message => Message & ": value '" & Value & "' not found",
Source => Source,
Line => Line);
end Assert_Contains;
-- ------------------------------
-- Check that the response body matches the regular expression
-- ------------------------------
procedure Assert_Matches (T : in Util.Tests.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Status : in Natural := ASF.Responses.SC_OK;
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
use GNAT.Regpat;
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
Regexp : constant Pattern_Matcher := Compile (Expression => Pattern,
Flags => Multiple_Lines);
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, Status, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Match (Regexp, To_String (Content)),
Message => Message & ": does not match '" & Pattern & "'",
Source => Source,
Line => Line);
end Assert_Matches;
-- ------------------------------
-- Check that the response contains the given header.
-- ------------------------------
procedure Assert_Header (T : in Util.Tests.Test'Class;
Header : in String;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Status : in Natural := ASF.Responses.SC_OK;
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
begin
Assert_Equals (T, Status, Reply.Get_Status,
"Invalid response status", Source, Line);
T.Assert (Condition => Reply.Contains_Header (Header),
Message => Message & ": missing header '" & Header & "'",
Source => Source,
Line => Line);
Assert_Equals (T, Value, Reply.Get_Header (Header), Message, Source, Line);
end Assert_Header;
-- ------------------------------
-- Check that the response body is a redirect to the given URI.
-- ------------------------------
procedure Assert_Redirect (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
begin
Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status,
"Invalid response", Source, Line);
Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"),
Message & ": missing Location",
Source, Line);
end Assert_Redirect;
-- ------------------------------
-- Cleanup the test instance.
-- ------------------------------
overriding
procedure Tear_Down (T : in out EL_Test) is
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class,
EL.Contexts.Default.Default_Context_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class,
EL.Variables.Variable_Mapper_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class,
EL.Contexts.Default.Default_ELResolver_Access);
begin
ASF.Contexts.Faces.Restore (null);
Free (T.ELContext);
Free (T.Variables);
Free (T.Root_Resolver);
end Tear_Down;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out EL_Test) is
begin
T.ELContext := new EL.Contexts.Default.Default_Context;
T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver;
T.Variables := new EL.Variables.Default.Default_Variable_Mapper;
T.ELContext.Set_Resolver (T.Root_Resolver.all'Access);
T.ELContext.Set_Variable_Mapper (T.Variables.all'Access);
end Set_Up;
end ASF.Tests;
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Regpat;
with Ada.Strings.Unbounded;
with Ada.Unchecked_Deallocation;
with Util.Files;
with ASF.Streams;
with ASF.Servlets.Faces;
with Servlet.Core.Files;
with ASF.Servlets.Ajax;
with Servlet.Core.Measures;
with ASF.Responses;
with ASF.Responses.Tools;
with ASF.Filters.Dump;
with ASF.Contexts.Faces;
with EL.Variables.Default;
package body ASF.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
type Container_Access is access ASF.Server.Container;
App_Created : ASF.Applications.Main.Application_Access;
App : ASF.Applications.Main.Application_Access;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Measures : aliased Servlet.Core.Measures.Measure_Servlet;
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
begin
if Application /= null then
App := Application;
else
if App_Created = null then
App_Created := new ASF.Applications.Main.Application;
end if;
App := App_Created;
end if;
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
Servlet.Tests.Initialize (Props, CONTEXT_PATH, App.all'Access);
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Cleanup the test instance.
-- ------------------------------
overriding
procedure Tear_Down (T : in out EL_Test) is
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class,
EL.Contexts.Default.Default_Context_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class,
EL.Variables.Variable_Mapper_Access);
procedure Free is
new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class,
EL.Contexts.Default.Default_ELResolver_Access);
begin
ASF.Contexts.Faces.Restore (null);
Free (T.ELContext);
Free (T.Variables);
Free (T.Root_Resolver);
end Tear_Down;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out EL_Test) is
begin
T.ELContext := new EL.Contexts.Default.Default_Context;
T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver;
T.Variables := new EL.Variables.Default.Default_Variable_Mapper;
T.ELContext.Set_Resolver (T.Root_Resolver.all'Access);
T.ELContext.Set_Variable_Mapper (T.Variables.all'Access);
end Set_Up;
end ASF.Tests;
|
Package ASF.Tests moved to Servlet.Tests
|
Package ASF.Tests moved to Servlet.Tests
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
4b97d8a77efb4169bf7439622289f5878cad22f0
|
awa/plugins/awa-mail/src/awa-mail-components-messages.adb
|
awa/plugins/awa-mail/src/awa-mail-components-messages.adb
|
-----------------------------------------------------------------------
-- awa-mail-components-messages -- Mail UI Message
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with ASF.Components.Base;
with AWA.Mail.Clients;
package body AWA.Mail.Components.Messages is
use Ada.Strings.Unbounded;
use type ASF.Components.Base.UIComponent_Access;
-- ------------------------------
-- Set the mail message instance.
-- ------------------------------
procedure Set_Message (UI : in out UIMailMessage;
Message : in AWA.Mail.Clients.Mail_Message_Access) is
begin
UI.Message := Message;
end Set_Message;
-- ------------------------------
-- Get the mail message instance.
-- ------------------------------
overriding
function Get_Message (UI : in UIMailMessage) return AWA.Mail.Clients.Mail_Message_Access is
begin
return UI.Message;
end Get_Message;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIMailMessage;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type AWA.Mail.Clients.Mail_Message_Access;
begin
if UI.Message /= null and UI.Is_Rendered (Context) then
UI.Message.Send;
end if;
end Encode_End;
-- ------------------------------
-- Finalize and release the mail message.
-- ------------------------------
overriding
procedure Finalize (UI : in out UIMailMessage) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Mail.Clients.Mail_Message'Class,
Name => AWA.Mail.Clients.Mail_Message_Access);
begin
Free (UI.Message);
end Finalize;
-- ------------------------------
-- Render the mail subject and initializes the message with its content.
-- ------------------------------
overriding
procedure Encode_Children (UI : in UIMailSubject;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
procedure Process (Content : in String);
procedure Process (Content : in String) is
Msg : constant AWA.Mail.Clients.Mail_Message_Access := UI.Get_Message;
begin
Msg.Set_Subject (Content);
end Process;
begin
UI.Wrap_Encode_Children (Context, Process'Access);
end Encode_Children;
-- ------------------------------
-- Render the mail body and initializes the message with its content.
-- ------------------------------
overriding
procedure Encode_Children (UI : in UIMailBody;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
procedure Process (Content : in Unbounded_String);
procedure Process_Alternative (Content : in Unbounded_String);
Body_Type : Util.Beans.Objects.Object;
Alternative_Content : Unbounded_String;
procedure Process_Alternative (Content : in Unbounded_String) is
begin
Alternative_Content := Content;
end Process_Alternative;
procedure Process (Content : in Unbounded_String) is
Msg : constant AWA.Mail.Clients.Mail_Message_Access := UI.Get_Message;
Typ : constant String := Util.Beans.Objects.To_String (Body_Type);
begin
if not Util.Beans.Objects.Is_Empty (Body_Type) then
Msg.Set_Body (Content, Alternative_Content, Typ);
else
Msg.Set_Body (Content, Alternative_Content);
end if;
end Process;
Alternative_Facet : ASF.Components.Base.UIComponent_Access;
begin
Body_Type := UI.Get_Attribute (Name => "type", Context => Context);
Alternative_Facet := UI.Get_Facet (ALTERNATIVE_NAME);
if Alternative_Facet /= null then
Alternative_Facet.Wrap_Encode_Children (Context, Process_Alternative'Access);
end if;
UI.Wrap_Encode_Children (Context, Process'Access);
end Encode_Children;
end AWA.Mail.Components.Messages;
|
-----------------------------------------------------------------------
-- awa-mail-components-messages -- Mail UI Message
-- Copyright (C) 2012, 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.Unchecked_Deallocation;
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with ASF.Components.Base;
with AWA.Mail.Clients;
package body AWA.Mail.Components.Messages is
use Ada.Strings.Unbounded;
use type ASF.Components.Base.UIComponent_Access;
-- ------------------------------
-- Set the mail message instance.
-- ------------------------------
procedure Set_Message (UI : in out UIMailMessage;
Message : in AWA.Mail.Clients.Mail_Message_Access) is
begin
UI.Message := Message;
end Set_Message;
-- ------------------------------
-- Get the mail message instance.
-- ------------------------------
overriding
function Get_Message (UI : in UIMailMessage) return AWA.Mail.Clients.Mail_Message_Access is
begin
return UI.Message;
end Get_Message;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIMailMessage;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type AWA.Mail.Clients.Mail_Message_Access;
begin
if UI.Message /= null and UI.Is_Rendered (Context) then
UI.Message.Send;
end if;
end Encode_End;
-- ------------------------------
-- Finalize and release the mail message.
-- ------------------------------
overriding
procedure Finalize (UI : in out UIMailMessage) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Mail.Clients.Mail_Message'Class,
Name => AWA.Mail.Clients.Mail_Message_Access);
begin
Free (UI.Message);
UIMailComponent (UI).Finalize;
end Finalize;
-- ------------------------------
-- Render the mail subject and initializes the message with its content.
-- ------------------------------
overriding
procedure Encode_Children (UI : in UIMailSubject;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
procedure Process (Content : in String);
procedure Process (Content : in String) is
Msg : constant AWA.Mail.Clients.Mail_Message_Access := UI.Get_Message;
begin
Msg.Set_Subject (Content);
end Process;
begin
UI.Wrap_Encode_Children (Context, Process'Access);
end Encode_Children;
-- ------------------------------
-- Render the mail body and initializes the message with its content.
-- ------------------------------
overriding
procedure Encode_Children (UI : in UIMailBody;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
procedure Process (Content : in Unbounded_String);
procedure Process_Alternative (Content : in Unbounded_String);
Body_Type : Util.Beans.Objects.Object;
Alternative_Content : Unbounded_String;
procedure Process_Alternative (Content : in Unbounded_String) is
begin
Alternative_Content := Content;
end Process_Alternative;
procedure Process (Content : in Unbounded_String) is
Msg : constant AWA.Mail.Clients.Mail_Message_Access := UI.Get_Message;
Typ : constant String := Util.Beans.Objects.To_String (Body_Type);
begin
if not Util.Beans.Objects.Is_Empty (Body_Type) then
Msg.Set_Body (Content, Alternative_Content, Typ);
else
Msg.Set_Body (Content, Alternative_Content);
end if;
end Process;
Alternative_Facet : ASF.Components.Base.UIComponent_Access;
begin
Body_Type := UI.Get_Attribute (Name => "type", Context => Context);
Alternative_Facet := UI.Get_Facet (ALTERNATIVE_NAME);
if Alternative_Facet /= null then
Alternative_Facet.Wrap_Encode_Children (Context, Process_Alternative'Access);
end if;
UI.Wrap_Encode_Children (Context, Process'Access);
end Encode_Children;
end AWA.Mail.Components.Messages;
|
Fix Finalize to call the base typ Finalize procedure to make sure we release the sub-tree of components!
|
Fix Finalize to call the base typ Finalize procedure to make sure we release the sub-tree of components!
|
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.