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
|
---|---|---|---|---|---|---|---|---|---|
b126e886898598ce4ed0e18c4ef3678c6d6b340e
|
src/gen-model-packages.ads
|
src/gen-model-packages.ads
|
-----------------------------------------------------------------------
-- gen-model-packages -- Packages holding model, query representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Gen.Model.List;
with Gen.Model.Mappings;
limited with Gen.Model.Enums;
limited with Gen.Model.Tables;
limited with Gen.Model.Queries;
limited with Gen.Model.Beans;
package Gen.Model.Packages is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Package Definition
-- ------------------------------
-- The <b>Package_Definition</b> holds the tables, queries and other information
-- that must be generated for a given Ada package.
type Package_Definition is new Definition with private;
type Package_Definition_Access is access all Package_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 Package_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
overriding
procedure Prepare (O : in out Package_Definition);
-- Initialize the package instance
overriding
procedure Initialize (O : in out Package_Definition);
-- Find the type identified by the name.
function Find_Type (From : in Package_Definition;
Name : in Unbounded_String)
return Gen.Model.Mappings.Mapping_Definition_Access;
-- ------------------------------
-- Model Definition
-- ------------------------------
-- The <b>Model_Definition</b> contains the complete model from one or
-- several files. It maintains a list of Ada packages that must be generated.
type Model_Definition is new Definition with private;
type Model_Definition_Access is access all Model_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 : Model_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Initialize the model definition instance.
overriding
procedure Initialize (O : in out Model_Definition);
-- Returns True if the model contains at least one package.
function Has_Packages (O : in Model_Definition) return Boolean;
-- Register or find the package knowing its name
procedure Register_Package (O : in out Model_Definition;
Name : in Unbounded_String;
Result : out Package_Definition_Access);
-- Register the declaration of the given enum in the model.
procedure Register_Enum (O : in out Model_Definition;
Enum : access Gen.Model.Enums.Enum_Definition'Class);
-- Register the declaration of the given table in the model.
procedure Register_Table (O : in out Model_Definition;
Table : access Gen.Model.Tables.Table_Definition'Class);
-- Register the declaration of the given query in the model.
procedure Register_Query (O : in out Model_Definition;
Table : access Gen.Model.Queries.Query_Definition'Class);
-- Register the declaration of the given bean in the model.
procedure Register_Bean (O : in out Model_Definition;
Bean : access Gen.Model.Beans.Bean_Definition'Class);
-- Register a type mapping. The <b>From</b> type describes a type in the XML
-- configuration files (hibernate, query, ...) and the <b>To</b> represents the
-- corresponding Ada type.
procedure Register_Type (O : in out Model_Definition;
From : in String;
To : in String);
-- Find the type identified by the name.
function Find_Type (From : in Model_Definition;
Name : in Unbounded_String)
return Gen.Model.Mappings.Mapping_Definition_Access;
-- Set the directory name associated with the model. This directory name allows to
-- save and build a model in separate directories for the application, the unit tests
-- and others.
procedure Set_Dirname (O : in out Model_Definition;
Target_Dir : in String;
Model_Dir : in String);
-- Get the directory name associated with the model.
function Get_Dirname (O : in Model_Definition) return String;
-- Get the directory name which contains the model.
function Get_Model_Directory (O : in Model_Definition) return String;
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
overriding
procedure Prepare (O : in out Model_Definition);
package Package_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Package_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Package_Cursor is Package_Map.Cursor;
-- Get the first package of the model definition.
function First (From : Model_Definition) return Package_Cursor;
-- Returns true if the package cursor contains a valid package
function Has_Element (Position : Package_Cursor) return Boolean
renames Package_Map.Has_Element;
-- Returns the package definition.
function Element (Position : Package_Cursor) return Package_Definition_Access
renames Package_Map.Element;
-- Move the iterator to the next package definition.
procedure Next (Position : in out Package_Cursor)
renames Package_Map.Next;
private
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
subtype Table_List_Definition is Table_List.List_Definition;
subtype Enum_List_Definition is Table_List.List_Definition;
type List_Object is new Util.Beans.Basic.List_Bean with record
Values : Util.Beans.Objects.Vectors.Vector;
Row : Natural;
Value_Bean : Util.Beans.Objects.Object;
end record;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in List_Object) return Natural;
-- Set the current row index. Valid row indexes start at 1.
overriding
procedure Set_Row_Index (From : in out List_Object;
Index : in Natural);
-- Get the element at the current row index.
overriding
function Get_Row (From : in List_Object) return Util.Beans.Objects.Object;
-- 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 List_Object;
Name : in String) return Util.Beans.Objects.Object;
type Package_Definition is new Definition with record
-- Enums defined in the package.
Enums : aliased Enum_List_Definition;
Enums_Bean : Util.Beans.Objects.Object;
-- Hibernate tables
Tables : aliased Table_List_Definition;
Tables_Bean : Util.Beans.Objects.Object;
-- Custom queries
Queries : aliased Table_List_Definition;
Queries_Bean : Util.Beans.Objects.Object;
-- Ada Beans
Beans : aliased Table_List_Definition;
Beans_Bean : Util.Beans.Objects.Object;
-- A list of external packages which are used (used for with clause generation).
Used_Types : aliased List_Object;
Used : Util.Beans.Objects.Object;
-- A map of all types defined in this package.
Types : Gen.Model.Mappings.Mapping_Maps.Map;
-- The package Ada name
Pkg_Name : Unbounded_String;
-- The base name for the package (ex: gen-model-users)
Base_Name : Unbounded_String;
-- True if the package uses Ada.Calendar.Time
Uses_Calendar_Time : Boolean := False;
-- The global model (used to resolve types from other packages).
Model : Model_Definition_Access;
end record;
type Model_Definition is new Definition with record
-- List of all enums.
Enums : aliased Enum_List_Definition;
Enums_Bean : Util.Beans.Objects.Object;
-- List of all tables.
Tables : aliased Table_List_Definition;
Tables_Bean : Util.Beans.Objects.Object;
-- List of all queries.
Queries : aliased Table_List_Definition;
Queries_Bean : Util.Beans.Objects.Object;
-- Ada Beans
Beans : aliased Table_List_Definition;
Beans_Bean : Util.Beans.Objects.Object;
-- Map of all packages.
Packages : Package_Map.Map;
-- Directory associated with the model ('src', 'samples', 'regtests', ...).
Dir_Name : Unbounded_String;
-- Directory that contains the SQL and model files.
DB_Name : Unbounded_String;
end record;
end Gen.Model.Packages;
|
-----------------------------------------------------------------------
-- gen-model-packages -- Packages holding model, query representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Gen.Model.List;
with Gen.Model.Mappings;
limited with Gen.Model.Enums;
limited with Gen.Model.Tables;
limited with Gen.Model.Queries;
limited with Gen.Model.Beans;
package Gen.Model.Packages is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Model Definition
-- ------------------------------
-- The <b>Model_Definition</b> contains the complete model from one or
-- several files. It maintains a list of Ada packages that must be generated.
type Model_Definition is new Definition with private;
type Model_Definition_Access is access all Model_Definition'Class;
-- ------------------------------
-- Package Definition
-- ------------------------------
-- The <b>Package_Definition</b> holds the tables, queries and other information
-- that must be generated for a given Ada package.
type Package_Definition is new Definition with private;
type Package_Definition_Access is access all Package_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 Package_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
overriding
procedure Prepare (O : in out Package_Definition);
-- Initialize the package instance
overriding
procedure Initialize (O : in out Package_Definition);
-- Find the type identified by the name.
function Find_Type (From : in Package_Definition;
Name : in Unbounded_String)
return Gen.Model.Mappings.Mapping_Definition_Access;
-- Get the model which contains all the package definitions.
function Get_Model (From : in Package_Definition)
return Model_Definition_Access;
-- 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 : Model_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Initialize the model definition instance.
overriding
procedure Initialize (O : in out Model_Definition);
-- Returns True if the model contains at least one package.
function Has_Packages (O : in Model_Definition) return Boolean;
-- Register or find the package knowing its name
procedure Register_Package (O : in out Model_Definition;
Name : in Unbounded_String;
Result : out Package_Definition_Access);
-- Register the declaration of the given enum in the model.
procedure Register_Enum (O : in out Model_Definition;
Enum : access Gen.Model.Enums.Enum_Definition'Class);
-- Register the declaration of the given table in the model.
procedure Register_Table (O : in out Model_Definition;
Table : access Gen.Model.Tables.Table_Definition'Class);
-- Register the declaration of the given query in the model.
procedure Register_Query (O : in out Model_Definition;
Table : access Gen.Model.Queries.Query_Definition'Class);
-- Register the declaration of the given bean in the model.
procedure Register_Bean (O : in out Model_Definition;
Bean : access Gen.Model.Beans.Bean_Definition'Class);
-- Register a type mapping. The <b>From</b> type describes a type in the XML
-- configuration files (hibernate, query, ...) and the <b>To</b> represents the
-- corresponding Ada type.
procedure Register_Type (O : in out Model_Definition;
From : in String;
To : in String);
-- Find the type identified by the name.
function Find_Type (From : in Model_Definition;
Name : in Unbounded_String)
return Gen.Model.Mappings.Mapping_Definition_Access;
-- Set the directory name associated with the model. This directory name allows to
-- save and build a model in separate directories for the application, the unit tests
-- and others.
procedure Set_Dirname (O : in out Model_Definition;
Target_Dir : in String;
Model_Dir : in String);
-- Get the directory name associated with the model.
function Get_Dirname (O : in Model_Definition) return String;
-- Get the directory name which contains the model.
function Get_Model_Directory (O : in Model_Definition) return String;
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
overriding
procedure Prepare (O : in out Model_Definition);
package Package_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Package_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
subtype Package_Cursor is Package_Map.Cursor;
-- Get the first package of the model definition.
function First (From : Model_Definition) return Package_Cursor;
-- Returns true if the package cursor contains a valid package
function Has_Element (Position : Package_Cursor) return Boolean
renames Package_Map.Has_Element;
-- Returns the package definition.
function Element (Position : Package_Cursor) return Package_Definition_Access
renames Package_Map.Element;
-- Move the iterator to the next package definition.
procedure Next (Position : in out Package_Cursor)
renames Package_Map.Next;
private
package Table_List is new Gen.Model.List (T => Definition,
T_Access => Definition_Access);
subtype Table_List_Definition is Table_List.List_Definition;
subtype Enum_List_Definition is Table_List.List_Definition;
type List_Object is new Util.Beans.Basic.List_Bean with record
Values : Util.Beans.Objects.Vectors.Vector;
Row : Natural;
Value_Bean : Util.Beans.Objects.Object;
end record;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in List_Object) return Natural;
-- Set the current row index. Valid row indexes start at 1.
overriding
procedure Set_Row_Index (From : in out List_Object;
Index : in Natural);
-- Get the element at the current row index.
overriding
function Get_Row (From : in List_Object) return Util.Beans.Objects.Object;
-- 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 List_Object;
Name : in String) return Util.Beans.Objects.Object;
type Package_Definition is new Definition with record
-- Enums defined in the package.
Enums : aliased Enum_List_Definition;
Enums_Bean : Util.Beans.Objects.Object;
-- Hibernate tables
Tables : aliased Table_List_Definition;
Tables_Bean : Util.Beans.Objects.Object;
-- Custom queries
Queries : aliased Table_List_Definition;
Queries_Bean : Util.Beans.Objects.Object;
-- Ada Beans
Beans : aliased Table_List_Definition;
Beans_Bean : Util.Beans.Objects.Object;
-- A list of external packages which are used (used for with clause generation).
Used_Types : aliased List_Object;
Used : Util.Beans.Objects.Object;
-- A map of all types defined in this package.
Types : Gen.Model.Mappings.Mapping_Maps.Map;
-- The package Ada name
Pkg_Name : Unbounded_String;
-- The base name for the package (ex: gen-model-users)
Base_Name : Unbounded_String;
-- True if the package uses Ada.Calendar.Time
Uses_Calendar_Time : Boolean := False;
-- The global model (used to resolve types from other packages).
Model : Model_Definition_Access;
end record;
type Model_Definition is new Definition with record
-- List of all enums.
Enums : aliased Enum_List_Definition;
Enums_Bean : Util.Beans.Objects.Object;
-- List of all tables.
Tables : aliased Table_List_Definition;
Tables_Bean : Util.Beans.Objects.Object;
-- List of all queries.
Queries : aliased Table_List_Definition;
Queries_Bean : Util.Beans.Objects.Object;
-- Ada Beans
Beans : aliased Table_List_Definition;
Beans_Bean : Util.Beans.Objects.Object;
-- Map of all packages.
Packages : Package_Map.Map;
-- Directory associated with the model ('src', 'samples', 'regtests', ...).
Dir_Name : Unbounded_String;
-- Directory that contains the SQL and model files.
DB_Name : Unbounded_String;
end record;
end Gen.Model.Packages;
|
Define new function Get_Model
|
Define new function Get_Model
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
399392a130175ae231473fb582ed83baf12f0873
|
src/util-streams-files.ads
|
src/util-streams-files.ads
|
-----------------------------------------------------------------------
-- Util.Streams.Files -- File Stream utilities
-- Copyright (C) 2010, 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.Finalization;
with Ada.Streams.Stream_IO;
package Util.Streams.Files is
-- -----------------------
-- File stream
-- -----------------------
-- The <b>File_Stream</b> is an output/input stream that reads or writes
-- into a file-based stream.
type File_Stream is limited new Output_Stream and Input_Stream with private;
-- Open the file and initialize the stream for reading or writing.
procedure Open (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "");
-- Create the file and initialize the stream for writing.
procedure Create (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "");
-- Close the stream.
overriding
procedure Close (Stream : in out File_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out File_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 File_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type File_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
File : Ada.Streams.Stream_IO.File_Type;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out File_Stream);
end Util.Streams.Files;
|
-----------------------------------------------------------------------
-- util-streams-files -- File Stream utilities
-- Copyright (C) 2010, 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 Ada.Streams.Stream_IO;
package Util.Streams.Files is
-- -----------------------
-- File stream
-- -----------------------
-- The <b>File_Stream</b> is an output/input stream that reads or writes
-- into a file-based stream.
type File_Stream is limited new Output_Stream and Input_Stream with private;
-- Open the file and initialize the stream for reading or writing.
procedure Open (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "");
-- Create the file and initialize the stream for writing.
procedure Create (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "");
-- Close the stream.
overriding
procedure Close (Stream : in out File_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out File_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 File_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type File_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
File : Ada.Streams.Stream_IO.File_Type;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out File_Stream);
end Util.Streams.Files;
|
Update the header
|
Update the header
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
26e587c0685066509adc7ecb2569c3854c51badc
|
src/security-auth-oauth.adb
|
src/security-auth-oauth.adb
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
null;
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Assoc_Handle := To_Unbounded_String ("nonce-generator");
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
Add the response_type in the request parameter
|
Add the response_type in the request parameter
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
4fc84a695077f4a1bfb1767ee1b91837303ef20f
|
src/wiki-buffers.adb
|
src/wiki-buffers.adb
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 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 Ada.Unchecked_Deallocation;
package body Wiki.Buffers is
subtype Input is Wiki.Strings.WString;
subtype Block_Access is Buffer_Access;
-- ------------------------------
-- Move forward to skip a number of items.
-- ------------------------------
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive) is
begin
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
else
Pos := Pos + 1;
end if;
end Next;
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive;
Count : in Natural) is
begin
for I in 1 .. Count loop
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
else
Pos := Pos + 1;
end if;
end loop;
end Next;
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Buffer (Size);
else
B.Next_Block := new Buffer (Source.Block_Size);
end if;
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
procedure Inline_Append (Source : in out Builder) is
B : Block_Access := Source.Current;
Last : Natural;
begin
loop
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Process (B.Content (B.Last + 1 .. B.Len), Last);
exit when Last > B.Len or Last <= B.Last;
Source.Length := Source.Length + Last - B.Last;
B.Last := Last;
exit when Last < B.Len;
end loop;
end Inline_Append;
-- ------------------------------
-- 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) is
begin
if From <= Content.First.Last then
if To <= Content.First.Last then
Append (Into, Content.First.Content (From .. To));
return;
end if;
Append (Into, Content.First.Content (From .. Content.First.Last));
end if;
declare
Pos : Integer := From - Into.First.Last;
Last : Integer := To - Into.First.Last;
B : Block_Access := Into.First.Next_Block;
begin
loop
if B = null then
return;
end if;
if Pos <= B.Last then
if Last <= B.Last then
Append (Into, B.Content (1 .. Last));
return;
end if;
Append (Into, B.Content (1 .. B.Last));
end if;
Pos := Pos - B.Last;
Last := Last - B.Last;
B := B.Next_Block;
end loop;
end;
end Append;
procedure Append (Into : in out Builder;
Buffer : in Buffer_Access;
From : in Positive) is
Block : Buffer_Access := Buffer;
Pos : Positive := From;
First : Positive := From;
begin
while Block /= null loop
Append (Into, Block.Content (First .. Block.Last));
Block := Block.Next_Block;
Pos := 1;
First := 1;
end loop;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- 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)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
procedure Inline_Iterate (Source : in Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Iterate;
procedure Inline_Update (Source : in out Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Update;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Buffer := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
function Element (Source : in Builder;
Position : in Positive) return Wiki.Strings.WChar is
begin
if Position <= Source.First.Last then
return Source.First.Content (Position);
else
declare
Pos : Positive := Position - Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if Pos <= B.Last then
return B.Content (Pos);
end if;
Pos := Pos - B.Last;
B := B.Next_Block;
end loop;
end;
end if;
end Element;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
function Count_Occurence (Buffer : in Buffer_Access;
From : in Positive;
Item : in Wiki.Strings.WChar) return Natural is
Count : Natural := 0;
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
while Current /= null loop
declare
First : Positive := Pos;
Last : Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
return Count;
end Count_Occurence;
procedure Count_Occurence (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar;
Count : out Natural) is
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
while Current /= null loop
declare
First : Positive := From;
Last : Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
Buffer := Current;
From := Pos;
end Count_Occurence;
procedure Find (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar) is
Pos : Positive := From;
begin
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
if Buffer.Content (Pos) = Item then
From := Pos;
return;
end if;
Pos := Pos + 1;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop;
end Find;
end Wiki.Buffers;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 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 Ada.Unchecked_Deallocation;
package body Wiki.Buffers is
subtype Input is Wiki.Strings.WString;
subtype Block_Access is Buffer_Access;
-- ------------------------------
-- Move forward to skip a number of items.
-- ------------------------------
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive) is
begin
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
else
Pos := Pos + 1;
end if;
end Next;
procedure Next (Content : in out Buffer_Access;
Pos : in out Positive;
Count : in Natural) is
begin
for I in 1 .. Count loop
if Pos + 1 > Content.Last then
Content := Content.Next_Block;
Pos := 1;
else
Pos := Pos + 1;
end if;
end loop;
end Next;
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Buffer (Size);
else
B.Next_Block := new Buffer (Source.Block_Size);
end if;
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
procedure Inline_Append (Source : in out Builder) is
B : Block_Access := Source.Current;
Last : Natural;
begin
loop
if B.Len = B.Last then
B.Next_Block := new Buffer (Source.Block_Size);
B.Next_Block.Offset := B.Offset + B.Len;
B := B.Next_Block;
Source.Current := B;
end if;
Process (B.Content (B.Last + 1 .. B.Len), Last);
exit when Last > B.Len or Last <= B.Last;
Source.Length := Source.Length + Last - B.Last;
B.Last := Last;
exit when Last < B.Len;
end loop;
end Inline_Append;
-- ------------------------------
-- 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) is
begin
if From <= Content.First.Last then
if To <= Content.First.Last then
Append (Into, Content.First.Content (From .. To));
return;
end if;
Append (Into, Content.First.Content (From .. Content.First.Last));
end if;
declare
Pos : Integer := From - Into.First.Last;
Last : Integer := To - Into.First.Last;
B : Block_Access := Into.First.Next_Block;
begin
loop
if B = null then
return;
end if;
if Pos <= B.Last then
if Last <= B.Last then
Append (Into, B.Content (1 .. Last));
return;
end if;
Append (Into, B.Content (1 .. B.Last));
end if;
Pos := Pos - B.Last;
Last := Last - B.Last;
B := B.Next_Block;
end loop;
end;
end Append;
procedure Append (Into : in out Builder;
Buffer : in Buffer_Access;
From : in Positive) is
Block : Buffer_Access := Buffer;
First : Positive := From;
begin
while Block /= null loop
Append (Into, Block.Content (First .. Block.Last));
Block := Block.Next_Block;
First := 1;
end loop;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- 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)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
procedure Inline_Iterate (Source : in Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Iterate;
procedure Inline_Update (Source : in out Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Update;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Buffer := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
function Element (Source : in Builder;
Position : in Positive) return Wiki.Strings.WChar is
begin
if Position <= Source.First.Last then
return Source.First.Content (Position);
else
declare
Pos : Positive := Position - Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if Pos <= B.Last then
return B.Content (Pos);
end if;
Pos := Pos - B.Last;
B := B.Next_Block;
end loop;
end;
end if;
end Element;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
function Count_Occurence (Buffer : in Buffer_Access;
From : in Positive;
Item : in Wiki.Strings.WChar) return Natural is
Count : Natural := 0;
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
while Current /= null loop
declare
First : constant Positive := Pos;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
return Count;
end Count_Occurence;
procedure Count_Occurence (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar;
Count : out Natural) is
Current : Buffer_Access := Buffer;
Pos : Positive := From;
begin
Count := 0;
while Current /= null loop
declare
First : constant Positive := From;
Last : constant Natural := Current.Last;
begin
while Pos <= Last and then Current.Content (Pos) = Item loop
Pos := Pos + 1;
end loop;
if Pos > First then
Count := Count + Pos - First;
end if;
exit when Pos <= Last;
end;
Current := Current.Next_Block;
Pos := 1;
end loop;
Buffer := Current;
From := Pos;
end Count_Occurence;
procedure Find (Buffer : in out Buffer_Access;
From : in out Positive;
Item : in Wiki.Strings.WChar) is
Pos : Positive := From;
begin
while Buffer /= null loop
declare
Last : constant Natural := Buffer.Last;
begin
while Pos <= Last loop
if Buffer.Content (Pos) = Item then
From := Pos;
return;
end if;
Pos := Pos + 1;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop;
end Find;
end Wiki.Buffers;
|
Fix compilation warning: add constant to some local variables
|
Fix compilation warning: add constant to some local variables
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
0c383f8e71c6a37e809083f9e3c68be6bac94c0a
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
use Wiki.Strings.Wide_Wide_Builders;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wiki.Strings.WChar);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access constant Parser_Table;
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Previous_Syntax : Wiki_Syntax;
Table : Parser_Table_Access;
Document : Wiki.Documents.Document;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
In_Table : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser'Class;
Token : out Wiki.Strings.WChar);
pragma Inline (Peek);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Parse_Token (P : in out Parser);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence. This procedure
-- is instantiated for several format types (bold, italic, superscript, subscript, code).
-- Example:
-- --name-- **bold** ~~strike~~
generic
Format : Format_Type;
procedure Parse_Double_Format (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse the beginning or the end of a single character sequence. This procedure
-- is instantiated for several format types (bold, italic, superscript, subscript, code).
-- Example:
-- _name_ *bold* `code`
generic
Format : Format_Type;
procedure Parse_Single_Format (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse a space and take necessary formatting actions.
-- Example:
-- item1 item2 => add space in text buffer
-- ' * item' => start a bullet list (Google)
-- ' # item' => start an ordered list (Google)
-- ' item' => preformatted text (Google, Creole)
procedure Parse_Space (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse a HTML component.
-- Example:
-- <b> or </b>
procedure Parse_Maybe_Html (P : in out Parser;
Token : in Wiki.Strings.WChar);
procedure Parse_End_Line (P : in out Parser;
Token : in Wiki.Strings.WChar);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
use Wiki.Strings.Wide_Wide_Builders;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wiki.Strings.WChar);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access constant Parser_Table;
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Previous_Syntax : Wiki_Syntax;
Table : Parser_Table_Access;
Document : Wiki.Documents.Document;
Format : Wiki.Format_Map;
Line : Wiki.Strings.BString (512);
Text : Wiki.Strings.BString (512);
Line_Length : Natural := 0;
Line_Pos : Natural := 0;
Empty_Line : Boolean := True;
Is_Last_Line : Boolean := False;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
In_Table : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
-- Read the next wiki input line in the line buffer.
procedure Read_Line (P : in out Parser'Class);
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser'Class;
Token : out Wiki.Strings.WChar);
pragma Inline (Peek);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Parse_Token (P : in out Parser);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence. This procedure
-- is instantiated for several format types (bold, italic, superscript, subscript, code).
-- Example:
-- --name-- **bold** ~~strike~~
generic
Format : Format_Type;
procedure Parse_Double_Format (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse the beginning or the end of a single character sequence. This procedure
-- is instantiated for several format types (bold, italic, superscript, subscript, code).
-- Example:
-- _name_ *bold* `code`
generic
Format : Format_Type;
procedure Parse_Single_Format (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse a space and take necessary formatting actions.
-- Example:
-- item1 item2 => add space in text buffer
-- ' * item' => start a bullet list (Google)
-- ' # item' => start an ordered list (Google)
-- ' item' => preformatted text (Google, Creole)
procedure Parse_Space (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse a HTML component.
-- Example:
-- <b> or </b>
procedure Parse_Maybe_Html (P : in out Parser;
Token : in Wiki.Strings.WChar);
procedure Parse_End_Line (P : in out Parser;
Token : in Wiki.Strings.WChar);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
Add a Read_Line private procedure Add a line buffer in the parser with a length and current position
|
Add a Read_Line private procedure
Add a line buffer in the parser with a length and current position
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
54421d0e0e79619138f315487c9855039e0524e3
|
awa/plugins/awa-wikis/src/awa-wikis-beans.adb
|
awa/plugins/awa-wikis/src/awa-wikis-beans.adb
|
-----------------------------------------------------------------------
-- 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 ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Services;
with AWA.Services.Contexts;
package body AWA.Wikis.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Space_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki space.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
if Bean.Is_Inserted then
Bean.Service.Save_Wiki_Space (Bean);
else
Bean.Service.Create_Wiki_Space (Bean);
end if;
end Save;
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Space_Bean_Access := new Wiki_Space_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Wiki_Space_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "wikiId" then
if From.Wiki_Space.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return ADO.Utils.To_Object (From.Wiki_Space.Get_Id);
end if;
elsif Name = "text" then
if From.Content.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (String '(From.Content.Get_Content));
end if;
elsif Name = "comment" then
if From.Content.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (String '(From.Content.Get_Save_Comment));
end if;
elsif Name = "tags" then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Page_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "id" then
declare
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Service.Load_Page (From, From.Content, From.Tags, Id);
end;
elsif Name = "wikiId" then
From.Wiki_Space.Set_Id (ADO.Utils.To_Identifier (Value));
elsif Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
elsif Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "is_public" then
From.Set_Is_Public (Util.Beans.Objects.To_Boolean (Value));
elsif Name = "text" then
From.Has_Content := True;
From.Content.Set_Content (Util.Beans.Objects.To_String (Value));
elsif Name = "comment" then
From.Content.Set_Save_Comment (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki page.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
if Bean.Is_Inserted then
Bean.Service.Save (Bean);
else
Bean.Service.Create_Wiki_Page (Bean.Wiki_Space, Bean);
end if;
if Bean.Has_Content then
Bean.Service.Create_Wiki_Content (Bean, Bean.Content);
end if;
end Save;
-- ------------------------------
-- Load the wiki page.
-- ------------------------------
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Service.Load_Page (Bean, Bean.Content, Bean.Tags,
Bean.Wiki_Space.Get_Id, Bean.Get_Name);
exception
when ADO.Objects.NOT_FOUND =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Page_Bean_Access := new Wiki_Page_Bean;
begin
Object.Service := Module;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Wikis.Models.WIKI_PAGE_TABLE);
return Object.all'Access;
end Create_Wiki_Page_Bean;
-- ------------------------------
-- Load the list of wikis.
-- ------------------------------
procedure Load_Wikis (List : in Wiki_Admin_Bean) is
use AWA.Wikis.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Wikis.Models.Query_Wiki_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "table",
Table => AWA.Wikis.Models.WIKI_SPACE_TABLE,
Session => Session);
AWA.Wikis.Models.List (List.Wiki_List_Bean.all, Session, Query);
List.Flags (INIT_WIKI_LIST) := True;
end Load_Wikis;
-- ------------------------------
-- Get the wiki space identifier.
-- ------------------------------
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier is
use type ADO.Identifier;
begin
if List.Wiki_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_WIKI_LIST) then
Load_Wikis (List);
end if;
if not List.Wiki_List.List.Is_Empty then
return List.Wiki_List.List.Element (0).Id;
end if;
end if;
return List.Wiki_Id;
end Get_Wiki_Id;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "wikis" then
if not List.Init_Flags (INIT_WIKI_LIST) then
Load_Wikis (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Wiki_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
use type ADO.Identifier;
Id : constant ADO.Identifier := List.Get_Wiki_Id;
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end;
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 Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Wiki_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
-- ------------------------------
-- 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 is
Object : constant Wiki_Admin_Bean_Access := new Wiki_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Wiki_List_Bean := Object.Wiki_List'Access;
return Object.all'Access;
end Create_Wiki_Admin_Bean;
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 ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Datasets;
with ADO.Sessions.Entities;
with AWA.Services;
with AWA.Services.Contexts;
with AWA.Tags.Modules;
package body AWA.Wikis.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Space_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki space.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
if Bean.Is_Inserted then
Bean.Service.Save_Wiki_Space (Bean);
else
Bean.Service.Create_Wiki_Space (Bean);
end if;
end Save;
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Space_Bean_Access := new Wiki_Space_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Wiki_Space_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "wikiId" then
if From.Wiki_Space.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return ADO.Utils.To_Object (From.Wiki_Space.Get_Id);
end if;
elsif Name = "text" then
if From.Content.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (String '(From.Content.Get_Content));
end if;
elsif Name = "comment" then
if From.Content.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (String '(From.Content.Get_Save_Comment));
end if;
elsif Name = "tags" then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Page_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "id" then
declare
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Service.Load_Page (From, From.Content, From.Tags, Id);
end;
elsif Name = "wikiId" then
From.Wiki_Space.Set_Id (ADO.Utils.To_Identifier (Value));
elsif Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
elsif Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "is_public" then
From.Set_Is_Public (Util.Beans.Objects.To_Boolean (Value));
elsif Name = "text" then
From.Has_Content := True;
From.Content.Set_Content (Util.Beans.Objects.To_String (Value));
elsif Name = "comment" then
From.Content.Set_Save_Comment (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki page.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
if Bean.Is_Inserted then
Bean.Service.Save (Bean);
else
Bean.Service.Create_Wiki_Page (Bean.Wiki_Space, Bean);
end if;
if Bean.Has_Content then
Bean.Service.Create_Wiki_Content (Bean, Bean.Content);
end if;
end Save;
-- ------------------------------
-- Load the wiki page.
-- ------------------------------
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Service.Load_Page (Bean, Bean.Content, Bean.Tags,
Bean.Wiki_Space.Get_Id, Bean.Get_Name);
exception
when ADO.Objects.NOT_FOUND =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Page_Bean_Access := new Wiki_Page_Bean;
begin
Object.Service := Module;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Wikis.Models.WIKI_PAGE_TABLE);
return Object.all'Access;
end Create_Wiki_Page_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
Pos : Natural;
begin
if Name = "tags" then
Pos := From.Pages.Get_Row_Index;
if Pos = 0 then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Models.Wiki_Page_Info := From.Pages.List.Element (Pos - 1);
begin
return From.Tags.Get_Tags (Item.Id);
end;
elsif Name = "pages" then
return Util.Beans.Objects.To_Object (Value => From.Pages_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "tag" then
return Util.Beans.Objects.To_Object (From.Tag);
elsif Name = "page" then
return Util.Beans.Objects.To_Object (From.Page);
elsif Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
elsif Name = "page_count" then
return Util.Beans.Objects.To_Object ((From.Count + From.Page_Size - 1) / From.Page_Size);
elsif Name = "wiki_id" then
return ADO.Utils.To_Object (From.Wiki_Id);
elsif Name = "updateDate" then
if From.Pages.Get_Count = 0 then
return Util.Beans.Objects.Null_Object;
else
declare
Item : constant Models.Wiki_Page_Info := From.Pages.List.Element (0);
begin
return Util.Beans.Objects.Time.To_Object (Item.Create_Date);
end;
end if;
else
return From.Pages.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "tag" then
From.Tag := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "page" and not Util.Beans.Objects.Is_Empty (Value) then
From.Page := Util.Beans.Objects.To_Integer (Value);
elsif Name = "wiki_id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Wiki_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
From.Load_List;
end Load;
-- ------------------------------
-- 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) is
use AWA.Wikis.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Service.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
Tag_Id : ADO.Identifier;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
if Into.Wiki_Id = ADO.NO_IDENTIFIER then
return;
end if;
AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id);
if Tag_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Wikis.Models.Query_Wiki_Page_List);
Query.Bind_Param (Name => "tag", Value => Tag_Id);
Count_Query.Set_Count_Query (AWA.Wikis.Models.Query_Wiki_Page_List);
Count_Query.Bind_Param (Name => "tag", Value => Tag_Id);
else
Query.Set_Query (AWA.Wikis.Models.Query_Wiki_Page_List);
Count_Query.Set_Count_Query (AWA.Wikis.Models.Query_Wiki_Page_List);
end if;
Query.Bind_Param (Name => "first", Value => First);
Query.Bind_Param (Name => "count", Value => Into.Page_Size);
Query.Bind_Param (Name => "wiki_id", Value => Into.Wiki_Id);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "wiki_id", Value => Into.Wiki_Id);
Count_Query.Bind_Param (Name => "user_id", Value => User);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "table",
Table => AWA.Wikis.Models.WIKI_SPACE_TABLE,
Session => Session);
ADO.Sessions.Entities.Bind_Param (Params => Count_Query,
Name => "table",
Table => AWA.Wikis.Models.WIKI_SPACE_TABLE,
Session => Session);
AWA.Wikis.Models.List (Into.Pages, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
declare
List : ADO.Utils.Identifier_Vector;
Iter : Wiki_Page_Info_Vectors.Cursor := Into.Pages.List.First;
begin
while Wiki_Page_Info_Vectors.Has_Element (Iter) loop
List.Append (Wiki_Page_Info_Vectors.Element (Iter).Id);
Wiki_Page_Info_Vectors.Next (Iter);
end loop;
Into.Tags.Load_Tags (Session, AWA.Wikis.Models.WIKI_PAGE_TABLE.Table.all,
List);
end;
end Load_List;
-- ------------------------------
-- Create the Wiki_List_Bean bean instance.
-- ------------------------------
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Wiki_List_Bean_Access := new Wiki_List_Bean;
begin
Object.Service := Module;
Object.Pages_Bean := Object.Pages'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
Object.Wiki_Id := ADO.NO_IDENTIFIER;
return Object.all'Access;
end Create_Wiki_List_Bean;
-- ------------------------------
-- Load the list of wikis.
-- ------------------------------
procedure Load_Wikis (List : in Wiki_Admin_Bean) is
use AWA.Wikis.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Wikis.Models.Query_Wiki_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "table",
Table => AWA.Wikis.Models.WIKI_SPACE_TABLE,
Session => Session);
AWA.Wikis.Models.List (List.Wiki_List_Bean.all, Session, Query);
List.Flags (INIT_WIKI_LIST) := True;
end Load_Wikis;
-- ------------------------------
-- Get the wiki space identifier.
-- ------------------------------
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier is
use type ADO.Identifier;
begin
if List.Wiki_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_WIKI_LIST) then
Load_Wikis (List);
end if;
if not List.Wiki_List.List.Is_Empty then
return List.Wiki_List.List.Element (0).Id;
end if;
end if;
return List.Wiki_Id;
end Get_Wiki_Id;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "wikis" then
if not List.Init_Flags (INIT_WIKI_LIST) then
Load_Wikis (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Wiki_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
use type ADO.Identifier;
Id : constant ADO.Identifier := List.Get_Wiki_Id;
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end;
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 Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Wiki_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
-- ------------------------------
-- 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 is
Object : constant Wiki_Admin_Bean_Access := new Wiki_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Wiki_List_Bean := Object.Wiki_List'Access;
return Object.all'Access;
end Create_Wiki_Admin_Bean;
end AWA.Wikis.Beans;
|
Implement the Wiki_List_Bean operations
|
Implement the Wiki_List_Bean operations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a4447dc2bc3e1849840e21eab199b5061b9c06e1
|
src/util-events-timers.adb
|
src/util-events-timers.adb
|
-----------------------------------------------------------------------
-- util-events-timers -- Timer list management
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Events.Timers is
use type Ada.Real_Time.Time;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Timer_Node,
Name => Timer_Node_Access);
-- -----------------------
-- Repeat the timer.
-- -----------------------
procedure Repeat (Event : in out Timer_Ref;
In_Time : in Ada.Real_Time.Time_Span) is
Timer : constant Timer_Node_Access := Event.Value;
begin
if Timer /= null and then Timer.List /= null then
Timer.List.Add (Timer, Timer.Deadline + In_Time);
end if;
end Repeat;
-- -----------------------
-- Cancel the timer.
-- -----------------------
procedure Cancel (Event : in out Timer_Ref) is
begin
if Event.Value /= null and then Event.Value.List /= null then
Event.Value.List.all.Cancel (Event.Value);
Event.Value.List := null;
end if;
end Cancel;
-- -----------------------
-- Check if the timer is ready to be executed.
-- -----------------------
function Is_Scheduled (Event : in Timer_Ref) return Boolean is
begin
return Event.Value /= null and then Event.Value.List /= null;
end Is_Scheduled;
-- -----------------------
-- Returns the deadline time for the timer execution.
-- Returns Time'Last if the timer is not scheduled.
-- -----------------------
function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is
begin
return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last);
end Time_Of_Event;
-- -----------------------
-- Set a timer to be called at the given time.
-- -----------------------
procedure Set_Timer (List : in out Timer_List;
Handler : in Timer_Access;
Event : in out Timer_Ref'Class;
At_Time : in Ada.Real_Time.Time) is
Timer : Timer_Node_Access := Event.Value;
begin
if Timer = null then
Event.Value := new Timer_Node;
Timer := Event.Value;
end if;
Timer.Handler := Handler;
-- Cancel the timer if it is part of another timer manager.
if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then
Timer.List.Cancel (Timer);
end if;
-- Update the timer.
Timer.List := List.Manager'Unchecked_Access;
List.Manager.Add (Timer, At_Time);
end Set_Timer;
-- -----------------------
-- Set a timer to be called after the given time span.
-- -----------------------
procedure Set_Timer (List : in out Timer_List;
Handler : in Timer_Access;
Event : in out Timer_Ref'Class;
In_Time : in Ada.Real_Time.Time_Span) is
begin
List.Set_Timer (Handler, Event, Ada.Real_Time.Clock + In_Time);
end Set_Timer;
-- -----------------------
-- Process the timer handlers that have passed the deadline and return the next
-- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers
-- that are called by operation. The default is not limited.
-- -----------------------
procedure Process (List : in out Timer_List;
Timeout : out Ada.Real_Time.Time;
Max_Count : in Natural := Natural'Last) is
Timer : Timer_Ref;
Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
begin
loop
List.Manager.Find_Next (Now, Timeout, Timer);
exit when Timer.Value = null;
Timer.Value.Handler.Time_Handler (Timer);
Timer.Finalize;
end loop;
end Process;
overriding
procedure Adjust (Object : in out Timer_Ref) is
begin
if Object.Value /= null then
Util.Concurrent.Counters.Increment (Object.Value.Counter);
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Timer_Ref) is
Is_Zero : Boolean;
begin
if Object.Value /= null then
Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero);
if Is_Zero then
Free (Object.Value);
else
Object.Value := null;
end if;
end if;
end Finalize;
protected body Timer_Manager is
procedure Remove (Timer : in Timer_Node_Access) is
begin
if List = Timer then
List := Timer.Next;
Timer.Prev := null;
if List /= null then
List.Prev := null;
end if;
elsif Timer.Prev /= null then
Timer.Prev.Next := Timer.Next;
Timer.Next.Prev := Timer.Prev;
else
return;
end if;
Timer.Next := null;
Timer.Prev := null;
Timer.List := null;
end Remove;
-- -----------------------
-- Add a timer.
-- -----------------------
procedure Add (Timer : in Timer_Node_Access;
Deadline : in Ada.Real_Time.Time) is
Current : Timer_Node_Access := List;
Prev : Timer_Node_Access;
begin
Util.Concurrent.Counters.Increment (Timer.Counter);
if Timer.List /= null then
Remove (Timer);
end if;
Timer.Deadline := Deadline;
while Current /= null loop
if Current.Deadline > Deadline then
if Prev = null then
List := Timer;
else
Prev.Next := Timer;
end if;
Timer.Next := Current;
Current.Prev := Timer;
return;
end if;
Prev := Current;
Current := Current.Next;
end loop;
if Prev = null then
List := Timer;
Timer.Prev := null;
else
Prev.Next := Timer;
Timer.Prev := Prev;
end if;
Timer.Next := null;
end Add;
-- -----------------------
-- Cancel a timer.
-- -----------------------
procedure Cancel (Timer : in out Timer_Node_Access) is
Is_Zero : Boolean;
begin
if Timer.List = null then
return;
end if;
Remove (Timer);
Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero);
if Is_Zero then
Free (Timer);
end if;
end Cancel;
-- -----------------------
-- Find the next timer to be executed before the given time or return the next deadline.
-- -----------------------
procedure Find_Next (Before : in Ada.Real_Time.Time;
Deadline : out Ada.Real_Time.Time;
Timer : in out Timer_Ref) is
begin
if List = null then
Deadline := Ada.Real_Time.Time_Last;
elsif List.Deadline < Before then
Timer.Value := List;
List := List.Next;
if List /= null then
List.Prev := null;
Deadline := List.Deadline;
else
Deadline := Ada.Real_Time.Time_Last;
end if;
else
Deadline := List.Deadline;
end if;
end Find_Next;
end Timer_Manager;
overriding
procedure Finalize (Object : in out Timer_List) is
Timer : Timer_Ref;
Timeout : Ada.Real_Time.Time;
begin
loop
Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer);
exit when Timer.Value = null;
Timer.Finalize;
end loop;
end Finalize;
end Util.Events.Timers;
|
-----------------------------------------------------------------------
-- util-events-timers -- Timer list management
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
package body Util.Events.Timers is
use type Ada.Real_Time.Time;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Events.Timers");
procedure Free is
new Ada.Unchecked_Deallocation (Object => Timer_Node,
Name => Timer_Node_Access);
-- -----------------------
-- Repeat the timer.
-- -----------------------
procedure Repeat (Event : in out Timer_Ref;
In_Time : in Ada.Real_Time.Time_Span) is
Timer : constant Timer_Node_Access := Event.Value;
begin
if Timer /= null and then Timer.List /= null then
Timer.List.Add (Timer, Timer.Deadline + In_Time);
end if;
end Repeat;
-- -----------------------
-- Cancel the timer.
-- -----------------------
procedure Cancel (Event : in out Timer_Ref) is
begin
if Event.Value /= null and then Event.Value.List /= null then
Event.Value.List.all.Cancel (Event.Value);
Event.Value.List := null;
end if;
end Cancel;
-- -----------------------
-- Check if the timer is ready to be executed.
-- -----------------------
function Is_Scheduled (Event : in Timer_Ref) return Boolean is
begin
return Event.Value /= null and then Event.Value.List /= null;
end Is_Scheduled;
-- -----------------------
-- Returns the deadline time for the timer execution.
-- Returns Time'Last if the timer is not scheduled.
-- -----------------------
function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is
begin
return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last);
end Time_Of_Event;
-- -----------------------
-- Set a timer to be called at the given time.
-- -----------------------
procedure Set_Timer (List : in out Timer_List;
Handler : in Timer_Access;
Event : in out Timer_Ref'Class;
At_Time : in Ada.Real_Time.Time) is
Timer : Timer_Node_Access := Event.Value;
begin
if Timer = null then
Event.Value := new Timer_Node;
Timer := Event.Value;
end if;
Timer.Handler := Handler;
-- Cancel the timer if it is part of another timer manager.
if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then
Timer.List.Cancel (Timer);
end if;
-- Update the timer.
Timer.List := List.Manager'Unchecked_Access;
List.Manager.Add (Timer, At_Time);
end Set_Timer;
-- -----------------------
-- Set a timer to be called after the given time span.
-- -----------------------
procedure Set_Timer (List : in out Timer_List;
Handler : in Timer_Access;
Event : in out Timer_Ref'Class;
In_Time : in Ada.Real_Time.Time_Span) is
begin
List.Set_Timer (Handler, Event, Ada.Real_Time.Clock + In_Time);
end Set_Timer;
-- -----------------------
-- Process the timer handlers that have passed the deadline and return the next
-- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers
-- that are called by operation. The default is not limited.
-- -----------------------
procedure Process (List : in out Timer_List;
Timeout : out Ada.Real_Time.Time;
Max_Count : in Natural := Natural'Last) is
Timer : Timer_Ref;
Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Count : Natural := 0;
begin
for Count in 1 .. Max_Count loop
List.Manager.Find_Next (Now, Timeout, Timer);
exit when Timer.Value = null;
begin
Timer.Value.Handler.Time_Handler (Timer);
exception
when E : others =>
Timer_List'Class (List).Error (Timer.Value.Handler, E);
end;
Timer.Finalize;
end loop;
end Process;
-- -----------------------
-- Procedure called when a timer handler raises an exception.
-- The default operation reports an error in the logs. This procedure can be
-- overriden to implement specific error handling.
-- -----------------------
procedure Error (List : in out Timer_List;
Handler : in Timer_Access;
E : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (List, Handler);
begin
Log.Error ("Timer handler raised an exception", E, True);
end Error;
overriding
procedure Adjust (Object : in out Timer_Ref) is
begin
if Object.Value /= null then
Util.Concurrent.Counters.Increment (Object.Value.Counter);
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Timer_Ref) is
Is_Zero : Boolean;
begin
if Object.Value /= null then
Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero);
if Is_Zero then
Free (Object.Value);
else
Object.Value := null;
end if;
end if;
end Finalize;
protected body Timer_Manager is
procedure Remove (Timer : in Timer_Node_Access) is
begin
if List = Timer then
List := Timer.Next;
Timer.Prev := null;
if List /= null then
List.Prev := null;
end if;
elsif Timer.Prev /= null then
Timer.Prev.Next := Timer.Next;
Timer.Next.Prev := Timer.Prev;
else
return;
end if;
Timer.Next := null;
Timer.Prev := null;
Timer.List := null;
end Remove;
-- -----------------------
-- Add a timer.
-- -----------------------
procedure Add (Timer : in Timer_Node_Access;
Deadline : in Ada.Real_Time.Time) is
Current : Timer_Node_Access := List;
Prev : Timer_Node_Access;
begin
Util.Concurrent.Counters.Increment (Timer.Counter);
if Timer.List /= null then
Remove (Timer);
end if;
Timer.Deadline := Deadline;
while Current /= null loop
if Current.Deadline > Deadline then
if Prev = null then
List := Timer;
else
Prev.Next := Timer;
end if;
Timer.Next := Current;
Current.Prev := Timer;
return;
end if;
Prev := Current;
Current := Current.Next;
end loop;
if Prev = null then
List := Timer;
Timer.Prev := null;
else
Prev.Next := Timer;
Timer.Prev := Prev;
end if;
Timer.Next := null;
end Add;
-- -----------------------
-- Cancel a timer.
-- -----------------------
procedure Cancel (Timer : in out Timer_Node_Access) is
Is_Zero : Boolean;
begin
if Timer.List = null then
return;
end if;
Remove (Timer);
Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero);
if Is_Zero then
Free (Timer);
end if;
end Cancel;
-- -----------------------
-- Find the next timer to be executed before the given time or return the next deadline.
-- -----------------------
procedure Find_Next (Before : in Ada.Real_Time.Time;
Deadline : out Ada.Real_Time.Time;
Timer : in out Timer_Ref) is
begin
if List = null then
Deadline := Ada.Real_Time.Time_Last;
elsif List.Deadline < Before then
Timer.Value := List;
List := List.Next;
if List /= null then
List.Prev := null;
Deadline := List.Deadline;
else
Deadline := Ada.Real_Time.Time_Last;
end if;
else
Deadline := List.Deadline;
end if;
end Find_Next;
end Timer_Manager;
overriding
procedure Finalize (Object : in out Timer_List) is
Timer : Timer_Ref;
Timeout : Ada.Real_Time.Time;
begin
loop
Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer);
exit when Timer.Value = null;
Timer.Finalize;
end loop;
end Finalize;
end Util.Events.Timers;
|
Implement Error procedure and report an error message Catch exception raised by a timer handler and call the dispatching operation Error to report the problem Take into account the Max_Count parameter for the Process procedure to execute at most Max_Count timer handlers
|
Implement Error procedure and report an error message
Catch exception raised by a timer handler and call the dispatching operation Error to report the problem
Take into account the Max_Count parameter for the Process procedure to execute at most Max_Count timer handlers
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
eca2c1be16d57a7a94f8f2bd0e93e602355123b7
|
awa/regtests/awa-commands-tests.ads
|
awa/regtests/awa-commands-tests.ads
|
-----------------------------------------------------------------------
-- awa-commands-tests -- Test the AWA.Commands
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Ada.Strings.Unbounded;
package AWA.Commands.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test start and stop command.
procedure Test_Start_Stop (T : in out Test);
procedure Test_List_Tables (T : in out Test);
-- Test the list -u command.
procedure Test_List_Users (T : in out Test);
-- Test the list -s command.
procedure Test_List_Sessions (T : in out Test);
-- Test the list -j command.
procedure Test_List_Jobs (T : in out Test);
procedure Execute (T : in out Test;
Command : in String;
Input : in String;
Output : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String;
Status : in Natural := 0);
end AWA.Commands.Tests;
|
-----------------------------------------------------------------------
-- awa-commands-tests -- Test the AWA.Commands
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Ada.Strings.Unbounded;
package AWA.Commands.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test start and stop command.
procedure Test_Start_Stop (T : in out Test);
procedure Test_List_Tables (T : in out Test);
-- Test the list -u command.
procedure Test_List_Users (T : in out Test);
-- Test the list -s command.
procedure Test_List_Sessions (T : in out Test);
-- Test the list -j command.
procedure Test_List_Jobs (T : in out Test);
-- Test the command with a secure keystore configuration.
procedure Test_Secure_Configuration (T : in out Test);
procedure Execute (T : in out Test;
Command : in String;
Input : in String;
Output : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String;
Status : in Natural := 0);
end AWA.Commands.Tests;
|
Declare Test_Secure_Configuration procedure to check using secure configuration
|
Declare Test_Secure_Configuration procedure to check using secure configuration
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
02b498caffaeba6632e8fcbd19a7492cc2c3e43d
|
src/asf-routes-servlets.adb
|
src/asf-routes-servlets.adb
|
-----------------------------------------------------------------------
-- asf-routes -- Request routing
-- 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.Unchecked_Deallocation;
package body ASF.Routes.Servlets is
use type ASF.Filters.Filter_Access;
use type ASF.Filters.Filter_List_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Filters.Filter_List,
Name => ASF.Filters.Filter_List_Access);
-- ------------------------------
-- Get the servlet to call for the route.
-- ------------------------------
function Get_Servlet (Route : in Servlet_Route_Type) return ASF.Servlets.Servlet_Access is
begin
return Route.Servlet;
end Get_Servlet;
-- ------------------------------
-- Append the filter to the filter list defined by the mapping node.
-- ------------------------------
procedure Append_Filter (Route : in out Servlet_Route_Type;
Filter : in ASF.Filters.Filter_Access) is
List : ASF.Filters.Filter_List_Access;
begin
-- Filters are executed through the <b>Filter_Chain.Do_Filter</b> method
-- starting from the last position to the first. To append a filter,
-- it must be inserted as first position of the list.
if Route.Filters = null then
List := new ASF.Filters.Filter_List (1 .. 1);
else
-- Check that the filter is not already executed.
for I in Route.Filters'Range loop
if Route.Filters (I) = Filter then
return;
end if;
end loop;
List := new ASF.Filters.Filter_List (1 .. Route.Filters'Last + 1);
List (2 .. List'Last) := Route.Filters.all;
Free (Route.Filters);
end if;
List (List'First) := Filter;
Route.Filters := List;
end Append_Filter;
-- ------------------------------
-- Release the storage held by the route.
-- ------------------------------
overriding
procedure Finalize (Route : in out Servlet_Route_Type) is
begin
Free (Route.Filters);
end Finalize;
end ASF.Routes.Servlets;
|
-----------------------------------------------------------------------
-- asf-routes -- Request routing
-- 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.Unchecked_Deallocation;
package body ASF.Routes.Servlets is
use type ASF.Filters.Filter_Access;
use type ASF.Filters.Filter_List_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Filters.Filter_List,
Name => ASF.Filters.Filter_List_Access);
-- ------------------------------
-- Get the servlet to call for the route.
-- ------------------------------
function Get_Servlet (Route : in Servlet_Route_Type) return ASF.Servlets.Servlet_Access is
begin
return Route.Servlet;
end Get_Servlet;
-- ------------------------------
-- Append the filter to the filter list defined by the mapping node.
-- ------------------------------
procedure Append_Filter (Route : in out Servlet_Route_Type;
Filter : in ASF.Filters.Filter_Access) is
List : ASF.Filters.Filter_List_Access;
begin
-- Filters are executed through the <b>Filter_Chain.Do_Filter</b> method
-- starting from the last position to the first. To append a filter,
-- it must be inserted as first position of the list.
if Route.Filters = null then
List := new ASF.Filters.Filter_List (1 .. 1);
else
-- Check that the filter is not already executed.
for I in Route.Filters'Range loop
if Route.Filters (I) = Filter then
return;
end if;
end loop;
List := new ASF.Filters.Filter_List (1 .. Route.Filters'Last + 1);
List (2 .. List'Last) := Route.Filters.all;
Free (Route.Filters);
end if;
List (List'First) := Filter;
Route.Filters := List;
end Append_Filter;
-- ------------------------------
-- Release the storage held by the route.
-- ------------------------------
overriding
procedure Finalize (Route : in out Servlet_Route_Type) is
begin
Free (Route.Filters);
end Finalize;
-- ------------------------------
-- Get the servlet to call for the route.
-- ------------------------------
overriding
function Get_Servlet (Route : in Proxy_Route_Type) return ASF.Servlets.Servlet_Access is
begin
if Route.Route /= null then
return Route.Route.Get_Servlet;
else
return Route.Servlet;
end if;
end Get_Servlet;
end ASF.Routes.Servlets;
|
Implement the Get_Servlet function for Proxy_Route_Type
|
Implement the Get_Servlet function for Proxy_Route_Type
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
37c5ed454b5985f3eb4e0a0e6bafa32c878406c3
|
src/util-streams-texts.adb
|
src/util-streams-texts.adb
|
-----------------------------------------------------------------------
-- Util.Streams.Files -- File Stream utilities
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
package body Util.Streams.Texts is
procedure Initialize (Stream : in out Print_Stream;
To : in Output_Stream_Access) is
begin
Stream.Initialize (Output => To, Input => null, Size => 4096);
end Initialize;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Integer) is
S : constant String := Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer) is
S : constant String := Long_Long_Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write a string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Stream.Write (Ada.Strings.Unbounded.To_String (Item));
end Write;
-- ------------------------------
-- Write a date on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date) is
begin
Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format));
end Write;
-- ------------------------------
-- Get the output stream content as a string.
-- ------------------------------
function To_String (Stream : in Buffered.Buffered_Stream) return String is
use Ada.Streams;
Size : constant Natural := Stream.Get_Size;
Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer;
Result : String (1 .. Size);
begin
for I in Result'Range loop
Result (I) := Character'Val (Buffer (Stream_Element_Offset (I)));
end loop;
return Result;
end To_String;
-- ------------------------------
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
-- ------------------------------
procedure Initialize (Stream : in out Reader_Stream;
From : in Input_Stream_Access) is
begin
Stream.Initialize (Output => null, Input => From, Size => 4096);
end Initialize;
-- ------------------------------
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
-- ------------------------------
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False) is
C : Character;
begin
while not Stream.Is_Eof loop
Stream.Read (C);
if C = ASCII.LF then
if not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
return;
elsif C /= ASCII.CR or not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
return;
end Read_Line;
end Util.Streams.Texts;
|
-----------------------------------------------------------------------
-- Util.Streams.Files -- File Stream utilities
-- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
package body Util.Streams.Texts is
procedure Initialize (Stream : in out Print_Stream;
To : in Output_Stream_Access) is
begin
Stream.Initialize (Output => To, Input => null, Size => 4096);
end Initialize;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Integer) is
S : constant String := Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer) is
S : constant String := Long_Long_Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write a string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Stream.Write (Ada.Strings.Unbounded.To_String (Item));
end Write;
-- ------------------------------
-- Write a date on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date) is
begin
Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format));
end Write;
-- ------------------------------
-- Get the output stream content as a string.
-- ------------------------------
function To_String (Stream : in Buffered.Buffered_Stream) return String is
use Ada.Streams;
Size : constant Natural := Stream.Get_Size;
Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer;
Result : String (1 .. Size);
begin
for I in Result'Range loop
Result (I) := Character'Val (Buffer (Stream_Element_Offset (I)));
end loop;
return Result;
end To_String;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class;
Item : in Character) is
begin
Stream.Write (Item);
end Write_Char;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class;
Item : in Wide_Wide_Character) is
begin
Stream.Write_Wide (Item);
end Write_Char;
-- ------------------------------
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
-- ------------------------------
procedure Initialize (Stream : in out Reader_Stream;
From : in Input_Stream_Access) is
begin
Stream.Initialize (Output => null, Input => From, Size => 4096);
end Initialize;
-- ------------------------------
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
-- ------------------------------
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False) is
C : Character;
begin
while not Stream.Is_Eof loop
Stream.Read (C);
if C = ASCII.LF then
if not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
return;
elsif C /= ASCII.CR or not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
return;
end Read_Line;
end Util.Streams.Texts;
|
Implement the Wide_Char procedures for the TR and WTR packages
|
Implement the Wide_Char procedures for the TR and WTR packages
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
3e2f539e9c2c6108cc53da423702a36c36a01940
|
regtests/el-beans-tests.adb
|
regtests/el-beans-tests.adb
|
-----------------------------------------------------------------------
-- EL.Beans.Tests - Testsuite for EL.Beans
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Test_Bean;
with Util.Beans.Objects;
with EL.Contexts.Default;
package body EL.Beans.Tests is
use Util.Tests;
use Util.Beans.Objects;
use Test_Bean;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test EL.Beans.Add_Parameter",
Test_Add_Parameter'Access);
Caller.Add_Test (Suite, "Test EL.Beans.Initialize",
Test_Initialize'Access);
end Add_Tests;
-- ------------------------------
-- Test Add_Parameter
-- ------------------------------
procedure Test_Add_Parameter (T : in out Test) is
P : Param_Vectors.Vector;
Context : EL.Contexts.Default.Default_Context;
begin
-- Add a constant parameter.
Add_Parameter (Container => P,
Name => "firstName",
Value => "my name",
Context => Context);
Assert_Equals (T, 1, Integer (P.Length), "Parameter was not added");
T.Assert_Equals ("firstName", P.Element (1).Name, "Invalid parameter name");
T.Assert (P.Element (1).Value.Is_Constant, "Value should be a constant");
T.Assert_Equals ("my name",
Util.Beans.Objects.To_String (P.Element (1).Value.Get_Value (Context)),
"Invalid value");
-- Add an expression parameter.
Add_Parameter (Container => P,
Name => "lastName",
Value => "#{name}",
Context => Context);
Assert_Equals (T, 2, Integer (P.Length), "Parameter was not added");
end Test_Add_Parameter;
-- ------------------------------
-- Test the Initialize procedure with a set of expressions
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
P : Param_Vectors.Vector;
Context : EL.Contexts.Default.Default_Context;
User : Person_Access := Create_Person ("Joe", "Black", 42);
Bean : Person_Access := Create_Person ("", "", 0);
begin
Context.Set_Variable ("user", User);
Add_Parameter (P, "firstName", "#{user.firstName}", Context);
Add_Parameter (P, "lastName", "#{user.lastName}", Context);
Add_Parameter (P, "age", "#{user.age + 2}", Context);
Initialize (Bean.all, P, Context);
T.Assert_Equals ("Joe", Bean.First_Name, "First name not initialized");
T.Assert_Equals ("Black", Bean.Last_Name, "Last name not initialized");
Assert_Equals (T, 44, Integer (Bean.Age), "Age was not initialized");
Free (Bean);
Free (User);
end Test_Initialize;
end EL.Beans.Tests;
|
-----------------------------------------------------------------------
-- EL.Beans.Tests - Testsuite for EL.Beans
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Test_Bean;
with Util.Beans.Objects;
with EL.Contexts.Default;
package body EL.Beans.Tests is
use Util.Tests;
use Util.Beans.Objects;
use Test_Bean;
package Caller is new Util.Test_Caller (Test, "EL.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test EL.Beans.Add_Parameter",
Test_Add_Parameter'Access);
Caller.Add_Test (Suite, "Test EL.Beans.Initialize",
Test_Initialize'Access);
end Add_Tests;
-- ------------------------------
-- Test Add_Parameter
-- ------------------------------
procedure Test_Add_Parameter (T : in out Test) is
P : Param_Vectors.Vector;
Context : EL.Contexts.Default.Default_Context;
begin
-- Add a constant parameter.
Add_Parameter (Container => P,
Name => "firstName",
Value => "my name",
Context => Context);
Assert_Equals (T, 1, Integer (P.Length), "Parameter was not added");
T.Assert_Equals ("firstName", P.Element (1).Name, "Invalid parameter name");
T.Assert (P.Element (1).Value.Is_Constant, "Value should be a constant");
T.Assert_Equals ("my name",
Util.Beans.Objects.To_String (P.Element (1).Value.Get_Value (Context)),
"Invalid value");
-- Add an expression parameter.
Add_Parameter (Container => P,
Name => "lastName",
Value => "#{name}",
Context => Context);
Assert_Equals (T, 2, Integer (P.Length), "Parameter was not added");
end Test_Add_Parameter;
-- ------------------------------
-- Test the Initialize procedure with a set of expressions
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
P : Param_Vectors.Vector;
Context : EL.Contexts.Default.Default_Context;
User : Person_Access := Create_Person ("Joe", "Black", 42);
Bean : Person_Access := Create_Person ("", "", 0);
begin
Context.Set_Variable ("user", User);
Add_Parameter (P, "firstName", "#{user.firstName}", Context);
Add_Parameter (P, "lastName", "#{user.lastName}", Context);
Add_Parameter (P, "age", "#{user.age + 2}", Context);
Initialize (Bean.all, P, Context);
T.Assert_Equals ("Joe", Bean.First_Name, "First name not initialized");
T.Assert_Equals ("Black", Bean.Last_Name, "Last name not initialized");
Assert_Equals (T, 44, Integer (Bean.Age), "Age was not initialized");
Free (Bean);
Free (User);
end Test_Initialize;
end EL.Beans.Tests;
|
Use the test name EL.Beans
|
Use the test name EL.Beans
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
aab219e237d25475e2273949daa205650d7736a1
|
src/gl/implementation/gl-low_level-enums.ads
|
src/gl/implementation/gl-low_level-enums.ads
|
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT 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 GL.Low_Level.Enums is
pragma Preelaborate;
-- Unlike GL.Enums, this package is not private and hosts enum types that may
-- be needed by third-party code or wrappers.
type Texture_Kind is (Texture_1D, Texture_2D, Texture_3D,
Texture_Rectangle, Texture_Cube_Map,
Texture_1D_Array, Texture_2D_Array,
Texture_Buffer, Texture_Cube_Map_Array,
Texture_2D_Multisample, Texture_2D_Multisample_Array);
type Renderbuffer_Kind is (Renderbuffer);
type Framebuffer_Kind is (Read, Draw);
type Transform_Feedback_Kind is (Transform_Feedback);
type Buffer_Kind is (Array_Buffer, Element_Array_Buffer, Pixel_Pack_Buffer,
Pixel_Unpack_Buffer, Uniform_Buffer, Texture_Buffer,
Transform_Feedback_Buffer, Copy_Read_Buffer,
Copy_Write_Buffer, Draw_Indirect_Buffer,
Shader_Storage_Buffer, Dispatch_Indirect_Buffer,
Query_Buffer, Atomic_Counter_Buffer);
type Draw_Buffer_Index is (DB0, DB1, DB2, DB3, DB4, DB5, DB6, DB7,
DB8, DB9, DB10, DB11, DB12, DB13, DB14, DB15);
type Only_Depth_Buffer is (Depth_Buffer);
type Only_Stencil_Buffer is (Stencil);
type Only_Depth_Stencil_Buffer is (Depth_Stencil);
type Only_Color_Buffer is (Color);
type Resource_Type is
(Int_Type,
UInt_Type,
Single_Type,
Double_Type,
Single_Vec2,
Single_Vec3,
Single_Vec4,
Int_Vec2,
Int_Vec3,
Int_Vec4,
Bool_Type,
Bool_Vec2,
Bool_Vec3,
Bool_Vec4,
Single_Matrix2,
Single_Matrix3,
Single_Matrix4,
Sampler_1D,
Sampler_2D,
Sampler_3D,
Sampler_Cube,
Sampler_1D_Shadow,
Sampler_2D_Shadow,
Sampler_2D_Rect,
Sampler_2D_Rect_Shadow,
Single_Matrix2x3,
Single_Matrix2x4,
Single_Matrix3x2,
Single_Matrix3x4,
Single_Matrix4x2,
Single_Matrix4x3,
Sampler_1D_Array,
Sampler_2D_Array,
Sampler_Buffer,
Sampler_1D_Array_Shadow,
Sampler_2D_Array_Shadow,
Sampler_Cube_Shadow,
UInt_Vec2,
UInt_Vec3,
UInt_Vec4,
Int_Sampler_1D,
Int_Sampler_2D,
Int_Sampler_3D,
Int_Sampler_Cube,
Int_Sampler_2D_Rect,
Int_Sampler_1D_Array,
Int_Sampler_2D_Array,
Int_Sampler_Buffer,
UInt_Sampler_1D,
UInt_Sampler_2D,
UInt_Sampler_3D,
UInt_Sampler_Cube,
UInt_Sampler_2D_Rect,
UInt_Sampler_1D_Array,
UInt_Sampler_2D_Array,
UInt_Sampler_Buffer,
Double_Matrix2,
Double_Matrix3,
Double_Matrix4,
Double_Matrix2x3,
Double_Matrix2x4,
Double_Matrix3x2,
Double_Matrix3x4,
Double_Matrix4x2,
Double_Matrix4x3,
Double_Vec2,
Double_Vec3,
Double_Vec4,
Sampler_2D_Multisample,
Int_Sampler_2D_Multisample,
UInt_Sampler_2D_Multisample,
Sampler_2D_Multisample_Array,
Int_Sampler_2D_Multisample_Array,
UInt_Sampler_2D_Multisample_Array);
private
for Texture_Kind use (Texture_1D => 16#0DE0#,
Texture_2D => 16#0DE1#,
Texture_3D => 16#806F#,
Texture_Rectangle => 16#84F5#,
Texture_Cube_Map => 16#8513#,
Texture_1D_Array => 16#8C18#,
Texture_2D_Array => 16#8C1A#,
Texture_Buffer => 16#8C2A#,
Texture_Cube_Map_Array => 16#9009#,
Texture_2D_Multisample => 16#9100#,
Texture_2D_Multisample_Array => 16#9102#);
for Texture_Kind'Size use Enum'Size;
for Renderbuffer_Kind use (Renderbuffer => 16#8D41#);
for Renderbuffer_Kind'Size use Enum'Size;
for Framebuffer_Kind use (Read => 16#8CA8#,
Draw => 16#8CA9#);
for Framebuffer_Kind'Size use Enum'Size;
for Transform_Feedback_Kind use (Transform_Feedback => 16#8E22#);
for Transform_Feedback_Kind'Size use Enum'Size;
for Buffer_Kind use (Array_Buffer => 16#8892#,
Element_Array_Buffer => 16#8893#,
Pixel_Pack_Buffer => 16#88EB#,
Pixel_Unpack_Buffer => 16#88EC#,
Uniform_Buffer => 16#8A11#,
Texture_Buffer => 16#8C2A#,
Transform_Feedback_Buffer => 16#8C8E#,
Copy_Read_Buffer => 16#8F36#,
Copy_Write_Buffer => 16#8F37#,
Draw_Indirect_Buffer => 16#8F3F#,
Shader_Storage_Buffer => 16#90D2#,
Dispatch_Indirect_Buffer => 16#90EE#,
Query_Buffer => 16#9192#,
Atomic_Counter_Buffer => 16#92C0#);
for Buffer_Kind'Size use Enum'Size;
for Draw_Buffer_Index use (DB0 => 16#8825#,
DB1 => 16#8826#,
DB2 => 16#8827#,
DB3 => 16#8828#,
DB4 => 16#8829#,
DB5 => 16#882A#,
DB6 => 16#882B#,
DB7 => 16#882C#,
DB8 => 16#882D#,
DB9 => 16#882E#,
DB10 => 16#882F#,
DB11 => 16#8830#,
DB12 => 16#8831#,
DB13 => 16#8832#,
DB14 => 16#8833#,
DB15 => 16#8834#);
for Draw_Buffer_Index'Size use Int'Size;
for Only_Depth_Buffer use (Depth_Buffer => 16#1801#);
for Only_Depth_Buffer'Size use Enum'Size;
for Only_Stencil_Buffer use (Stencil => 16#1802#);
for Only_Stencil_Buffer'Size use Enum'Size;
for Only_Depth_Stencil_Buffer use (Depth_Stencil => 16#84F9#);
for Only_Depth_Stencil_Buffer'Size use Enum'Size;
for Only_Color_Buffer use (Color => 16#1800#);
for Only_Color_Buffer'Size use Enum'Size;
for Resource_Type use
(Int_Type => 16#1404#,
UInt_Type => 16#1405#,
Single_Type => 16#1406#,
Double_Type => 16#140A#,
Single_Vec2 => 16#8B50#,
Single_Vec3 => 16#8B51#,
Single_Vec4 => 16#8B52#,
Int_Vec2 => 16#8B53#,
Int_Vec3 => 16#8B54#,
Int_Vec4 => 16#8B55#,
Bool_Type => 16#8B56#,
Bool_Vec2 => 16#8B57#,
Bool_Vec3 => 16#8B58#,
Bool_Vec4 => 16#8B59#,
Single_Matrix2 => 16#8B5A#,
Single_Matrix3 => 16#8B5B#,
Single_Matrix4 => 16#8B5C#,
Sampler_1D => 16#8B5D#,
Sampler_2D => 16#8B5E#,
Sampler_3D => 16#8B5F#,
Sampler_Cube => 16#8B60#,
Sampler_1D_Shadow => 16#8B61#,
Sampler_2D_Shadow => 16#8B62#,
Sampler_2D_Rect => 16#8B63#,
Sampler_2D_Rect_Shadow => 16#8B64#,
Single_Matrix2x3 => 16#8B65#,
Single_Matrix2x4 => 16#8B66#,
Single_Matrix3x2 => 16#8B67#,
Single_Matrix3x4 => 16#8B68#,
Single_Matrix4x2 => 16#8B69#,
Single_Matrix4x3 => 16#8B6A#,
Sampler_1D_Array => 16#8DC0#,
Sampler_2D_Array => 16#8DC1#,
Sampler_Buffer => 16#8DC2#,
Sampler_1D_Array_Shadow => 16#8DC3#,
Sampler_2D_Array_Shadow => 16#8DC4#,
Sampler_Cube_Shadow => 16#8DC5#,
UInt_Vec2 => 16#8DC6#,
UInt_Vec3 => 16#8DC7#,
UInt_Vec4 => 16#8DC8#,
Int_Sampler_1D => 16#8DC9#,
Int_Sampler_2D => 16#8DCA#,
Int_Sampler_3D => 16#8DCB#,
Int_Sampler_Cube => 16#8DCC#,
Int_Sampler_2D_Rect => 16#8DCD#,
Int_Sampler_1D_Array => 16#8DCE#,
Int_Sampler_2D_Array => 16#8DCF#,
Int_Sampler_Buffer => 16#8DD0#,
UInt_Sampler_1D => 16#8DD1#,
UInt_Sampler_2D => 16#8DD2#,
UInt_Sampler_3D => 16#8DD3#,
UInt_Sampler_Cube => 16#8DD4#,
UInt_Sampler_2D_Rect => 16#8DD5#,
UInt_Sampler_1D_Array => 16#8DD6#,
UInt_Sampler_2D_Array => 16#8DD7#,
UInt_Sampler_Buffer => 16#8DD8#,
Double_Matrix2 => 16#8F46#,
Double_Matrix3 => 16#8F47#,
Double_Matrix4 => 16#8F48#,
Double_Matrix2x3 => 16#8F49#,
Double_Matrix2x4 => 16#8F4A#,
Double_Matrix3x2 => 16#8F4B#,
Double_Matrix3x4 => 16#8F4C#,
Double_Matrix4x2 => 16#8F4D#,
Double_Matrix4x3 => 16#8F4E#,
Double_Vec2 => 16#8FFC#,
Double_Vec3 => 16#8FFD#,
Double_Vec4 => 16#8FFE#,
Sampler_2D_Multisample => 16#9108#,
Int_Sampler_2D_Multisample => 16#9109#,
UInt_Sampler_2D_Multisample => 16#910A#,
Sampler_2D_Multisample_Array => 16#910B#,
Int_Sampler_2D_Multisample_Array => 16#910C#,
UInt_Sampler_2D_Multisample_Array => 16#910D#);
for Resource_Type'Size use Enum'Size;
end GL.Low_Level.Enums;
|
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT 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 GL.Low_Level.Enums is
pragma Preelaborate;
-- Unlike GL.Enums, this package is not private and hosts enum types that may
-- be needed by third-party code or wrappers.
type Texture_Kind is (Texture_1D, Texture_2D, Texture_3D,
Texture_Rectangle, Texture_Cube_Map,
Texture_1D_Array, Texture_2D_Array,
Texture_Buffer, Texture_Cube_Map_Array,
Texture_2D_Multisample, Texture_2D_Multisample_Array);
type Renderbuffer_Kind is (Renderbuffer);
type Framebuffer_Kind is (Read, Draw);
type Transform_Feedback_Kind is (Transform_Feedback);
type Buffer_Kind is (Array_Buffer, Element_Array_Buffer, Pixel_Pack_Buffer,
Pixel_Unpack_Buffer, Uniform_Buffer, Texture_Buffer,
Transform_Feedback_Buffer, Copy_Read_Buffer,
Copy_Write_Buffer, Draw_Indirect_Buffer,
Shader_Storage_Buffer, Dispatch_Indirect_Buffer,
Query_Buffer, Atomic_Counter_Buffer);
type Draw_Buffer_Index is (DB0, DB1, DB2, DB3, DB4, DB5, DB6, DB7,
DB8, DB9, DB10, DB11, DB12, DB13, DB14, DB15);
type Only_Depth_Buffer is (Depth_Buffer);
type Only_Stencil_Buffer is (Stencil);
type Only_Depth_Stencil_Buffer is (Depth_Stencil);
type Only_Color_Buffer is (Color);
type Resource_Type is
(Int_Type,
UInt_Type,
Single_Type,
Double_Type,
Single_Vec2,
Single_Vec3,
Single_Vec4,
Int_Vec2,
Int_Vec3,
Int_Vec4,
Bool_Type,
Bool_Vec2,
Bool_Vec3,
Bool_Vec4,
Single_Matrix2,
Single_Matrix3,
Single_Matrix4,
Sampler_1D,
Sampler_2D,
Sampler_3D,
Sampler_Cube,
Sampler_1D_Shadow,
Sampler_2D_Shadow,
Sampler_2D_Rect,
Sampler_2D_Rect_Shadow,
Single_Matrix2x3,
Single_Matrix2x4,
Single_Matrix3x2,
Single_Matrix3x4,
Single_Matrix4x2,
Single_Matrix4x3,
Sampler_1D_Array,
Sampler_2D_Array,
Sampler_Buffer,
Sampler_1D_Array_Shadow,
Sampler_2D_Array_Shadow,
Sampler_Cube_Shadow,
UInt_Vec2,
UInt_Vec3,
UInt_Vec4,
Int_Sampler_1D,
Int_Sampler_2D,
Int_Sampler_3D,
Int_Sampler_Cube,
Int_Sampler_2D_Rect,
Int_Sampler_1D_Array,
Int_Sampler_2D_Array,
Int_Sampler_Buffer,
UInt_Sampler_1D,
UInt_Sampler_2D,
UInt_Sampler_3D,
UInt_Sampler_Cube,
UInt_Sampler_2D_Rect,
UInt_Sampler_1D_Array,
UInt_Sampler_2D_Array,
UInt_Sampler_Buffer,
Double_Matrix2,
Double_Matrix3,
Double_Matrix4,
Double_Matrix2x3,
Double_Matrix2x4,
Double_Matrix3x2,
Double_Matrix3x4,
Double_Matrix4x2,
Double_Matrix4x3,
Double_Vec2,
Double_Vec3,
Double_Vec4,
Sampler_Cube_Array,
Sampler_Cube_Array_Shadow,
Int_Sampler_Cube_Array,
UInt_Sampler_Cube_Array,
Sampler_2D_Multisample,
Int_Sampler_2D_Multisample,
UInt_Sampler_2D_Multisample,
Sampler_2D_Multisample_Array,
Int_Sampler_2D_Multisample_Array,
UInt_Sampler_2D_Multisample_Array);
private
for Texture_Kind use (Texture_1D => 16#0DE0#,
Texture_2D => 16#0DE1#,
Texture_3D => 16#806F#,
Texture_Rectangle => 16#84F5#,
Texture_Cube_Map => 16#8513#,
Texture_1D_Array => 16#8C18#,
Texture_2D_Array => 16#8C1A#,
Texture_Buffer => 16#8C2A#,
Texture_Cube_Map_Array => 16#9009#,
Texture_2D_Multisample => 16#9100#,
Texture_2D_Multisample_Array => 16#9102#);
for Texture_Kind'Size use Enum'Size;
for Renderbuffer_Kind use (Renderbuffer => 16#8D41#);
for Renderbuffer_Kind'Size use Enum'Size;
for Framebuffer_Kind use (Read => 16#8CA8#,
Draw => 16#8CA9#);
for Framebuffer_Kind'Size use Enum'Size;
for Transform_Feedback_Kind use (Transform_Feedback => 16#8E22#);
for Transform_Feedback_Kind'Size use Enum'Size;
for Buffer_Kind use (Array_Buffer => 16#8892#,
Element_Array_Buffer => 16#8893#,
Pixel_Pack_Buffer => 16#88EB#,
Pixel_Unpack_Buffer => 16#88EC#,
Uniform_Buffer => 16#8A11#,
Texture_Buffer => 16#8C2A#,
Transform_Feedback_Buffer => 16#8C8E#,
Copy_Read_Buffer => 16#8F36#,
Copy_Write_Buffer => 16#8F37#,
Draw_Indirect_Buffer => 16#8F3F#,
Shader_Storage_Buffer => 16#90D2#,
Dispatch_Indirect_Buffer => 16#90EE#,
Query_Buffer => 16#9192#,
Atomic_Counter_Buffer => 16#92C0#);
for Buffer_Kind'Size use Enum'Size;
for Draw_Buffer_Index use (DB0 => 16#8825#,
DB1 => 16#8826#,
DB2 => 16#8827#,
DB3 => 16#8828#,
DB4 => 16#8829#,
DB5 => 16#882A#,
DB6 => 16#882B#,
DB7 => 16#882C#,
DB8 => 16#882D#,
DB9 => 16#882E#,
DB10 => 16#882F#,
DB11 => 16#8830#,
DB12 => 16#8831#,
DB13 => 16#8832#,
DB14 => 16#8833#,
DB15 => 16#8834#);
for Draw_Buffer_Index'Size use Int'Size;
for Only_Depth_Buffer use (Depth_Buffer => 16#1801#);
for Only_Depth_Buffer'Size use Enum'Size;
for Only_Stencil_Buffer use (Stencil => 16#1802#);
for Only_Stencil_Buffer'Size use Enum'Size;
for Only_Depth_Stencil_Buffer use (Depth_Stencil => 16#84F9#);
for Only_Depth_Stencil_Buffer'Size use Enum'Size;
for Only_Color_Buffer use (Color => 16#1800#);
for Only_Color_Buffer'Size use Enum'Size;
for Resource_Type use
(Int_Type => 16#1404#,
UInt_Type => 16#1405#,
Single_Type => 16#1406#,
Double_Type => 16#140A#,
Single_Vec2 => 16#8B50#,
Single_Vec3 => 16#8B51#,
Single_Vec4 => 16#8B52#,
Int_Vec2 => 16#8B53#,
Int_Vec3 => 16#8B54#,
Int_Vec4 => 16#8B55#,
Bool_Type => 16#8B56#,
Bool_Vec2 => 16#8B57#,
Bool_Vec3 => 16#8B58#,
Bool_Vec4 => 16#8B59#,
Single_Matrix2 => 16#8B5A#,
Single_Matrix3 => 16#8B5B#,
Single_Matrix4 => 16#8B5C#,
Sampler_1D => 16#8B5D#,
Sampler_2D => 16#8B5E#,
Sampler_3D => 16#8B5F#,
Sampler_Cube => 16#8B60#,
Sampler_1D_Shadow => 16#8B61#,
Sampler_2D_Shadow => 16#8B62#,
Sampler_2D_Rect => 16#8B63#,
Sampler_2D_Rect_Shadow => 16#8B64#,
Single_Matrix2x3 => 16#8B65#,
Single_Matrix2x4 => 16#8B66#,
Single_Matrix3x2 => 16#8B67#,
Single_Matrix3x4 => 16#8B68#,
Single_Matrix4x2 => 16#8B69#,
Single_Matrix4x3 => 16#8B6A#,
Sampler_1D_Array => 16#8DC0#,
Sampler_2D_Array => 16#8DC1#,
Sampler_Buffer => 16#8DC2#,
Sampler_1D_Array_Shadow => 16#8DC3#,
Sampler_2D_Array_Shadow => 16#8DC4#,
Sampler_Cube_Shadow => 16#8DC5#,
UInt_Vec2 => 16#8DC6#,
UInt_Vec3 => 16#8DC7#,
UInt_Vec4 => 16#8DC8#,
Int_Sampler_1D => 16#8DC9#,
Int_Sampler_2D => 16#8DCA#,
Int_Sampler_3D => 16#8DCB#,
Int_Sampler_Cube => 16#8DCC#,
Int_Sampler_2D_Rect => 16#8DCD#,
Int_Sampler_1D_Array => 16#8DCE#,
Int_Sampler_2D_Array => 16#8DCF#,
Int_Sampler_Buffer => 16#8DD0#,
UInt_Sampler_1D => 16#8DD1#,
UInt_Sampler_2D => 16#8DD2#,
UInt_Sampler_3D => 16#8DD3#,
UInt_Sampler_Cube => 16#8DD4#,
UInt_Sampler_2D_Rect => 16#8DD5#,
UInt_Sampler_1D_Array => 16#8DD6#,
UInt_Sampler_2D_Array => 16#8DD7#,
UInt_Sampler_Buffer => 16#8DD8#,
Double_Matrix2 => 16#8F46#,
Double_Matrix3 => 16#8F47#,
Double_Matrix4 => 16#8F48#,
Double_Matrix2x3 => 16#8F49#,
Double_Matrix2x4 => 16#8F4A#,
Double_Matrix3x2 => 16#8F4B#,
Double_Matrix3x4 => 16#8F4C#,
Double_Matrix4x2 => 16#8F4D#,
Double_Matrix4x3 => 16#8F4E#,
Double_Vec2 => 16#8FFC#,
Double_Vec3 => 16#8FFD#,
Double_Vec4 => 16#8FFE#,
Sampler_Cube_Array => 16#900C#,
Sampler_Cube_Array_Shadow => 16#900D#,
Int_Sampler_Cube_Array => 16#900E#,
UInt_Sampler_Cube_Array => 16#900F#,
Sampler_2D_Multisample => 16#9108#,
Int_Sampler_2D_Multisample => 16#9109#,
UInt_Sampler_2D_Multisample => 16#910A#,
Sampler_2D_Multisample_Array => 16#910B#,
Int_Sampler_2D_Multisample_Array => 16#910C#,
UInt_Sampler_2D_Multisample_Array => 16#910D#);
for Resource_Type'Size use Enum'Size;
end GL.Low_Level.Enums;
|
Add support for cube map array textures
|
gl: Add support for cube map array textures
* Extension ARB_texture_cube_map_array (OpenGL 4.0)
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
9cf3d8ef86d7de1e00e755fcb77efdcd8e15de14
|
src/base/beans/util-beans-objects-datasets.ads
|
src/base/beans/util-beans-objects-datasets.ads
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Datasets -- Datasets
-- 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 Ada.Strings.Hash;
with Ada.Finalization;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Beans.Basic;
-- == Datasets ==
-- The `Datasets` package implements the `Dataset` list bean which
-- defines a set of objects organized in rows and columns. The `Dataset`
-- implements the `List_Bean` interface and allows to iterate over its rows.
-- Each row defines a `Bean` instance and allows to access each column value.
-- Each column is associated with a unique name. The row `Bean` allows to
-- get or set the column by using the column name.
package Util.Beans.Objects.Datasets is
Invalid_State : exception;
-- An array of objects.
type Object_Array is array (Positive range <>) of Object;
type Dataset is new Util.Beans.Basic.List_Bean with private;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in Dataset) return Natural;
-- Set the current row index. Valid row indexes start at 1.
overriding
procedure Set_Row_Index (From : in out Dataset;
Index : in Natural);
-- Get the element at the current row index.
overriding
function Get_Row (From : in Dataset) return Util.Beans.Objects.Object;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Dataset;
Name : in String) return Util.Beans.Objects.Object;
-- Append a row in the dataset and call the fill procedure to populate
-- the row content.
procedure Append (Into : in out Dataset;
Fill : not null access procedure (Data : in out Object_Array));
-- Add a column to the dataset. If the position is not specified,
-- the column count is incremented and the name associated with the last column.
-- Raises Invalid_State exception if the dataset contains some rows,
procedure Add_Column (Into : in out Dataset;
Name : in String;
Pos : in Natural := 0);
-- Clear the content of the dataset.
procedure Clear (Set : in out Dataset);
private
type Object_Array_Access is access all Object_Array;
type Dataset_Array is array (Positive range <>) of Object_Array_Access;
type Dataset_Array_Access is access all Dataset_Array;
package Dataset_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Positive,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
type Row is new Util.Beans.Basic.Bean with record
Data : Object_Array_Access;
Map : access Dataset_Map.Map;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Row;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Row;
Name : in String;
Value : in Util.Beans.Objects.Object);
type Dataset is new Ada.Finalization.Controlled and Util.Beans.Basic.List_Bean with record
Data : Dataset_Array_Access;
Count : Natural := 0;
Columns : Natural := 0;
Map : aliased Dataset_Map.Map;
Current : aliased Row;
Current_Pos : Natural := 0;
Row : Util.Beans.Objects.Object;
end record;
-- Initialize the dataset and the row bean instance.
overriding
procedure Initialize (Set : in out Dataset);
-- Release the dataset storage.
overriding
procedure Finalize (Set : in out Dataset);
end Util.Beans.Objects.Datasets;
|
-----------------------------------------------------------------------
-- util-beans-objects-datasets -- Datasets
-- Copyright (C) 2013, 2018, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Hash;
with Ada.Finalization;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Beans.Basic;
with Util.Beans.Objects.Iterators;
-- == Datasets ==
-- The `Datasets` package implements the `Dataset` list bean which
-- defines a set of objects organized in rows and columns. The `Dataset`
-- implements the `List_Bean` interface and allows to iterate over its rows.
-- Each row defines a `Bean` instance and allows to access each column value.
-- Each column is associated with a unique name. The row `Bean` allows to
-- get or set the column by using the column name.
--
-- with Util.Beans.Objects.Datasets;
-- ...
-- Set : Util.Beans.Objects.Datasets.Dataset_Access
-- := new Util.Beans.Objects.Datasets.Dataset;
--
-- After creation of the dataset instance, the first step is to define
-- the columns that composed the list. This is done by using the `Add_Column`
-- procedure:
--
-- Set.Add_Column ("name");
-- Set.Add_Column ("email");
-- Set.Add_Column ("age");
--
-- To populate the dataset, the package only provide the `Append` procedure
-- which adds a new row and calls a procedure whose job is to fill the columns
-- of the new row. The procedure gets the row as an array of `Object`:
--
-- procedure Fill (Row : in out Util.Beans.Objects.Object_Array) is
-- begin
-- Row (Row'First) := To_Object (String '("Yoda"));
-- Row (Row'First + 1) := To_Object (String '("Yoda@Dagobah"));
-- Row (Row'First + 2) := To_Object (Integer (900));
-- end Fill;
--
-- Set.Append (Fill'Access);
--
-- The dataset instance is converted to an `Object` by using the `To_Object`
-- function. Note that the default behavior of `To_Object` is to take
-- the ownershiup of the object and hence it will be released automatically.
--
-- List : Util.Beans.Objects.Object
-- := Util.Beans.Objects.To_Object (Set);
--
package Util.Beans.Objects.Datasets is
subtype Iterator_Bean is Util.Beans.Objects.Iterators.Iterator_Bean;
Invalid_State : exception;
type Dataset is new Util.Beans.Basic.List_Bean and Iterator_Bean with private;
type Dataset_Access is access all Dataset'Class;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in Dataset) return Natural;
-- Set the current row index. Valid row indexes start at 1.
overriding
procedure Set_Row_Index (From : in out Dataset;
Index : in Natural);
-- Get the element at the current row index.
overriding
function Get_Row (From : in Dataset) return Util.Beans.Objects.Object;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Dataset;
Name : in String) return Util.Beans.Objects.Object;
-- Get an iterator to iterate starting with the first element.
overriding
function First (From : in Dataset) return Iterators.Proxy_Iterator_Access;
-- Get an iterator to iterate starting with the last element.
overriding
function Last (From : in Dataset) return Iterators.Proxy_Iterator_Access;
-- Append a row in the dataset and call the fill procedure to populate
-- the row content.
procedure Append (Into : in out Dataset;
Fill : not null access procedure (Data : in out Object_Array));
-- Add a column to the dataset. If the position is not specified,
-- the column count is incremented and the name associated with the last column.
-- Raises Invalid_State exception if the dataset contains some rows,
procedure Add_Column (Into : in out Dataset;
Name : in String;
Pos : in Natural := 0);
-- Clear the content of the dataset.
procedure Clear (Set : in out Dataset);
private
type Object_Array_Access is access all Object_Array;
type Dataset_Array is array (Positive range <>) of Object_Array_Access;
type Dataset_Array_Access is access all Dataset_Array;
package Dataset_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Positive,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
type Row is new Util.Beans.Basic.Bean and Iterator_Bean with record
Data : Object_Array_Access;
Map : access Dataset_Map.Map;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Row;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Row;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get an iterator to iterate starting with the first element.
overriding
function First (From : in Row) return Iterators.Proxy_Iterator_Access;
-- Get an iterator to iterate starting with the last element.
overriding
function Last (From : in Row) return Iterators.Proxy_Iterator_Access;
type Dataset is new Ada.Finalization.Controlled
and Util.Beans.Basic.List_Bean and Iterator_Bean with record
Data : Dataset_Array_Access;
Count : Natural := 0;
Columns : Natural := 0;
Map : aliased Dataset_Map.Map;
Current : aliased Row;
Current_Pos : Natural := 0;
Row : Util.Beans.Objects.Object;
end record;
-- Initialize the dataset and the row bean instance.
overriding
procedure Initialize (Set : in out Dataset);
-- Release the dataset storage.
overriding
procedure Finalize (Set : in out Dataset);
type Dataset_Iterator is new Iterators.Proxy_Iterator with record
Current : aliased Row;
Current_Pos : Natural := 0;
Row : Util.Beans.Objects.Object;
end record;
type Dataset_Iterator_Access is access all Dataset_Iterator;
overriding
procedure Initialize (Iter : in out Dataset_Iterator);
overriding
function Has_Element (Iter : in Dataset_Iterator) return Boolean;
overriding
procedure Next (Iter : in out Dataset_Iterator);
overriding
procedure Previous (Iter : in out Dataset_Iterator);
overriding
function Element (Iter : in Dataset_Iterator) return Object;
type Row_Iterator is new Iterators.Proxy_Map_Iterator with record
Pos : Dataset_Map.Cursor;
Data : Object_Array_Access;
end record;
type Row_Iterator_Access is access all Row_Iterator;
overriding
procedure Initialize (Iter : in out Row_Iterator);
overriding
function Has_Element (Iter : in Row_Iterator) return Boolean;
overriding
procedure Next (Iter : in out Row_Iterator);
overriding
procedure Previous (Iter : in out Row_Iterator);
overriding
function Element (Iter : in Row_Iterator) return Object;
overriding
function Key (Iter : in Row_Iterator) return String;
end Util.Beans.Objects.Datasets;
|
Add some documentation Implement the Iterator_Bean interface to allow iterating over the dataset and its columns
|
Add some documentation
Implement the Iterator_Bean interface to allow iterating over the dataset
and its columns
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8de13147f9d0d76bbecef7a66a49ac66265ca245
|
src/security-auth-oauth.adb
|
src/security-auth-oauth.adb
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Assoc_Handle := To_Unbounded_String ("nonce-generator");
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Assoc_Handle := To_Unbounded_String ("nonce-generator");
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
Initialize the issuer from the parameters
|
Initialize the issuer from the parameters
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
df73136f9605070c18f3f7b31abd2d029fa397d5
|
src/wiki-filters-toc.ads
|
src/wiki-filters-toc.ads
|
-----------------------------------------------------------------------
-- wiki-filters-toc -- Filter for the creation of Table Of Contents
-- 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.
-----------------------------------------------------------------------
-- === TOC Filter ===
-- The <tt>TOC_Filter</tt> is a filter used to build the table of contents.
-- It collects the headers with the section level as they are added to the
-- wiki document. The TOC is built in the wiki document as a separate node
-- and it can be retrieved by using the <tt>Get_TOC</tt> function.
package Wiki.Filters.TOC is
pragma Preelaborate;
-- ------------------------------
-- TOC Filter
-- ------------------------------
type TOC_Filter is new Filter_Type with null record;
-- Add a text content with the given format to the document.
overriding
procedure Add_Text (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
overriding
procedure Add_Header (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
end Wiki.Filters.TOC;
|
-----------------------------------------------------------------------
-- wiki-filters-toc -- Filter for the creation of Table Of Contents
-- 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.
-----------------------------------------------------------------------
-- === TOC Filter ===
-- The <tt>TOC_Filter</tt> is a filter used to build the table of contents.
-- It collects the headers with the section level as they are added to the
-- wiki document. The TOC is built in the wiki document as a separate node
-- and it can be retrieved by using the <tt>Get_TOC</tt> function. To use
-- the filter, declare an aliased instance:
--
-- TOC : aliased Wiki.Filters.TOC.TOC_Filter;
--
-- and add the filter to the Wiki parser engine:
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
--
package Wiki.Filters.TOC is
pragma Preelaborate;
-- ------------------------------
-- TOC Filter
-- ------------------------------
type TOC_Filter is new Filter_Type with null record;
-- Add a text content with the given format to the document.
overriding
procedure Add_Text (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
overriding
procedure Add_Header (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
end Wiki.Filters.TOC;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
2ff734b6c07623b724b16ec5e68412ffdeeeebdf
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with ADO.Objects;
with ADO.Sessions;
with Ada.Calendar;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Stat_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Workspaces.Modules.Add_Permission (Session => DB,
User => User,
Entity => Blog,
Workspace => WS.Get_Id,
List => (ACL_Delete_Blog.Permission,
ACL_Update_Post.Permission,
ACL_Create_Post.Permission,
ACL_Delete_Post.Permission));
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
-- ------------------------------
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Storages.Models;
with ADO.Objects;
with ADO.Sessions;
with ADO.Statements;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Stat_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Workspaces.Modules.Add_Permission (Session => DB,
User => User,
Entity => Blog,
Workspace => WS.Get_Id,
List => (ACL_Delete_Blog.Permission,
ACL_Update_Post.Permission,
ACL_Create_Post.Permission,
ACL_Delete_Post.Permission));
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
-- ------------------------------
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
-- ------------------------------
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
-- ------------------------------
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Model);
use type AWA.Storages.Models.Storage_Type;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement;
Kind : AWA.Storages.Models.Storage_Type;
begin
if Width = Natural'Last or Height = Natural'Last then
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
elsif Width > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data);
Query.Bind_Param ("width", Width);
elsif Height > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data);
Query.Bind_Param ("height", Height);
else
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
end if;
Query.Bind_Param ("post_id", Post_Id);
Query.Bind_Param ("store_id", Image_Id);
Query.Bind_Param ("user_id", User);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Width := Query.Get_Natural (4);
Height := Query.Get_Natural (5);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (6);
else
null;
end if;
end Load_Image;
end AWA.Blogs.Modules;
|
Implement the Load_Image procedure to load the image data for a post
|
Implement the Load_Image procedure to load the image data for a post
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
c09a715ea7870f459693c7d030542b3c50d5def7
|
awa/plugins/awa-counters/src/awa-counters.ads
|
awa/plugins/awa-counters/src/awa-counters.ads
|
-----------------------------------------------------------------------
-- awa-counters --
-- 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 ADO.Objects;
with ADO.Schemas;
with Util.Strings;
with AWA.Index_Arrays;
package AWA.Counters is
type Counter_Index_Type is new Natural;
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object <tt>Object</tt>.
procedure Increment (Counter : in Counter_Index_Type;
Object : in ADO.Objects.Object_Ref'Class);
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object key <tt>Key</tt>.
procedure Increment (Counter : in Counter_Index_Type;
Key : in ADO.Objects.Object_Key);
-- Increment the global counter identified by <tt>Counter</tt>.
procedure Increment (Counter : in Counter_Index_Type);
private
type Counter_Def is record
Table : ADO.Schemas.Class_Mapping_Access;
Field : Util.Strings.Name_Access;
end record;
function "=" (Left, Right : in Counter_Def) return Boolean;
function "<" (Left, Right : in Counter_Def) return Boolean;
function "&" (Left : in String;
Right : in Counter_Def) return String;
package Counter_Arrays is new AWA.Index_Arrays (Counter_Index_Type, Counter_Def);
end AWA.Counters;
|
-----------------------------------------------------------------------
-- awa-counters --
-- 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 ADO.Objects;
with ADO.Schemas;
with Util.Strings;
with AWA.Index_Arrays;
-- == Introduction ==
-- The <b>Counters</b> module defines a general purpose counter service that allows to
-- associate counters to database entities. For example it can be used to track the number
-- of times a blog post or a wiki page is accessed. The <b>Counters</b> module maintains the
-- counters in a table on a per-day and per-entity basis. It allows to update the full counter
-- in the target database entity table.
--
-- @include awa-counters-modules.ads
--
-- === Counter Declaration ===
-- Each counter must be declared by instantiating the <b>Definition</b> package.
-- This instantiation serves as identification of the counter and it defines the database
-- table as well as the column in that table that will hold the total counter. The following
-- definition is used for the read counter of a wiki page. The wiki page table contains a
-- <i>read_count</i> column and it will be incremented each time the counter is incremented.
--
-- package Read_Counter is
-- new AWA.Counters.Definition (AWA.Wikis.Models.WIKI_PAGE_TABLE, "read_count");
--
-- When the database table does not contain any counter column, the counter definition is
-- defined as follows:
--
-- package Login_Counter is
-- new AWA.Counters.Definition (AWA.Users.Models.USER_PAGE_TABLE);
--
-- Sometimes a counter is not associated with any database entity. Such counters are global
-- and they are assigned a unique name.
--
-- package Start_Counter is
-- new AWA.Counters.Definition (null, "startup_counter");
--
-- === Incrementing the counter ===
-- Incrementing the counter is done by calling the <b>Increment</b> operation.
-- When the counter is associated with a database entity, the entity primary key must be given.
--
-- AWA.Counters.Increment (Counter => Read_Counter.Counter, Key => Id);
--
-- A global counter is also incremented by using the <b>Increment</b> operation.
--
-- AWA.Counters.Increment (Counter => Start_Counter.Counter);
--
-- @include awa-counters-beans.ads
-- @include awa-counters-components.ads
-- @include counters.xml
--
-- == Model ==
-- [images/awa_counters_model.png]
--
package AWA.Counters is
type Counter_Index_Type is new Natural;
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object <tt>Object</tt>.
procedure Increment (Counter : in Counter_Index_Type;
Object : in ADO.Objects.Object_Ref'Class);
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object key <tt>Key</tt>.
procedure Increment (Counter : in Counter_Index_Type;
Key : in ADO.Objects.Object_Key);
-- Increment the global counter identified by <tt>Counter</tt>.
procedure Increment (Counter : in Counter_Index_Type);
private
type Counter_Def is record
Table : ADO.Schemas.Class_Mapping_Access;
Field : Util.Strings.Name_Access;
end record;
function "=" (Left, Right : in Counter_Def) return Boolean;
function "<" (Left, Right : in Counter_Def) return Boolean;
function "&" (Left : in String;
Right : in Counter_Def) return String;
package Counter_Arrays is new AWA.Index_Arrays (Counter_Index_Type, Counter_Def);
end AWA.Counters;
|
Document the AWA counters plugin
|
Document the AWA counters plugin
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
776104864ab10c8b88fd3a6a458f3ad433fb8ec6
|
src/el-contexts-default.ads
|
src/el-contexts-default.ads
|
-----------------------------------------------------------------------
-- EL.Contexts -- Default contexts for evaluating an expression
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Variables;
with Ada.Finalization;
private with Util.Beans.Objects.Maps;
-- private with EL.Objects.Maps; creates Assert_Failure sem_ch10.adb:2691
package EL.Contexts.Default is
-- ------------------------------
-- Default Context
-- ------------------------------
-- Context information for expression evaluation.
type Default_Context is new Ada.Finalization.Controlled and ELContext with private;
type Default_Context_Access is access all Default_Context'Class;
-- Retrieves the ELResolver associated with this ELcontext.
overriding
function Get_Resolver (Context : Default_Context) return ELResolver_Access;
-- Retrieves the VariableMapper associated with this ELContext.
overriding
function Get_Variable_Mapper (Context : Default_Context)
return access EL.Variables.Variable_Mapper'Class;
-- Retrieves the FunctionMapper associated with this ELContext.
-- The FunctionMapper is only used when parsing an expression.
overriding
function Get_Function_Mapper (Context : Default_Context)
return EL.Functions.Function_Mapper_Access;
-- Set the function mapper to be used when parsing an expression.
overriding
procedure Set_Function_Mapper (Context : in out Default_Context;
Mapper : access EL.Functions.Function_Mapper'Class);
-- Set the VariableMapper associated with this ELContext.
overriding
procedure Set_Variable_Mapper (Context : in out Default_Context;
Mapper : access EL.Variables.Variable_Mapper'Class);
-- Set the ELResolver associated with this ELcontext.
procedure Set_Resolver (Context : in out Default_Context;
Resolver : in ELResolver_Access);
procedure Set_Variable (Context : in out Default_Context;
Name : in String;
Value : access Util.Beans.Basic.Readonly_Bean'Class);
-- Handle the exception during expression evaluation.
overriding
procedure Handle_Exception (Context : in Default_Context;
Ex : in Ada.Exceptions.Exception_Occurrence);
-- ------------------------------
-- Guarded Context
-- ------------------------------
-- The <b>Guarded_Context</b> is a proxy context that allows to handle exceptions
-- raised when evaluating expressions. The <b>Handler</b> procedure will be called
-- when an exception is raised when the expression is evaluated. This allows to
-- report an error message and ignore or not the exception (See ASF).
type Guarded_Context (Handler : not null access
procedure (Ex : in Ada.Exceptions.Exception_Occurrence);
Context : ELContext_Access)
is new Ada.Finalization.Limited_Controlled and ELContext with null record;
type Guarded_Context_Access is access all Default_Context'Class;
-- Retrieves the ELResolver associated with this ELcontext.
overriding
function Get_Resolver (Context : in Guarded_Context) return ELResolver_Access;
-- Retrieves the Variable_Mapper associated with this ELContext.
overriding
function Get_Variable_Mapper (Context : in Guarded_Context)
return access EL.Variables.Variable_Mapper'Class;
-- Retrieves the Function_Mapper associated with this ELContext.
-- The Function_Mapper is only used when parsing an expression.
overriding
function Get_Function_Mapper (Context : in Guarded_Context)
return EL.Functions.Function_Mapper_Access;
-- Set the function mapper to be used when parsing an expression.
overriding
procedure Set_Function_Mapper (Context : in out Guarded_Context;
Mapper : access EL.Functions.Function_Mapper'Class);
-- Set the Variable_Mapper associated with this ELContext.
overriding
procedure Set_Variable_Mapper (Context : in out Guarded_Context;
Mapper : access EL.Variables.Variable_Mapper'Class);
-- Handle the exception during expression evaluation.
overriding
procedure Handle_Exception (Context : in Guarded_Context;
Ex : in Ada.Exceptions.Exception_Occurrence);
-- ------------------------------
-- Default Resolver
-- ------------------------------
type Default_ELResolver is new ELResolver with private;
type Default_ELResolver_Access is access all Default_ELResolver'Class;
-- Get the value associated with a base object and a given property.
overriding
function Get_Value (Resolver : Default_ELResolver;
Context : ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : Unbounded_String) return EL.Objects.Object;
-- Set the value associated with a base object and a given property.
overriding
procedure Set_Value (Resolver : in out Default_ELResolver;
Context : in ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Unbounded_String;
Value : in EL.Objects.Object);
-- Register the value under the given name.
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : in Util.Beans.Basic.Readonly_Bean_Access);
-- Register the value under the given name.
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : in EL.Objects.Object);
private
type Default_Context is new Ada.Finalization.Controlled and ELContext with record
Var_Mapper : EL.Variables.Variable_Mapper_Access;
Resolver : ELResolver_Access;
Function_Mapper : EL.Functions.Function_Mapper_Access;
Var_Mapper_Created : Boolean := False;
end record;
overriding
procedure Finalize (Obj : in out Default_Context);
type Default_ELResolver is new ELResolver with record
Map : EL.Objects.Maps.Map;
end record;
end EL.Contexts.Default;
|
-----------------------------------------------------------------------
-- EL.Contexts -- Default contexts for evaluating an expression
-- Copyright (C) 2009, 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Variables;
with Ada.Finalization;
private with Util.Beans.Objects.Maps;
-- private with EL.Objects.Maps; creates Assert_Failure sem_ch10.adb:2691
package EL.Contexts.Default is
-- ------------------------------
-- Default Context
-- ------------------------------
-- Context information for expression evaluation.
type Default_Context is new Ada.Finalization.Controlled and ELContext with private;
type Default_Context_Access is access all Default_Context'Class;
overriding
procedure Finalize (Obj : in out Default_Context);
-- Retrieves the ELResolver associated with this ELcontext.
overriding
function Get_Resolver (Context : Default_Context) return ELResolver_Access;
-- Retrieves the VariableMapper associated with this ELContext.
overriding
function Get_Variable_Mapper (Context : Default_Context)
return access EL.Variables.Variable_Mapper'Class;
-- Retrieves the FunctionMapper associated with this ELContext.
-- The FunctionMapper is only used when parsing an expression.
overriding
function Get_Function_Mapper (Context : Default_Context)
return EL.Functions.Function_Mapper_Access;
-- Set the function mapper to be used when parsing an expression.
overriding
procedure Set_Function_Mapper (Context : in out Default_Context;
Mapper : access EL.Functions.Function_Mapper'Class);
-- Set the VariableMapper associated with this ELContext.
overriding
procedure Set_Variable_Mapper (Context : in out Default_Context;
Mapper : access EL.Variables.Variable_Mapper'Class);
-- Set the ELResolver associated with this ELcontext.
procedure Set_Resolver (Context : in out Default_Context;
Resolver : in ELResolver_Access);
procedure Set_Variable (Context : in out Default_Context;
Name : in String;
Value : access Util.Beans.Basic.Readonly_Bean'Class);
-- Handle the exception during expression evaluation.
overriding
procedure Handle_Exception (Context : in Default_Context;
Ex : in Ada.Exceptions.Exception_Occurrence);
-- ------------------------------
-- Guarded Context
-- ------------------------------
-- The <b>Guarded_Context</b> is a proxy context that allows to handle exceptions
-- raised when evaluating expressions. The <b>Handler</b> procedure will be called
-- when an exception is raised when the expression is evaluated. This allows to
-- report an error message and ignore or not the exception (See ASF).
type Guarded_Context (Handler : not null access
procedure (Ex : in Ada.Exceptions.Exception_Occurrence);
Context : ELContext_Access)
is new Ada.Finalization.Limited_Controlled and ELContext with null record;
type Guarded_Context_Access is access all Default_Context'Class;
-- Retrieves the ELResolver associated with this ELcontext.
overriding
function Get_Resolver (Context : in Guarded_Context) return ELResolver_Access;
-- Retrieves the Variable_Mapper associated with this ELContext.
overriding
function Get_Variable_Mapper (Context : in Guarded_Context)
return access EL.Variables.Variable_Mapper'Class;
-- Retrieves the Function_Mapper associated with this ELContext.
-- The Function_Mapper is only used when parsing an expression.
overriding
function Get_Function_Mapper (Context : in Guarded_Context)
return EL.Functions.Function_Mapper_Access;
-- Set the function mapper to be used when parsing an expression.
overriding
procedure Set_Function_Mapper (Context : in out Guarded_Context;
Mapper : access EL.Functions.Function_Mapper'Class);
-- Set the Variable_Mapper associated with this ELContext.
overriding
procedure Set_Variable_Mapper (Context : in out Guarded_Context;
Mapper : access EL.Variables.Variable_Mapper'Class);
-- Handle the exception during expression evaluation.
overriding
procedure Handle_Exception (Context : in Guarded_Context;
Ex : in Ada.Exceptions.Exception_Occurrence);
-- ------------------------------
-- Default Resolver
-- ------------------------------
type Default_ELResolver is new ELResolver with private;
type Default_ELResolver_Access is access all Default_ELResolver'Class;
-- Get the value associated with a base object and a given property.
overriding
function Get_Value (Resolver : Default_ELResolver;
Context : ELContext'Class;
Base : access Util.Beans.Basic.Readonly_Bean'Class;
Name : Unbounded_String) return EL.Objects.Object;
-- Set the value associated with a base object and a given property.
overriding
procedure Set_Value (Resolver : in out Default_ELResolver;
Context : in ELContext'Class;
Base : access Util.Beans.Basic.Bean'Class;
Name : in Unbounded_String;
Value : in EL.Objects.Object);
-- Register the value under the given name.
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : in Util.Beans.Basic.Readonly_Bean_Access);
-- Register the value under the given name.
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : in EL.Objects.Object);
private
type Default_Context is new Ada.Finalization.Controlled and ELContext with record
Var_Mapper : EL.Variables.Variable_Mapper_Access;
Resolver : ELResolver_Access;
Function_Mapper : EL.Functions.Function_Mapper_Access;
Var_Mapper_Created : Boolean := False;
end record;
type Default_ELResolver is new ELResolver with record
Map : EL.Objects.Maps.Map;
end record;
end EL.Contexts.Default;
|
Make the Finalize procedure visible
|
Make the Finalize procedure visible
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
6773db96c8b9cd015e12477215280b3095a874bd
|
regtests/ado-statements-tests.ads
|
regtests/ado-statements-tests.ads
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.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);
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);
end ADO.Statements.Tests;
|
Declare the Test_Invalid_Column procedure
|
Declare the Test_Invalid_Column procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
4bdadb9e52d29290803b6bf91151683469f29151
|
src/natools-s_expressions-printers-pretty.ads
|
src/natools-s_expressions-printers-pretty.ads
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.S_Expressions.Printers.Pretty provides an implementation of the --
-- S-expression Printer interface, using user-defines perferences to pretty --
-- print the S-expression into the output stream. --
------------------------------------------------------------------------------
with Ada.Streams;
with Natools.S_Expressions.Encodings;
package Natools.S_Expressions.Printers.Pretty is
pragma Pure (Pretty);
type Atom_Encoding is (Base64, Hexadecimal, Verbatim);
type Character_Encoding is (ASCII, Latin, UTF_8);
type Newline_Encoding is (CR, LF, CR_LF, LF_CR);
type Entity is (Opening, Atom_Data, Closing);
type Entity_Separator is array (Entity, Entity) of Boolean;
type Indent_Type is (Spaces, Tabs, Tabs_And_Spaces);
type Quoted_Escape_Type is (Hex_Escape, Octal_Escape);
type Quoted_Option is (When_Shorter, Single_Line, No_Quoted);
type Token_Option is (Extended_Token, Standard_Token, No_Token);
type Screen_Offset is new Natural;
subtype Screen_Column is Screen_Offset range 1 .. Screen_Offset'Last;
type Parameters is record
Width : Screen_Offset := 0;
Newline_At : Entity_Separator := (others => (others => False));
Space_At : Entity_Separator := (others => (others => False));
Tab_Stop : Screen_Column := 8; -- *
Indentation : Screen_Offset := 0;
Indent : Indent_Type := Spaces; -- *
Quoted : Quoted_Option := No_Quoted;
Token : Token_Option := No_Token;
Hex_Casing : Encodings.Hex_Casing := Encodings.Upper; -- *
Quoted_Escape : Quoted_Escape_Type := Hex_Escape; -- *
Char_Encoding : Character_Encoding := ASCII; -- *
Fallback : Atom_Encoding := Verbatim;
Newline : Newline_Encoding := LF; -- *
end record;
-- Default values yield canonical encoding, though fields marked with
-- an asterisk (*) can have any value and still be canonical.
Canonical : constant Parameters := (others => <>);
type Printer is abstract limited new Printers.Printer with private;
pragma Preelaborable_Initialization (Printer);
procedure Write_Raw
(Output : in out Printer;
Data : in Ada.Streams.Stream_Element_Array)
is abstract;
overriding procedure Open_List (Output : in out Printer);
overriding procedure Append_Atom
(Output : in out Printer;
Data : in Atom);
overriding procedure Close_List (Output : in out Printer);
procedure Newline (Output : in out Printer);
-- Open a new indented line in the output
procedure Set_Parameters (Output : in out Printer; Param : in Parameters);
function Get_Parameters (Output : Printer) return Parameters;
procedure Set_Width
(Output : in out Printer;
Width : in Screen_Offset);
procedure Set_Newline_At
(Output : in out Printer;
Newline_At : in Entity_Separator);
procedure Set_Space_At
(Output : in out Printer;
Space_At : in Entity_Separator);
procedure Set_Tab_Stop
(Output : in out Printer;
Tab_Stop : in Screen_Column);
procedure Set_Indentation
(Output : in out Printer;
Indentation : in Screen_Offset);
procedure Set_Indent
(Output : in out Printer;
Indent : in Indent_Type);
procedure Set_Quoted
(Output : in out Printer;
Quoted : in Quoted_Option);
procedure Set_Token
(Output : in out Printer;
Token : in Token_Option);
procedure Set_Hex_Casing
(Output : in out Printer;
Hex_Casing : in Encodings.Hex_Casing);
procedure Set_Quoted_Escape
(Output : in out Printer;
Quoted_Escape : in Quoted_Escape_Type);
procedure Set_Char_Encoding
(Output : in out Printer;
Char_Encoding : in Character_Encoding);
procedure Set_Fallback
(Output : in out Printer;
Fallback : in Atom_Encoding);
procedure Set_Newline
(Output : in out Printer;
Newline : in Newline_Encoding);
type Stream_Printer (Stream : access Ada.Streams.Root_Stream_Type'Class) is
limited new Printers.Printer with private;
private
type Printer is abstract limited new Printers.Printer with record
Param : Parameters;
Cursor : Screen_Column := 1;
Previous : Entity;
First : Boolean := True;
Indent_Level : Screen_Offset := 0;
Need_Blank : Boolean := False;
end record;
type Stream_Printer (Stream : access Ada.Streams.Root_Stream_Type'Class) is
new Printer with null record;
overriding procedure Write_Raw
(Output : in out Stream_Printer;
Data : in Ada.Streams.Stream_Element_Array);
end Natools.S_Expressions.Printers.Pretty;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.S_Expressions.Printers.Pretty provides an implementation of the --
-- S-expression Printer interface, using user-defines perferences to pretty --
-- print the S-expression into the output stream. --
------------------------------------------------------------------------------
with Ada.Streams;
with Natools.S_Expressions.Encodings;
package Natools.S_Expressions.Printers.Pretty is
pragma Pure (Pretty);
type Atom_Encoding is (Base64, Hexadecimal, Verbatim);
type Character_Encoding is (ASCII, Latin, UTF_8);
type Newline_Encoding is (CR, LF, CR_LF, LF_CR);
type Entity is (Opening, Atom_Data, Closing);
type Entity_Separator is array (Entity, Entity) of Boolean;
type Indent_Type is (Spaces, Tabs, Tabs_And_Spaces);
type Quoted_Escape_Type is (Hex_Escape, Octal_Escape);
type Quoted_Option is (When_Shorter, Single_Line, No_Quoted);
type Token_Option is (Extended_Token, Standard_Token, No_Token);
type Screen_Offset is new Natural;
subtype Screen_Column is Screen_Offset range 1 .. Screen_Offset'Last;
type Parameters is record
Width : Screen_Offset := 0;
Newline_At : Entity_Separator := (others => (others => False));
Space_At : Entity_Separator := (others => (others => False));
Tab_Stop : Screen_Column := 8; -- *
Indentation : Screen_Offset := 0;
Indent : Indent_Type := Spaces; -- *
Quoted : Quoted_Option := No_Quoted;
Token : Token_Option := No_Token;
Hex_Casing : Encodings.Hex_Casing := Encodings.Upper; -- *
Quoted_Escape : Quoted_Escape_Type := Hex_Escape; -- *
Char_Encoding : Character_Encoding := ASCII; -- *
Fallback : Atom_Encoding := Verbatim;
Newline : Newline_Encoding := LF; -- *
end record;
-- Default values yield canonical encoding, though fields marked with
-- an asterisk (*) can have any value and still be canonical.
Canonical : constant Parameters := (others => <>);
type Printer is abstract limited new Printers.Printer with private;
pragma Preelaborable_Initialization (Printer);
procedure Write_Raw
(Output : in out Printer;
Data : in Ada.Streams.Stream_Element_Array)
is abstract;
overriding procedure Open_List (Output : in out Printer);
overriding procedure Append_Atom
(Output : in out Printer;
Data : in Atom);
overriding procedure Close_List (Output : in out Printer);
procedure Newline (Output : in out Printer);
-- Open a new indented line in the output
procedure Set_Parameters (Output : in out Printer; Param : in Parameters);
function Get_Parameters (Output : Printer) return Parameters;
procedure Set_Width
(Output : in out Printer;
Width : in Screen_Offset);
procedure Set_Newline_At
(Output : in out Printer;
Newline_At : in Entity_Separator);
procedure Set_Space_At
(Output : in out Printer;
Space_At : in Entity_Separator);
procedure Set_Tab_Stop
(Output : in out Printer;
Tab_Stop : in Screen_Column);
procedure Set_Indentation
(Output : in out Printer;
Indentation : in Screen_Offset);
procedure Set_Indent
(Output : in out Printer;
Indent : in Indent_Type);
procedure Set_Quoted
(Output : in out Printer;
Quoted : in Quoted_Option);
procedure Set_Token
(Output : in out Printer;
Token : in Token_Option);
procedure Set_Hex_Casing
(Output : in out Printer;
Hex_Casing : in Encodings.Hex_Casing);
procedure Set_Quoted_Escape
(Output : in out Printer;
Quoted_Escape : in Quoted_Escape_Type);
procedure Set_Char_Encoding
(Output : in out Printer;
Char_Encoding : in Character_Encoding);
procedure Set_Fallback
(Output : in out Printer;
Fallback : in Atom_Encoding);
procedure Set_Newline
(Output : in out Printer;
Newline : in Newline_Encoding);
type Stream_Printer (Stream : access Ada.Streams.Root_Stream_Type'Class) is
limited new Printer with private;
private
type Printer is abstract limited new Printers.Printer with record
Param : Parameters;
Cursor : Screen_Column := 1;
Previous : Entity;
First : Boolean := True;
Indent_Level : Screen_Offset := 0;
Need_Blank : Boolean := False;
end record;
type Stream_Printer (Stream : access Ada.Streams.Root_Stream_Type'Class) is
new Printer with null record;
overriding procedure Write_Raw
(Output : in out Stream_Printer;
Data : in Ada.Streams.Stream_Element_Array);
end Natools.S_Expressions.Printers.Pretty;
|
make ancestry of Stream_Parser public
|
s_expressions-printers-pretty: make ancestry of Stream_Parser public
|
Ada
|
isc
|
faelys/natools
|
573a0a32aa8dc460d7fe97810ca9270034e32dc4
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with Util.Processes.Tools;
with ADO.Sessions;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Rollback;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
Result : int;
begin
Log.Info ("Close connection {0}", Database.Name);
if Database.Server /= null then
Result := Sqlite3_H.sqlite3_close_v2 (Database.Server);
if Result /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot close database {0}: {1}", To_String (Database.Name), Msg);
end;
end if;
Database.Server := null;
end if;
end Close;
-- ------------------------------
-- Releases the sqlite connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release database connection");
if Database.Server /= null then
Database.Close;
end if;
end Finalize;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
pragma Unreferenced (D);
use Strings;
Name : constant String := Config.Get_Database;
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased access Sqlite3;
Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Log.Info ("Opening database {0}", Name);
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot open SQLite database: {0}", Msg);
raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg;
end;
end if;
declare
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
ADO.Statements.Sqlite.Execute (Database.Server, SQL);
end if;
exception
when SQL_Error =>
null;
end Configure;
begin
Database.Server := Handle;
Database.Name := To_Unbounded_String (Config.Get_Database);
Result := Ref.Create (Database.all'Access);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Iterate (Process => Configure'Access);
end;
end Create_Connection;
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
-- ------------------------------
overriding
procedure Create_Database (D : in out Sqlite_Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is
pragma Unreferenced (D, Admin);
Status : Integer;
Database_Path : constant String := Config.Get_Database;
Command : constant String :=
"sqlite3 --batch --init " & Schema_Path & " " & Database_Path;
begin
Log.Info ("Creating SQLite database {0}", Database_Path);
Util.Processes.Tools.Execute (Command, Messages, Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Status = 255 then
Messages.Append ("Command not found: " & Command);
Log.Error ("Command not found: {0}", Command);
else
Messages.Append ("Command " & Command & " failed with exit code "
& Util.Strings.Image (Status));
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Status));
end if;
end Create_Database;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
end ADO.Drivers.Connections.Sqlite;
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with Util.Processes.Tools;
with ADO.Sessions;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Rollback;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
Log.Info ("Close connection {0}", Database.Name);
end Close;
-- ------------------------------
-- Releases the sqlite connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
Result : int;
begin
Log.Debug ("Release database connection");
if Database.Server /= null then
Result := Sqlite3_H.sqlite3_close_v2 (Database.Server);
if Result /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot close database {0}: {1}", To_String (Database.Name), Msg);
end;
end if;
Database.Server := null;
end if;
end Finalize;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
protected body Sqlite_Connections is
procedure Open (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
use Strings;
URI : constant String := Config.Get_URI;
Pos : Database_List.Cursor := Database_List.First (List);
C : Database_Connection_Access;
begin
-- Look first in the database list.
while Database_List.Has_Element (Pos) loop
C := Database_Connection'Class (Database_List.Element (Pos).Value.all)'Access;
if C.URI = URI then
Result := Ref.Ref'Class (Database_List.Element (Pos));
return;
end if;
Database_List.Next (Pos);
end loop;
-- Now we can open a new database connection.
declare
Name : constant String := Config.Get_Database;
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased access Sqlite3;
Flags : constant int
:= Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot open SQLite database: {0}", Msg);
raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg;
end;
end if;
declare
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
ADO.Statements.Sqlite.Execute (Database.Server, SQL);
end if;
exception
when SQL_Error =>
null;
end Configure;
begin
Database.Server := Handle;
Database.Name := To_Unbounded_String (Config.Get_Database);
Database.URI := To_Unbounded_String (URI);
Result := Ref.Create (Database.all'Access);
Database_List.Prepend (Container => List, New_Item => Ref.Ref (Result));
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Iterate (Process => Configure'Access);
end;
end;
end Open;
end Sqlite_Connections;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
begin
D.Map.Open (Config, Result);
end Create_Connection;
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
-- ------------------------------
overriding
procedure Create_Database (D : in out Sqlite_Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is
pragma Unreferenced (D, Admin);
Status : Integer;
Database_Path : constant String := Config.Get_Database;
Command : constant String :=
"sqlite3 --batch --init " & Schema_Path & " " & Database_Path;
begin
Log.Info ("Creating SQLite database {0}", Database_Path);
Util.Processes.Tools.Execute (Command, Messages, Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Status = 255 then
Messages.Append ("Command not found: " & Command);
Log.Error ("Command not found: {0}", Command);
else
Messages.Append ("Command " & Command & " failed with exit code "
& Util.Strings.Image (Status));
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Status));
end if;
end Create_Database;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the SQLite driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Sqlite_Driver) is
pragma Unreferenced (D);
begin
Log.Debug ("Deleting the sqlite driver");
end Finalize;
end ADO.Drivers.Connections.Sqlite;
|
Implement Sqlite_Connections protected type Implement Finalize on SQLite driver
|
Implement Sqlite_Connections protected type
Implement Finalize on SQLite driver
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
072f1254e096a3c47bff402c0c9d80eb7504b188
|
awa/regtests/awa_command.adb
|
awa/regtests/awa_command.adb
|
-----------------------------------------------------------------------
-- awa_command - Tests for AWA command
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands;
with Util.Tests;
with AWA.Commands.Drivers;
with AWA.Commands.List;
with AWA.Commands.Start;
with AWA.Commands.Stop;
with AWA.Commands.Info;
with Servlet.Server;
with ADO.Drivers;
with AWA.Testsuite;
with AWA_Test_App;
procedure AWA_Command is
package Server_Commands is
new AWA.Commands.Drivers (Driver_Name => "awa",
Container_Type => Servlet.Server.Container);
package List_Command is
new AWA.Commands.List (Server_Commands);
package Start_Command is
new AWA.Commands.Start (Server_Commands);
package Stop_Command is
new AWA.Commands.Stop (Server_Commands);
package Info_Command is
new AWA.Commands.Info (Server_Commands);
App : aliased AWA_Test_App.Application;
Context : AWA.Commands.Context_Type;
Arguments : Util.Commands.Dynamic_Argument_List;
Suite : Util.Tests.Access_Test_Suite := AWA.Testsuite.Suite;
pragma Unreferenced (Suite);
begin
ADO.Drivers.Initialize;
Server_Commands.WS.Register_Application ("/test", App'Unchecked_Access);
Server_Commands.Run (Context, Arguments);
exception
when E : others =>
AWA.Commands.Print (Context, E);
end AWA_Command;
|
-----------------------------------------------------------------------
-- awa_command - Tests for AWA command
-- Copyright (C) 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands;
with Util.Tests;
with AWA.Commands.Drivers;
with AWA.Commands.List;
with AWA.Commands.Start;
with AWA.Commands.Stop;
with AWA.Commands.Info;
with Servlet.Server;
with ADO.Drivers;
with AWA.Testsuite;
with AWA_Test_App;
procedure AWA_Command is
package Server_Commands is
new AWA.Commands.Drivers (Driver_Name => "awa",
Container_Type => Servlet.Server.Container);
package List_Command is
new AWA.Commands.List (Server_Commands);
package Start_Command is
new AWA.Commands.Start (Server_Commands);
package Stop_Command is
new AWA.Commands.Stop (Server_Commands);
package Info_Command is
new AWA.Commands.Info (Server_Commands);
pragma Unreferenced (List_Command, Start_Command, Stop_Command, Info_Command);
App : aliased AWA_Test_App.Application;
Context : AWA.Commands.Context_Type;
Arguments : Util.Commands.Dynamic_Argument_List;
Suite : Util.Tests.Access_Test_Suite := AWA.Testsuite.Suite;
pragma Unreferenced (Suite);
begin
ADO.Drivers.Initialize;
Server_Commands.WS.Register_Application ("/test", App'Unchecked_Access);
Server_Commands.Run (Context, Arguments);
exception
when E : others =>
AWA.Commands.Print (Context, E);
end AWA_Command;
|
Fix style warnings: add missing overriding and update and then/or else conditions
|
Fix style warnings: add missing overriding and update and then/or else conditions
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
37989f1ad9c1aad732af01a1281ec818ced65f9d
|
src/util-texts-builders.adb
|
src/util-texts-builders.adb
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- 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.Unchecked_Deallocation;
package body Util.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- 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)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : Block_Access := Source.First'Unrestricted_Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- 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.Unchecked_Deallocation;
package body Util.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- 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) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- 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)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : Block_Access := Source.First'Unrestricted_Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
Implement the Get generic procedure
|
Implement the Get generic procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
7e98527bb3746727da287590b54767961c947d8a
|
awa/plugins/awa-comments/src/awa-comments-beans.ads
|
awa/plugins/awa-comments/src/awa-comments-beans.ads
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Schemas;
with ADO.Sessions;
with ASF.Helpers.Beans;
with AWA.Comments.Models;
with AWA.Comments.Modules;
-- == Comment Beans ==
-- Several bean types are provided to represent and manage a list of tags.
-- The tag module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- === Comment_List_Bean ===
-- The <tt>Comment_List_Bean</tt> holds a list of comments and provides operations used by the
-- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component.
-- A bean can be declared and configured as follows in the XML application configuration file:
--
-- <managed-bean>
-- <managed-bean-name>postCommentList</managed-bean-name>
-- <managed-bean-class>AWA.Comments.Beans.Comment_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_post</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>blog-comment-post</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the comments
-- are assigned. The <tt>permission</tt> property defines the permission name that must be used
-- to verify that the user has the permission do add or remove the comment.
--
package AWA.Comments.Beans is
type Comment_Bean is new AWA.Comments.Models.Comment_Bean with record
Module : Modules.Comment_Module_Access := null;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Comment_Bean_Access is access all Comment_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the comment.
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Publish or not the comment.
overriding
procedure Publish (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the comment.
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create a new comment bean instance.
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Comment_List_Bean is
new AWA.Comments.Models.Comment_Info_List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Comments.Modules.Comment_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Entity_Id : ADO.Identifier;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
end record;
type Comment_List_Bean_Access is access all Comment_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) with which the comments are associated.
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a comment on the entity.
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String);
-- Load the comments associated with the given database identifier.
procedure Load_Comments (Into : in out Comment_List_Bean;
For_Entity_Id : in ADO.Identifier);
-- Load the comments associated with the given database identifier.
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in out ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Create the comment list bean instance.
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
function Get_Comment_Bean is
new ASF.Helpers.Beans.Get_Bean (Element_Type => Comment_Bean,
Element_Access => Comment_Bean_Access);
function Get_Comment_List_Bean is
new ASF.Helpers.Beans.Get_Bean (Element_Type => Comment_List_Bean,
Element_Access => Comment_List_Bean_Access);
end AWA.Comments.Beans;
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- 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 Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Schemas;
with ADO.Sessions;
with ASF.Helpers.Beans;
with AWA.Comments.Models;
with AWA.Comments.Modules;
-- == Comment Beans ==
-- Several bean types are provided to represent and manage a list of tags.
-- The tag module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- === Comment_List_Bean ===
-- The <tt>Comment_List_Bean</tt> holds a list of comments and provides operations used by the
-- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component.
-- A bean can be declared and configured as follows in the XML application configuration file:
--
-- <managed-bean>
-- <managed-bean-name>postCommentList</managed-bean-name>
-- <managed-bean-class>AWA.Comments.Beans.Comment_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_post</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>blog-comment-post</value>
-- </managed-property>
-- <managed-property>
-- <property-name>sort</property-name>
-- <property-class>String</property-class>
-- <value>oldest</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the comments
-- are assigned. The <tt>permission</tt> property defines the permission name that must be used
-- to verify that the user has the permission do add or remove the comment.
--
package AWA.Comments.Beans is
type Comment_Bean is new AWA.Comments.Models.Comment_Bean with record
Module : Modules.Comment_Module_Access := null;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Comment_Bean_Access is access all Comment_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the comment.
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Publish or not the comment.
overriding
procedure Publish (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the comment.
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create a new comment bean instance.
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Comment_List_Bean is
new AWA.Comments.Models.Comment_Info_List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Comments.Modules.Comment_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Entity_Id : ADO.Identifier;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
Oldest_First : Boolean := True;
end record;
type Comment_List_Bean_Access is access all Comment_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) with which the comments are associated.
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a comment on the entity.
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String);
-- Load the comments associated with the given database identifier.
procedure Load_Comments (Into : in out Comment_List_Bean;
For_Entity_Id : in ADO.Identifier);
-- Load the comments associated with the given database identifier.
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in out ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Create the comment list bean instance.
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
function Get_Comment_Bean is
new ASF.Helpers.Beans.Get_Bean (Element_Type => Comment_Bean,
Element_Access => Comment_Bean_Access);
function Get_Comment_List_Bean is
new ASF.Helpers.Beans.Get_Bean (Element_Type => Comment_List_Bean,
Element_Access => Comment_List_Bean_Access);
end AWA.Comments.Beans;
|
Add a Oldest_First member to the Comment_List_Bean to control the comment sort mode
|
Add a Oldest_First member to the Comment_List_Bean to control the comment sort mode
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
2dbf4da7c925abf8c53c4bf048a2bc0c832b2fec
|
matp/src/mat-targets.ads
|
matp/src/mat-targets.ads
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- 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 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;
with MAT.Expressions;
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;
-- The library search path.
Search_Path : Ada.Strings.Unbounded.Unbounded_String;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
type Target_Process_Type is new Ada.Finalization.Limited_Controlled
and MAT.Expressions.Resolver_Type with record
Pid : MAT.Types.Target_Process_Ref;
Endian : MAT.Readers.Endian_Type := MAT.Readers.LITTLE_ENDIAN;
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;
-- Release the target process instance.
overriding
procedure Finalize (Target : in out Target_Process_Type);
-- Find the region that matches the given name.
overriding
function Find_Region (Resolver : in Target_Process_Type;
Name : in String) return MAT.Memory.Region_Info;
-- Find the symbol in the symbol table and return the start and end address.
overriding
function Find_Symbol (Resolver : in Target_Process_Type;
Name : in String) return MAT.Memory.Region_Info;
-- Get the start time for the tick reference.
overriding
function Get_Start_Time (Resolver : in Target_Process_Type)
return MAT.Types.Target_Tick_Ref;
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));
-- Add a search path for the library and symbol loader.
procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type;
Path : in String);
-- 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;
-- Release the storage used by the target object.
overriding
procedure Finalize (Target : in out Target_Type);
end MAT.Targets;
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- 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 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.Frames.Targets;
with MAT.Readers;
with MAT.Readers.Streams;
with MAT.Readers.Streams.Sockets;
with MAT.Consoles;
with MAT.Expressions;
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;
-- The library search path.
Search_Path : Ada.Strings.Unbounded.Unbounded_String;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
type Target_Process_Type is new Ada.Finalization.Limited_Controlled
and MAT.Expressions.Resolver_Type with record
Pid : MAT.Types.Target_Process_Ref;
Endian : MAT.Readers.Endian_Type := MAT.Readers.LITTLE_ENDIAN;
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;
Frames : MAT.Frames.Targets.Target_Frames_Access;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
-- Release the target process instance.
overriding
procedure Finalize (Target : in out Target_Process_Type);
-- Find the region that matches the given name.
overriding
function Find_Region (Resolver : in Target_Process_Type;
Name : in String) return MAT.Memory.Region_Info;
-- Find the symbol in the symbol table and return the start and end address.
overriding
function Find_Symbol (Resolver : in Target_Process_Type;
Name : in String) return MAT.Memory.Region_Info;
-- Get the start time for the tick reference.
overriding
function Get_Start_Time (Resolver : in Target_Process_Type)
return MAT.Types.Target_Tick_Ref;
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));
-- Add a search path for the library and symbol loader.
procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type;
Path : in String);
-- 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;
-- Release the storage used by the target object.
overriding
procedure Finalize (Target : in out Target_Type);
end MAT.Targets;
|
Add the target frames in the Target_Process type
|
Add the target frames in the Target_Process type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
65d92c05c23d25ecd195ecc940a4b73c5344675b
|
examples/MicroBit/src/main.adb
|
examples/MicroBit/src/main.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with MicroBit.Display; use MicroBit.Display;
procedure Main is
begin
Initialize;
loop
for X in Coord loop
for Y in Coord loop
Set (X, Y);
for Cnt in 0 .. 100_000 loop
null;
end loop;
Clear (X, Y);
end loop;
end loop;
end loop;
end Main;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with MicroBit.Display; use MicroBit.Display;
with HAL; use HAL;
procedure Main is
Tmp : UInt24 with Unreferenced;
Str : constant String := "MAKE WITH ADA ";
begin
loop
for C of Str loop
Display (C);
for Cnt in 0 .. 200_000 loop
null;
end loop;
end loop;
end loop;
end Main;
|
Use the new display features in the example
|
MicroBit: Use the new display features in the example
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
e6e65a360a02028e0c16d8794e87ae667722c147
|
src/gen-commands-project.adb
|
src/gen-commands-project.adb
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
Gtk_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: ? -web -tool -ado -gtk") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
elsif Full_Switch = "-gtk" then
Gtk_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "gpl3" then
Generator.Set_Project_Property ("license", "gpl3");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag));
Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag));
Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag));
Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag));
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
if Ado_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado");
elsif Gtk_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk");
else
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
end if;
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
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 ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]"
& "[--ado] [--gtk] NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses");
Put_Line (" license, the GNU licenses or a proprietary license.");
Put_Line (" The author's name and email addresses are also reported in generated files.");
New_Line;
Put_Line (" --web Generate a Web application (the default)");
Put_Line (" --tool Generate a command line tool");
Put_Line (" --ado Generate a database tool operation for ADO");
Put_Line (" --gtk Generate a GtkAda project");
end Help;
end Gen.Commands.Project;
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
Gtk_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: ? -web -tool -ado -gtk") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
elsif Full_Switch = "-gtk" then
Gtk_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "gpl3" then
Generator.Set_Project_Property ("license", "gpl3");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag));
Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag));
Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag));
Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag));
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
if Ado_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado");
elsif Gtk_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk");
else
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
end if;
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]"
& "[--ado] [--gtk] NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses");
Put_Line (" license, the GNU licenses or a proprietary license.");
Put_Line (" The author's name and email addresses are also reported in generated files.");
New_Line;
Put_Line (" --web Generate a Web application (the default)");
Put_Line (" --tool Generate a command line tool");
Put_Line (" --ado Generate a database tool operation for ADO");
Put_Line (" --gtk Generate a GtkAda project");
end Help;
end Gen.Commands.Project;
|
Update to use the new command implementation
|
Update to use the new command implementation
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
8824b7e21b7839cfcb047e32c3f83e8fb4ceebc1
|
awa/plugins/awa-votes/src/awa-votes-modules.ads
|
awa/plugins/awa-votes/src/awa-votes-modules.ads
|
-----------------------------------------------------------------------
-- awa-votes-modules -- Module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with AWA.Modules;
-- == Integration ==
-- The <tt>Vote_Module</tt> manages the votes on entities. It provides operations that are
-- used by the vote beans or other services to vote for an item. An instance of the
-- the <tt>Vote_Module</tt> must be declared and registered in the AWA application.
-- The module instance can be defined as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Vote_Module : aliased AWA.Votes.Modules.Vote_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Votes.Modules.NAME,
-- URI => "votes",
-- Module => App.Vote_Module'Access);
package AWA.Votes.Modules is
-- The name under which the module is registered.
NAME : constant String := "votes";
-- ------------------------------
-- Module votes
-- ------------------------------
type Vote_Module is new AWA.Modules.Module with private;
type Vote_Module_Access is access all Vote_Module'Class;
-- Initialize the votes module.
overriding
procedure Initialize (Plugin : in out Vote_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the votes module.
function Get_Vote_Module return Vote_Module_Access;
-- Vote for the given element and return the total vote for that element.
procedure Vote_For (Model : in Vote_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Value : in Integer;
Total : out Integer);
private
type Vote_Module is new AWA.Modules.Module with null record;
end AWA.Votes.Modules;
|
-----------------------------------------------------------------------
-- awa-votes-modules -- Module votes
-- Copyright (C) 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with AWA.Modules;
-- == Integration ==
-- The <tt>Vote_Module</tt> manages the votes on entities. It provides operations that are
-- used by the vote beans or other services to vote for an item. An instance of the
-- <tt>Vote_Module</tt> must be declared and registered in the AWA application.
-- The module instance can be defined as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Vote_Module : aliased AWA.Votes.Modules.Vote_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Votes.Modules.NAME,
-- URI => "votes",
-- Module => App.Vote_Module'Access);
package AWA.Votes.Modules is
-- The name under which the module is registered.
NAME : constant String := "votes";
-- ------------------------------
-- Module votes
-- ------------------------------
type Vote_Module is new AWA.Modules.Module with private;
type Vote_Module_Access is access all Vote_Module'Class;
-- Initialize the votes module.
overriding
procedure Initialize (Plugin : in out Vote_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the votes module.
function Get_Vote_Module return Vote_Module_Access;
-- Vote for the given element and return the total vote for that element.
procedure Vote_For (Model : in Vote_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Value : in Integer;
Total : out Integer);
private
type Vote_Module is new AWA.Modules.Module with null record;
end AWA.Votes.Modules;
|
Fix some documentation typo
|
Fix some documentation typo
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e275339571c1b5b610a7c9eb6e61010f0b618372
|
regtests/util-streams-buffered-lzma-tests.adb
|
regtests/util-streams-buffered-lzma-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Lzma.Tests is
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write",
Test_Compress_Stream'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)",
Test_Compress_File_Stream'Access);
end Add_Tests;
procedure Test_Compress_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma");
begin
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_Stream;
procedure Test_Compress_File_Stream (T : in out Test) is
Stream : aliased File_Stream;
In_Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Path : constant String
:= Util.Tests.Get_Test_Path ("regtests/result/test-big-stream.lzma");
Expect : constant String
:= Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma");
begin
In_Stream.Open (Ada.Streams.Stream_IO.In_File,
Util.Tests.Get_Path ("regtests/files/test-big-stream.bin"));
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 32768,
Format => Util.Encoders.BASE_64);
Util.Streams.Copy (From => In_Stream, Into => Buffer);
Buffer.Flush;
Buffer.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_File_Stream;
end Util.Streams.Buffered.Lzma.Tests;
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Lzma.Tests is
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write",
Test_Compress_Stream'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)",
Test_Compress_File_Stream'Access);
end Add_Tests;
procedure Test_Compress_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma");
begin
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024);
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_Stream;
procedure Test_Compress_File_Stream (T : in out Test) is
Stream : aliased File_Stream;
In_Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Path : constant String
:= Util.Tests.Get_Test_Path ("regtests/result/test-big-stream.lzma");
Expect : constant String
:= Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma");
begin
In_Stream.Open (Ada.Streams.Stream_IO.In_File,
Util.Tests.Get_Path ("regtests/files/test-big-stream.bin"));
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 32768);
Util.Streams.Copy (From => In_Stream, Into => Buffer);
Buffer.Flush;
Buffer.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_File_Stream;
end Util.Streams.Buffered.Lzma.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
68d96ea1ba23dc7fa620c7c0fc7107155bd8a42a
|
regtests/util-streams-buffered-lzma-tests.adb
|
regtests/util-streams-buffered-lzma-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Lzma.Tests is
use Util.Tests;
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write",
Test_Compress_Stream'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)",
Test_Compress_File_Stream'Access);
end Add_Tests;
procedure Test_Compress_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma");
begin
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_Stream;
procedure Test_Compress_File_Stream (T : in out Test) is
Stream : aliased File_Stream;
In_Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-big-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma");
begin
In_Stream.Open (Ada.Streams.Stream_IO.In_File,
Util.Tests.Get_Path ("regtests/files/test-big-stream.bin"));
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 32768,
Format => Util.Encoders.BASE_64);
Util.Streams.Copy (From => In_Stream, Into => Buffer);
Buffer.Flush;
Buffer.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_File_Stream;
end Util.Streams.Buffered.Lzma.Tests;
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Lzma.Tests is
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write",
Test_Compress_Stream'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)",
Test_Compress_File_Stream'Access);
end Add_Tests;
procedure Test_Compress_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma");
begin
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_Stream;
procedure Test_Compress_File_Stream (T : in out Test) is
Stream : aliased File_Stream;
In_Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Path : constant String
:= Util.Tests.Get_Test_Path ("regtests/result/test-big-stream.lzma");
Expect : constant String
:= Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma");
begin
In_Stream.Open (Ada.Streams.Stream_IO.In_File,
Util.Tests.Get_Path ("regtests/files/test-big-stream.bin"));
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 32768,
Format => Util.Encoders.BASE_64);
Util.Streams.Copy (From => In_Stream, Into => Buffer);
Buffer.Flush;
Buffer.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_File_Stream;
end Util.Streams.Buffered.Lzma.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f7d5b92cf3fe18734fba30d12bbf2592867c8dd8
|
regtests/ado-queries-tests.adb
|
regtests/ado-queries-tests.adb
|
-----------------------------------------------------------------------
-- ado-queries-tests -- Test loading of database queries
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO.Queries.Loaders;
package body ADO.Queries.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "ADO.Queries");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query",
Test_Load_Queries'Access);
end Add_Tests;
package Simple_Query_File is
new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml",
Sha1 => "");
package Multi_Query_File is
new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml",
Sha1 => "");
package Simple_Query is
new ADO.Queries.Loaders.Query (Name => "simple-query",
File => Simple_Query_File.File'Access);
package Simple_Query_2 is
new ADO.Queries.Loaders.Query (Name => "simple-query",
File => Multi_Query_File.File'Access);
package Index_Query is
new ADO.Queries.Loaders.Query (Name => "index",
File => Multi_Query_File.File'Access);
package Value_Query is
new ADO.Queries.Loaders.Query (Name => "value",
File => Multi_Query_File.File'Access);
pragma Warnings (Off, Simple_Query_2);
pragma Warnings (Off, Value_Query);
procedure Test_Load_Queries (T : in out Test) is
use type ADO.Drivers.Driver_Access;
Mysql_Driver : constant ADO.Drivers.Driver_Access := ADO.Drivers.Get_Driver ("mysql");
Sqlite_Driver : constant ADO.Drivers.Driver_Access := ADO.Drivers.Get_Driver ("sqlite");
begin
declare
SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, 0);
begin
Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'");
end;
declare
SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 0);
begin
Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'");
end;
if Mysql_Driver /= null then
declare
SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 1);
begin
Assert_Equals (T, "select 1", SQL, "Invalid query for 'index'");
end;
end if;
end Test_Load_Queries;
end ADO.Queries.Tests;
|
-----------------------------------------------------------------------
-- ado-queries-tests -- Test loading of database queries
-- 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.Test_Caller;
with Util.Properties;
with ADO.Queries.Loaders;
package body ADO.Queries.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "ADO.Queries");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query",
Test_Load_Queries'Access);
end Add_Tests;
package Simple_Query_File is
new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml",
Sha1 => "");
package Multi_Query_File is
new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml",
Sha1 => "");
package Simple_Query is
new ADO.Queries.Loaders.Query (Name => "simple-query",
File => Simple_Query_File.File'Access);
package Simple_Query_2 is
new ADO.Queries.Loaders.Query (Name => "simple-query",
File => Multi_Query_File.File'Access);
package Index_Query is
new ADO.Queries.Loaders.Query (Name => "index",
File => Multi_Query_File.File'Access);
package Value_Query is
new ADO.Queries.Loaders.Query (Name => "value",
File => Multi_Query_File.File'Access);
pragma Warnings (Off, Simple_Query_2);
pragma Warnings (Off, Value_Query);
procedure Test_Load_Queries (T : in out Test) is
use type ADO.Drivers.Driver_Access;
Mysql_Driver : constant ADO.Drivers.Driver_Access := ADO.Drivers.Get_Driver ("mysql");
Sqlite_Driver : constant ADO.Drivers.Driver_Access := ADO.Drivers.Get_Driver ("sqlite");
Props : Util.Properties.Manager := Util.Tests.Get_Properties;
begin
-- Configure the XML query loader.
ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"),
Props.Get ("ado.queries.load", "false") = "true");
declare
SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, 0);
begin
Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'");
end;
declare
SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 0);
begin
Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'");
end;
if Mysql_Driver /= null then
declare
SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 1);
begin
Assert_Equals (T, "select 1", SQL, "Invalid query for 'index'");
end;
end if;
end Test_Load_Queries;
end ADO.Queries.Tests;
|
Initialize the query loaders before running the test
|
Initialize the query loaders before running the test
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
89712ac60ab9e7a84bf523bef45a23bfc4884bde
|
src/base/beans/util-beans-objects-vectors.adb
|
src/base/beans/util-beans-objects-vectors.adb
|
-----------------------------------------------------------------------
-- util-beans-vectors -- Object vectors
-- Copyright (C) 2011, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Vectors is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Vector_Bean;
Name : in String) return Object is
begin
if Name = "count" then
return To_Object (Natural (From.Length));
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Vector_Bean) return Natural is
begin
return Natural (From.Length);
end Get_Count;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
overriding
function Get_Row (From : in Vector_Bean;
Position : in Natural) return Util.Beans.Objects.Object is
begin
return From.Element (Position);
end Get_Row;
-- -----------------------
-- Create an object that contains a <tt>Vector_Bean</tt> instance.
-- -----------------------
function Create return Object is
M : constant Vector_Bean_Access := new Vector_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
end Util.Beans.Objects.Vectors;
|
-----------------------------------------------------------------------
-- util-beans-vectors -- Object vectors
-- Copyright (C) 2011, 2017, 2019, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Vectors is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Vector_Bean;
Name : in String) return Object is
begin
if Name = "count" then
return To_Object (Natural (From.Length));
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Vector_Bean) return Natural is
begin
return Natural (From.Length);
end Get_Count;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
overriding
function Get_Row (From : in Vector_Bean;
Position : in Natural) return Util.Beans.Objects.Object is
begin
return From.Element (Position);
end Get_Row;
-- -----------------------
-- Create an object that contains a <tt>Vector_Bean</tt> instance.
-- -----------------------
function Create return Object is
M : constant Vector_Bean_Access := new Vector_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
-- -----------------------
-- Iterate over the vectors or array elements.
-- If the object is not a `Vector_Bean` or an array, the operation does nothing.
-- -----------------------
procedure Iterate (From : in Object;
Process : not null access procedure (Item : in Object)) is
procedure Process_One (Pos : in Vectors.Cursor);
procedure Process_One (Pos : in Vectors.Cursor) is
begin
Process (Vectors.Element (Pos));
end Process_One;
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From);
begin
if Bean /= null and then Bean.all in Vector_Bean'Class then
Vector_Bean'Class (Bean.all).Iterate (Process_One'Access);
elsif Is_Array (From) then
declare
Count : constant Natural := Get_Count (From);
begin
for Pos in 1 .. Count loop
Process (Get_Value (From, Pos));
end loop;
end;
end if;
end Iterate;
end Util.Beans.Objects.Vectors;
|
Implement the Iterate procedure
|
Implement the Iterate procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
6c88277699e30ea35db487c1e5f2fa0330fdc139
|
matp/src/mat-expressions.adb
|
matp/src/mat-expressions.adb
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for event and memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with MAT.Expressions.Parser;
package body MAT.Expressions is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Node_Type,
Name => Node_Type_Access);
-- Destroy recursively the node, releasing the storage.
procedure Destroy (Node : in out Node_Type_Access);
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_INSIDE,
Name => Name,
Inside => Kind);
return Result;
end Create_Inside;
-- ------------------------------
-- Create an size range expression node.
-- ------------------------------
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_SIZE,
Min_Size => Min,
Max_Size => Max);
return Result;
end Create_Size;
-- ------------------------------
-- Create an addr range expression node.
-- ------------------------------
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_HAS_ADDR,
Min_Addr => Min,
Max_Addr => Max);
return Result;
end Create_Addr;
-- ------------------------------
-- Create an time range expression node.
-- ------------------------------
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_TIME,
Min_Time => Min,
Max_Time => Max);
return Result;
end Create_Time;
-- ------------------------------
-- Create a thread ID range expression node.
-- ------------------------------
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_THREAD,
Min_Thread => Min,
Max_Thread => Max);
return Result;
end Create_Thread;
-- ------------------------------
-- Create a event type expression check.
-- ------------------------------
function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type)
return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_TYPE,
Event_Kind => Event_Kind);
return Result;
end Create_Event_Type;
-- ------------------------------
-- Create an event ID range expression node.
-- ------------------------------
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_EVENT,
Min_Event => Min,
Max_Event => Max);
return Result;
end Create_Event;
-- ------------------------------
-- Create an expression node to keep allocation events which don't have any associated free.
-- ------------------------------
function Create_No_Free return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NO_FREE);
return Result;
end Create_No_Free;
-- ------------------------------
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Addr, Allocation);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
begin
return Is_Selected (Node.Node.all, Event);
end Is_Selected;
-- ------------------------------
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Addr, Allocation);
when N_AND =>
return Is_Selected (Node.Left.all, Addr, Allocation)
and then Is_Selected (Node.Right.all, Addr, Allocation);
when N_OR =>
return Is_Selected (Node.Left.all, Addr, Allocation)
or else Is_Selected (Node.Right.all, Addr, Allocation);
when N_RANGE_SIZE =>
return Allocation.Size >= Node.Min_Size
and Allocation.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Addr >= Node.Min_Addr
and Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Allocation.Time >= Node.Min_Time
and Allocation.Time <= Node.Max_Time;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
use type MAT.Types.Target_Thread_Ref;
use type MAT.Events.Targets.Event_Id_Type;
use type MAT.Events.Targets.Probe_Index_Type;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Event);
when N_AND =>
return Is_Selected (Node.Left.all, Event)
and then Is_Selected (Node.Right.all, Event);
when N_OR =>
return Is_Selected (Node.Left.all, Event)
or else Is_Selected (Node.Right.all, Event);
when N_RANGE_SIZE =>
return Event.Size >= Node.Min_Size
and Event.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Event.Addr >= Node.Min_Addr
and Event.Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Event.Time >= Node.Min_Time
and Event.Time <= Node.Max_Time;
when N_EVENT =>
return Event.Id >= Node.Min_Event
and Event.Id <= Node.Max_Event;
when N_THREAD =>
return Event.Thread >= Node.Min_Thread
and Event.Thread <= Node.Max_Thread;
when N_TYPE =>
return Event.Index = Node.Event_Kind;
when N_HAS_ADDR =>
if Event.Index = MAT.Events.Targets.MSG_MALLOC
or Event.Index = MAT.Events.Targets.MSG_REALLOC
then
return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr;
end if;
return False;
when N_NO_FREE =>
if Event.Index = MAT.Events.Targets.MSG_MALLOC
or Event.Index = MAT.Events.Targets.MSG_REALLOC
then
return Event.Next_Id = 0;
else
return False;
end if;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Parse the string and return the expression tree.
-- ------------------------------
function Parse (Expr : in String) return Expression_Type is
begin
return MAT.Expressions.Parser.Parse (Expr);
end Parse;
-- ------------------------------
-- Destroy recursively the node, releasing the storage.
-- ------------------------------
procedure Destroy (Node : in out Node_Type_Access) is
Release : Boolean;
begin
if Node /= null then
Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release);
if Release then
case Node.Kind is
when N_NOT =>
Destroy (Node.Expr);
when N_AND | N_OR =>
Destroy (Node.Left);
Destroy (Node.Right);
when others =>
null;
end case;
Free (Node);
else
Node := null;
end if;
end if;
end Destroy;
-- ------------------------------
-- Release the reference and destroy the expression tree if it was the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Destroy (Obj.Node);
end if;
end Finalize;
-- ------------------------------
-- Update the reference after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter);
end if;
end Adjust;
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for event and memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with MAT.Frames;
with MAT.Expressions.Parser;
package body MAT.Expressions is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Node_Type,
Name => Node_Type_Access);
-- Destroy recursively the node, releasing the storage.
procedure Destroy (Node : in out Node_Type_Access);
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_INSIDE,
Name => Name,
Inside => Kind);
return Result;
end Create_Inside;
-- ------------------------------
-- Create an size range expression node.
-- ------------------------------
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_SIZE,
Min_Size => Min,
Max_Size => Max);
return Result;
end Create_Size;
-- ------------------------------
-- Create an addr range expression node.
-- ------------------------------
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_HAS_ADDR,
Min_Addr => Min,
Max_Addr => Max);
return Result;
end Create_Addr;
-- ------------------------------
-- Create an time range expression node.
-- ------------------------------
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_TIME,
Min_Time => Min,
Max_Time => Max);
return Result;
end Create_Time;
-- ------------------------------
-- Create a thread ID range expression node.
-- ------------------------------
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_THREAD,
Min_Thread => Min,
Max_Thread => Max);
return Result;
end Create_Thread;
-- ------------------------------
-- Create a event type expression check.
-- ------------------------------
function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type)
return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_TYPE,
Event_Kind => Event_Kind);
return Result;
end Create_Event_Type;
-- ------------------------------
-- Create an event ID range expression node.
-- ------------------------------
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_EVENT,
Min_Event => Min,
Max_Event => Max);
return Result;
end Create_Event;
-- ------------------------------
-- Create an expression node to keep allocation events which don't have any associated free.
-- ------------------------------
function Create_No_Free return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NO_FREE);
return Result;
end Create_No_Free;
-- ------------------------------
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Addr, Allocation);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
begin
return Is_Selected (Node.Node.all, Event);
end Is_Selected;
-- ------------------------------
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Addr, Allocation);
when N_AND =>
return Is_Selected (Node.Left.all, Addr, Allocation)
and then Is_Selected (Node.Right.all, Addr, Allocation);
when N_OR =>
return Is_Selected (Node.Left.all, Addr, Allocation)
or else Is_Selected (Node.Right.all, Addr, Allocation);
when N_RANGE_SIZE =>
return Allocation.Size >= Node.Min_Size
and Allocation.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Addr >= Node.Min_Addr
and Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Allocation.Time >= Node.Min_Time
and Allocation.Time <= Node.Max_Time;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
use type MAT.Types.Target_Thread_Ref;
use type MAT.Events.Targets.Event_Id_Type;
use type MAT.Events.Targets.Probe_Index_Type;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Event);
when N_AND =>
return Is_Selected (Node.Left.all, Event)
and then Is_Selected (Node.Right.all, Event);
when N_OR =>
return Is_Selected (Node.Left.all, Event)
or else Is_Selected (Node.Right.all, Event);
when N_RANGE_SIZE =>
return Event.Size >= Node.Min_Size
and Event.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Event.Addr >= Node.Min_Addr
and Event.Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Event.Time >= Node.Min_Time
and Event.Time <= Node.Max_Time;
when N_EVENT =>
return Event.Id >= Node.Min_Event
and Event.Id <= Node.Max_Event;
when N_THREAD =>
return Event.Thread >= Node.Min_Thread
and Event.Thread <= Node.Max_Thread;
when N_TYPE =>
return Event.Index = Node.Event_Kind;
when N_HAS_ADDR =>
if Event.Index = MAT.Events.Targets.MSG_MALLOC
or Event.Index = MAT.Events.Targets.MSG_REALLOC
then
return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr;
end if;
return False;
when N_NO_FREE =>
if Event.Index = MAT.Events.Targets.MSG_MALLOC
or Event.Index = MAT.Events.Targets.MSG_REALLOC
then
return Event.Next_Id = 0;
else
return False;
end if;
when N_IN_FUNC =>
return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr);
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Parse the string and return the expression tree.
-- ------------------------------
function Parse (Expr : in String) return Expression_Type is
begin
return MAT.Expressions.Parser.Parse (Expr);
end Parse;
-- ------------------------------
-- Destroy recursively the node, releasing the storage.
-- ------------------------------
procedure Destroy (Node : in out Node_Type_Access) is
Release : Boolean;
begin
if Node /= null then
Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release);
if Release then
case Node.Kind is
when N_NOT =>
Destroy (Node.Expr);
when N_AND | N_OR =>
Destroy (Node.Left);
Destroy (Node.Right);
when others =>
null;
end case;
Free (Node);
else
Node := null;
end if;
end if;
end Destroy;
-- ------------------------------
-- Release the reference and destroy the expression tree if it was the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Destroy (Obj.Node);
end if;
end Finalize;
-- ------------------------------
-- Update the reference after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter);
end if;
end Adjust;
end MAT.Expressions;
|
Update Is_Selected to use the frames In_Function selector to check if a stack frame contains calls to a given function
|
Update Is_Selected to use the frames In_Function selector to check if
a stack frame contains calls to a given function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
31fc04ee690a4a160fd5e4bc72595b656d11224f
|
src/el-beans-methods-proc_1.adb
|
src/el-beans-methods-proc_1.adb
|
-----------------------------------------------------------------------
-- EL.Beans.Methods.Proc_1 -- Procedure Binding with 1 argument
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body EL.Beans.Methods.Proc_1 is
use EL.Expressions;
-- ------------------------------
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
-- ------------------------------
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in Param1_Type;
Context : in EL.Contexts.ELContext'Class) is
Info : constant Method_Info := Method.Get_Method_Info (Context);
begin
if Info.Binding = null then
raise EL.Expressions.Invalid_Method with "Method not found";
end if;
-- If the binding has the wrong type, we are trying to invoke
-- a method with a different signature.
if not (Info.Binding.all in Binding'Class) then
raise EL.Expressions.Invalid_Method
with "Invalid signature for method '" & Info.Binding.Name.all & "'";
end if;
declare
Proxy : constant Binding_Access := Binding (Info.Binding.all)'Access;
begin
Proxy.Method (Info.Object, Param);
end;
end Execute;
-- ------------------------------
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
-- ------------------------------
package body Bind is
procedure Method_Access (O : access EL.Beans.Readonly_Bean'Class;
P1 : Param1_Type) is
Object : access Bean := Bean (O.all)'Access;
begin
Method (Object.all, P1);
end Method_Access;
end Bind;
end EL.Beans.Methods.Proc_1;
|
-----------------------------------------------------------------------
-- EL.Beans.Methods.Proc_1 -- Procedure Binding with 1 argument
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body EL.Beans.Methods.Proc_1 is
use EL.Expressions;
-- ------------------------------
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
-- ------------------------------
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in Param1_Type;
Context : in EL.Contexts.ELContext'Class) is
Info : constant Method_Info := Method.Get_Method_Info (Context);
begin
if Info.Binding = null then
raise EL.Expressions.Invalid_Method with "Method not found";
end if;
-- If the binding has the wrong type, we are trying to invoke
-- a method with a different signature.
if not (Info.Binding.all in Binding'Class) then
raise EL.Expressions.Invalid_Method
with "Invalid signature for method '" & Info.Binding.Name.all & "'";
end if;
declare
Proxy : constant Binding_Access := Binding (Info.Binding.all)'Access;
begin
Proxy.Method (Info.Object, Param);
end;
end Execute;
-- ------------------------------
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
-- ------------------------------
package body Bind is
procedure Method_Access (O : access EL.Beans.Readonly_Bean'Class;
P1 : Param1_Type) is
Object : constant access Bean := Bean (O.all)'Access;
begin
Method (Object.all, P1);
end Method_Access;
end Bind;
end EL.Beans.Methods.Proc_1;
|
Fix indentation and compilation warning
|
Fix indentation and compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
f7711765b37e6637141da702bf4b8f02a808b127
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with ADO.Sessions;
with Ada.Calendar;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Blog);
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
-- ------------------------------
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with ADO.Sessions;
with Ada.Calendar;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Blog);
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
-- ------------------------------
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
end AWA.Blogs.Modules;
|
Save the allow comment flag on the post
|
Save the allow comment flag on the post
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6b0c6b59f2a84cb4608e83df6ee339dc5d727638
|
src/ado-sessions-factory.adb
|
src/ado-sessions-factory.adb
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sequences.Hilo;
package body ADO.Sessions.Factory is
-- ------------------------------
-- Open a session
-- ------------------------------
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session) is
S : constant Session_Record_Access := new Session_Record;
begin
Factory.Source.Create_Connection (S.Database);
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
Database.Impl := S;
end Open_Session;
-- ------------------------------
-- Get a read-only session from the factory.
-- ------------------------------
function Get_Session (Factory : in Session_Factory) return Session is
R : Session;
S : constant Session_Record_Access := new Session_Record;
begin
Factory.Source.Create_Connection (S.Database);
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
R.Impl := S;
return R;
end Get_Session;
-- ------------------------------
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
-- ------------------------------
function Get_Session (Proxy : in Session_Record_Access) return Session is
R : Session;
begin
if Proxy = null then
raise ADO.Objects.SESSION_EXPIRED;
end if;
R.Impl := Proxy;
Util.Concurrent.Counters.Increment (R.Impl.Counter);
return R;
end Get_Session;
-- ------------------------------
-- Get a read-write session from the factory.
-- ------------------------------
function Get_Master_Session (Factory : in Session_Factory) return Master_Session is
R : Master_Session;
S : constant Session_Record_Access := new Session_Record;
begin
R.Impl := S;
R.Sequences := Factory.Sequences;
Factory.Source.Create_Connection (S.Database);
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
return R;
end Get_Master_Session;
-- ------------------------------
-- Open a session
-- ------------------------------
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session) is
begin
null;
end Open_Session;
-- ------------------------------
-- Initialize the sequence factory associated with the session factory.
-- ------------------------------
procedure Initialize_Sequences (Factory : in out Session_Factory) is
use ADO.Sequences;
begin
Factory.Sequences := Factory.Seq_Factory'Unchecked_Access;
Set_Default_Generator (Factory.Seq_Factory,
ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unchecked_Access);
end Initialize_Sequences;
-- ------------------------------
-- Create the session factory to connect to the database represented
-- by the data source.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
Source : in ADO.Sessions.Sources.Data_Source) is
begin
Factory.Source := Source;
Factory.Entities := new ADO.Schemas.Entities.Entity_Cache;
Factory.Cache_Values := Factory.Cache'Unchecked_Access;
Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access);
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entities.all, S);
end;
end if;
end Create;
-- ------------------------------
-- Create the session factory to connect to the database identified
-- by the URI.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
URI : in String) is
begin
Factory.Source.Set_Connection (URI);
Factory.Entities := new ADO.Schemas.Entities.Entity_Cache;
Factory.Cache_Values := Factory.Cache'Unchecked_Access;
Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access);
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entities.all, S);
end;
end if;
end Create;
end ADO.Sessions.Factory;
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sequences.Hilo;
with ADO.Schemas.Entities;
package body ADO.Sessions.Factory is
-- ------------------------------
-- Open a session
-- ------------------------------
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session) is
S : constant Session_Record_Access := new Session_Record;
begin
Factory.Source.Create_Connection (S.Database);
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
Database.Impl := S;
end Open_Session;
-- ------------------------------
-- Get a read-only session from the factory.
-- ------------------------------
function Get_Session (Factory : in Session_Factory) return Session is
R : Session;
S : constant Session_Record_Access := new Session_Record;
begin
Factory.Source.Create_Connection (S.Database);
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
R.Impl := S;
return R;
end Get_Session;
-- ------------------------------
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
-- ------------------------------
function Get_Session (Proxy : in Session_Record_Access) return Session is
R : Session;
begin
if Proxy = null then
raise ADO.Objects.SESSION_EXPIRED;
end if;
R.Impl := Proxy;
Util.Concurrent.Counters.Increment (R.Impl.Counter);
return R;
end Get_Session;
-- ------------------------------
-- Get a read-write session from the factory.
-- ------------------------------
function Get_Master_Session (Factory : in Session_Factory) return Master_Session is
R : Master_Session;
S : constant Session_Record_Access := new Session_Record;
begin
R.Impl := S;
R.Sequences := Factory.Sequences;
Factory.Source.Create_Connection (S.Database);
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
return R;
end Get_Master_Session;
-- ------------------------------
-- Open a session
-- ------------------------------
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session) is
begin
null;
end Open_Session;
-- ------------------------------
-- Initialize the sequence factory associated with the session factory.
-- ------------------------------
procedure Initialize_Sequences (Factory : in out Session_Factory) is
use ADO.Sequences;
begin
Factory.Sequences := Factory.Seq_Factory'Unchecked_Access;
Set_Default_Generator (Factory.Seq_Factory,
ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unchecked_Access);
end Initialize_Sequences;
-- ------------------------------
-- Create the session factory to connect to the database represented
-- by the data source.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
Source : in ADO.Sessions.Sources.Data_Source) is
begin
Factory.Source := Source;
Factory.Entities := new ADO.Schemas.Entities.Entity_Cache;
Factory.Cache_Values := Factory.Cache'Unchecked_Access;
Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access);
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entities.all, S);
end;
end if;
end Create;
-- ------------------------------
-- Create the session factory to connect to the database identified
-- by the URI.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
URI : in String) is
begin
Factory.Source.Set_Connection (URI);
Factory.Entities := new ADO.Schemas.Entities.Entity_Cache;
Factory.Cache_Values := Factory.Cache'Unchecked_Access;
Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access);
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entities.all, S);
end;
end if;
end Create;
end ADO.Sessions.Factory;
|
Fix compilation warning detected by GNAT 2017
|
Fix compilation warning detected by GNAT 2017
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
69ce936b9613e4d4e3d000628a38fdeb87495b32
|
src/orka/interface/orka-rendering-programs.ads
|
src/orka/interface/orka-rendering-programs.ads
|
-- Copyright (c) 2016 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.Containers.Indefinite_Holders;
with GL.Objects.Programs;
with GL.Objects.Shaders;
with GL.Types;
limited with Orka.Rendering.Programs.Modules;
limited with Orka.Rendering.Programs.Uniforms;
package Orka.Rendering.Programs is
pragma Preelaborate;
subtype Uniform_Location is GL.Objects.Programs.Uniform_Location_Type;
subtype Subroutine_Index is GL.Objects.Programs.Subroutine_Index_Type;
type Program is tagged private;
function Create_Program (Module : Programs.Modules.Module;
Separable : Boolean := False) return Program;
function Create_Program (Modules : Programs.Modules.Module_Array;
Separable : Boolean := False) return Program;
function GL_Program (Object : Program) return GL.Objects.Programs.Program
with Inline;
function Has_Subroutines (Object : Program) return Boolean;
procedure Use_Subroutines (Object : in out Program)
with Pre => Object.Has_Subroutines;
-- Use the selected subroutines in the current program
--
-- This procedure only needs to be called if a different
-- subroutine function has been selected _after_ Use_Program
-- was called. If you select the subroutine functions before
-- calling Use_Program, then Use_Subroutines will be called
-- automatically.
procedure Use_Program (Object : in out Program);
-- Use the program during rendering
--
-- If one or more shader stages have subroutines, then these are
-- used as well (that is, Use_Subroutines is called automatically).
function Attribute_Location
(Object : Program;
Name : String) return GL.Types.Attribute;
function Uniform_Sampler (Object : Program; Name : String) return Uniforms.Uniform_Sampler;
-- Return the uniform sampler that has the given name
--
-- Name must be a GLSL uniform sampler. A Uniforms.Uniform_Inactive_Error
-- exception is raised if the name is not defined in any of the attached shaders.
function Uniform_Image (Object : Program; Name : String) return Uniforms.Uniform_Image;
-- Return the uniform image that has the given name
--
-- Name must be a GLSL uniform image.
function Uniform_Subroutine
(Object : in out Program;
Shader : GL.Objects.Shaders.Shader_Type;
Name : String) return Uniforms.Uniform_Subroutine;
-- Return the uniform subroutine that has the given name
--
-- Name must be a GLSL uniform subroutine. A Uniforms.Uniform_Inactive_Error
-- exception is raised if the name is not defined in any of the attached
-- shaders.
function Uniform_Block (Object : Program; Name : String) return Uniforms.Uniform_Block;
-- Return the uniform block that has the given name
--
-- Name must be a GLSL uniform block. A Uniforms.Uniform_Inactive_Error
-- exception is raised if the name is not defined in any of the attached
-- shaders.
function Uniform (Object : Program; Name : String) return Uniforms.Uniform;
-- Return the uniform that has the given name
--
-- Name must be a GLSL uniform. A Uniforms.Uniform_Inactive_Error exception
-- is raised if the name is not defined in any of the attached shaders.
Program_Link_Error : exception;
private
package Subroutines_Holder is new Ada.Containers.Indefinite_Holders
(Element_Type => GL.Types.UInt_Array,
"=" => GL.Types."=");
type Subroutines_Array is array (GL.Objects.Shaders.Shader_Type) of Subroutines_Holder.Holder;
type Stages_Array is array (GL.Objects.Shaders.Shader_Type) of Boolean;
type Program is tagged record
GL_Program : GL.Objects.Programs.Program;
Subroutines : Subroutines_Array;
Stages : Stages_Array;
Has_Subroutines : Boolean := False;
Subroutines_Modified : Boolean := False;
end record;
procedure Set_Subroutine_Function
(Object : in out Program;
Shader : GL.Objects.Shaders.Shader_Type;
Location : Uniform_Location;
Index : Subroutine_Index)
with Pre => Object.Has_Subroutines and then not Object.Subroutines (Shader).Is_Empty;
end Orka.Rendering.Programs;
|
-- Copyright (c) 2016 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.Containers.Indefinite_Holders;
with GL.Objects.Programs;
with GL.Objects.Shaders;
with GL.Types;
limited with Orka.Rendering.Programs.Modules;
limited with Orka.Rendering.Programs.Uniforms;
package Orka.Rendering.Programs is
pragma Preelaborate;
subtype Uniform_Location is GL.Objects.Programs.Uniform_Location_Type;
subtype Subroutine_Index is GL.Objects.Programs.Subroutine_Index_Type;
type Program is tagged private;
function Create_Program (Module : Programs.Modules.Module;
Separable : Boolean := False) return Program;
function Create_Program (Modules : Programs.Modules.Module_Array;
Separable : Boolean := False) return Program;
function GL_Program (Object : Program) return GL.Objects.Programs.Program
with Inline;
function Has_Subroutines (Object : Program) return Boolean;
procedure Use_Subroutines (Object : in out Program)
with Pre => Object.Has_Subroutines;
-- Use the selected subroutines in the current program
--
-- This procedure only needs to be called if a different
-- subroutine function has been selected _after_ Use_Program
-- was called. If you select the subroutine functions before
-- calling Use_Program, then Use_Subroutines will be called
-- automatically.
procedure Use_Program (Object : in out Program);
-- Use the program during rendering
--
-- If one or more shader stages have subroutines, then these are
-- used as well (that is, Use_Subroutines is called automatically).
function Attribute_Location
(Object : Program;
Name : String) return GL.Types.Attribute;
function Uniform_Sampler (Object : Program; Name : String) return Uniforms.Uniform_Sampler;
-- Return the uniform sampler that has the given name
--
-- Name must be a GLSL uniform sampler. A Uniforms.Uniform_Inactive_Error
-- exception is raised if the name is not defined in any of the attached shaders.
function Uniform_Image (Object : Program; Name : String) return Uniforms.Uniform_Image;
-- Return the uniform image that has the given name
--
-- Name must be a GLSL uniform image.
function Uniform_Subroutine
(Object : in out Program;
Shader : GL.Objects.Shaders.Shader_Type;
Name : String) return Uniforms.Uniform_Subroutine;
-- Return the uniform subroutine that has the given name
--
-- Name must be a GLSL uniform subroutine. A Uniforms.Uniform_Inactive_Error
-- exception is raised if the name is not defined in any of the attached
-- shaders.
function Uniform_Block (Object : Program; Name : String) return Uniforms.Uniform_Block;
-- Return the uniform block that has the given name
--
-- Name must be a GLSL uniform block. A Uniforms.Uniform_Inactive_Error
-- exception is raised if the name is not defined in any of the attached
-- shaders.
function Uniform (Object : Program; Name : String) return Uniforms.Uniform;
-- Return the uniform that has the given name
--
-- Name must be a GLSL uniform. A Uniforms.Uniform_Inactive_Error exception
-- is raised if the name is not defined in any of the attached shaders.
Program_Link_Error : exception;
private
package Subroutines_Holder is new Ada.Containers.Indefinite_Holders
(Element_Type => GL.Types.UInt_Array,
"=" => GL.Types."=");
type Subroutines_Array is array (GL.Objects.Shaders.Shader_Type) of Subroutines_Holder.Holder;
type Stages_Array is array (GL.Objects.Shaders.Shader_Type) of Boolean;
type Program is tagged record
GL_Program : GL.Objects.Programs.Program;
Subroutines : Subroutines_Array;
Stages : Stages_Array := (others => False);
Has_Subroutines : Boolean := False;
Subroutines_Modified : Boolean := False;
end record;
procedure Set_Subroutine_Function
(Object : in out Program;
Shader : GL.Objects.Shaders.Shader_Type;
Location : Uniform_Location;
Index : Subroutine_Index)
with Pre => Object.Has_Subroutines and then not Object.Subroutines (Shader).Is_Empty;
end Orka.Rendering.Programs;
|
Fix reading subroutine locations of stages conditionally
|
orka: Fix reading subroutine locations of stages conditionally
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
d5b15e6e5da12c05883f4cbc2773a011b3c9b05e
|
src/babel-streams-files.adb
|
src/babel-streams-files.adb
|
-----------------------------------------------------------------------
-- babel-streams-files -- Local file stream 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 Interfaces.C.Strings;
with Ada.Streams;
with Util.Systems.Os;
with Util.Systems.Constants;
package body Babel.Streams.Files is
use type Interfaces.C.int;
-- ------------------------------
-- Open the local file for reading and use the given buffer for the Read operation.
-- ------------------------------
procedure Open (Stream : in out Stream_Type;
Path : in String;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Fd : Util.Systems.Os.File_Type;
begin
Fd := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_RDONLY,
Mode => 0);
Interfaces.C.Strings.Free (Name);
Stream.Buffer := Buffer;
Stream.File.Initialize (File => Fd);
end Open;
-- ------------------------------
-- Create a file and prepare for the Write operation.
-- ------------------------------
procedure Create (Stream : in out Stream_Type;
Path : in String;
Mode : in Util.Systems.Types.mode_t) is
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Fd : Util.Systems.Os.File_Type;
begin
Fd := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_WRONLY
+ Util.Systems.Constants.O_CREAT
+ Util.Systems.Constants.O_TRUNC,
Mode => Interfaces.C.int (Mode));
Interfaces.C.Strings.Free (Name);
Stream.Buffer := null;
Stream.File.Initialize (File => Fd);
end Create;
-- ------------------------------
-- Read the data stream as much as possible and return the result in a buffer.
-- The buffer is owned by the stream and need not be released. The same buffer may
-- or may not be returned by the next <tt>Read</tt> operation.
-- A null buffer is returned when the end of the data stream is reached.
-- ------------------------------
overriding
procedure Read (Stream : in out Stream_Type;
Buffer : out Babel.Files.Buffers.Buffer_Access) is
use type Ada.Streams.Stream_Element_Offset;
begin
if Stream.Eof then
Buffer := null;
else
Stream.File.Read (Stream.Buffer.Data, Stream.Buffer.Last);
if Stream.Buffer.Last < Stream.Buffer.Data'First then
Buffer := null;
else
Buffer := Stream.Buffer;
end if;
Stream.Eof := Stream.Buffer.Last < Stream.Buffer.Data'Last;
end if;
end Read;
-- ------------------------------
-- Write the buffer in the data stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Stream_Type;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
begin
Stream.File.Write (Buffer.Data (Buffer.Data'First .. Buffer.Last));
end Write;
-- ------------------------------
-- Close the data stream.
-- ------------------------------
overriding
procedure Close (Stream : in out Stream_Type) is
begin
Stream.File.Close;
end Close;
-- ------------------------------
-- Prepare to read again the data stream from the beginning.
-- ------------------------------
overriding
procedure Rewind (Stream : in out Stream_Type) is
begin
null;
end Rewind;
end Babel.Streams.Files;
|
-----------------------------------------------------------------------
-- babel-streams-files -- Local file stream management
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with Ada.Streams;
with Ada.IO_Exceptions;
with Util.Systems.Os;
with Util.Systems.Constants;
package body Babel.Streams.Files is
use type Interfaces.C.int;
-- ------------------------------
-- Open the local file for reading and use the given buffer for the Read operation.
-- ------------------------------
procedure Open (Stream : in out Stream_Type;
Path : in String;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Fd : Util.Systems.Os.File_Type;
begin
Fd := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_RDONLY,
Mode => 0);
Interfaces.C.Strings.Free (Name);
Stream.Buffer := Buffer;
Stream.File.Initialize (File => Fd);
end Open;
-- ------------------------------
-- Create a file and prepare for the Write operation.
-- ------------------------------
procedure Create (Stream : in out Stream_Type;
Path : in String;
Mode : in Util.Systems.Types.mode_t) is
use type Util.Systems.Os.File_Type;
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Fd : Util.Systems.Os.File_Type;
begin
Fd := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_WRONLY
+ Util.Systems.Constants.O_CREAT
+ Util.Systems.Constants.O_TRUNC,
Mode => Interfaces.C.int (Mode));
Interfaces.C.Strings.Free (Name);
Stream.Buffer := null;
Stream.File.Initialize (File => Fd);
if Fd < 0 then
raise Ada.IO_Exceptions.Name_Error with "Cannot create '" & Path & "'";
end if;
end Create;
-- ------------------------------
-- Read the data stream as much as possible and return the result in a buffer.
-- The buffer is owned by the stream and need not be released. The same buffer may
-- or may not be returned by the next <tt>Read</tt> operation.
-- A null buffer is returned when the end of the data stream is reached.
-- ------------------------------
overriding
procedure Read (Stream : in out Stream_Type;
Buffer : out Babel.Files.Buffers.Buffer_Access) is
use type Ada.Streams.Stream_Element_Offset;
begin
if Stream.Eof then
Buffer := null;
else
Stream.File.Read (Stream.Buffer.Data, Stream.Buffer.Last);
if Stream.Buffer.Last < Stream.Buffer.Data'First then
Buffer := null;
else
Buffer := Stream.Buffer;
end if;
Stream.Eof := Stream.Buffer.Last < Stream.Buffer.Data'Last;
end if;
end Read;
-- ------------------------------
-- Write the buffer in the data stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Stream_Type;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
begin
Stream.File.Write (Buffer.Data (Buffer.Data'First .. Buffer.Last));
end Write;
-- ------------------------------
-- Close the data stream.
-- ------------------------------
overriding
procedure Close (Stream : in out Stream_Type) is
begin
Stream.File.Close;
end Close;
-- ------------------------------
-- Prepare to read again the data stream from the beginning.
-- ------------------------------
overriding
procedure Rewind (Stream : in out Stream_Type) is
begin
Stream.File.Seek (0, Util.Systems.Types.SEEK_SET);
Stream.Eof := False;
end Rewind;
end Babel.Streams.Files;
|
Raise an exception if the file cannot be created Implement the Rewind procedure
|
Raise an exception if the file cannot be created
Implement the Rewind procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
63ea07330556c6640756074a5c0a0f45cd0af067
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- 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.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST);
type Init_Map is array (Init_Flag) of Boolean;
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- 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.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_TAG_ATTR : constant String := "tags";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST);
type Init_Map is array (Init_Flag) of Boolean;
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
end AWA.Blogs.Beans;
|
Add a list of tags to the post
|
Add a list of tags to the post
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
2c3900320cb323aa613e475216de90adf4637c1e
|
awa/plugins/awa-mail/src/awa-mail-modules.adb
|
awa/plugins/awa-mail/src/awa-mail-modules.adb
|
-----------------------------------------------------------------------
-- awa-mail -- Mail module
-- Copyright (C) 2011, 2012, 2015, 2017, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Mail.Beans;
with AWA.Mail.Components.Factory;
with AWA.Applications;
with Security;
with Servlet.Core;
with Servlet.Sessions;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Log.Loggers;
package body AWA.Mail.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Module");
package Register is new AWA.Modules.Beans (Module => Mail_Module,
Module_Access => Mail_Module_Access);
type Mail_Principal is new Security.Principal with null record;
-- Get the principal name.
overriding
function Get_Name (From : in Mail_Principal) return String;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
overriding
function Get_Name (From : in Mail_Principal) return String is
pragma Unreferenced (From);
begin
return "AWA Mailer";
end Get_Name;
-- ------------------------------
-- Initialize the mail module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Mail_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the mail module");
-- Add the Mail UI components.
App.Add_Components (AWA.Mail.Components.Factory.Definition);
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Mail.Beans.Mail_Bean",
Handler => AWA.Mail.Beans.Create_Mail_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Mail_Module;
Props : in ASF.Applications.Config) is
Mailer : constant String := Props.Get ("mailer", "smtp");
begin
Log.Info ("Mail plugin is using {0} mailer", Mailer);
Plugin.Mailer := AWA.Mail.Clients.Factory (Mailer, Props);
end Configure;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
function Create_Message (Plugin : in Mail_Module)
return AWA.Mail.Clients.Mail_Message_Access is
begin
return Plugin.Mailer.Create_Message;
end Create_Message;
-- ------------------------------
-- Receive an event sent by another module with <b>Send_Event</b> method.
-- Format and send an email.
-- ------------------------------
procedure Send_Mail (Plugin : in Mail_Module;
Template : in String;
Props : in Util.Beans.Objects.Maps.Map;
Content : in AWA.Events.Module_Event'Class) is
Name : constant String := Content.Get_Parameter ("name");
Locale : constant String := Content.Get_Parameter ("locale");
App : constant AWA.Modules.Application_Access := Plugin.Get_Application;
begin
Log.Info ("Receive event {0} with template {1}", Name, Template);
if Template = "" then
Log.Debug ("No email template associated with event {0}", Name);
return;
end if;
declare
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Session : Servlet.Sessions.Session;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := Content'Unrestricted_Access;
Bean : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC);
Dispatcher : constant Servlet.Core.Request_Dispatcher
:= App.Get_Request_Dispatcher (Template);
begin
App.Create_Session (Session);
Session.Set_Principal (new Mail_Principal);
Req.Set_Session (Session);
Req.Set_Request_URI (Template);
Req.Set_Method ("GET");
Req.Set_Attribute (Name => "event", Value => Bean);
Req.Set_Attributes (Props);
if Locale'Length > 0 then
Req.Set_Header ("Accept-Language", Locale);
end if;
Servlet.Core.Forward (Dispatcher, Req, Reply);
App.Delete_Session (Session);
end;
end Send_Mail;
-- ------------------------------
-- Get the mail module instance associated with the current application.
-- ------------------------------
function Get_Mail_Module return Mail_Module_Access is
function Get is new AWA.Modules.Get (Mail_Module, Mail_Module_Access, NAME);
begin
return Get;
end Get_Mail_Module;
end AWA.Mail.Modules;
|
-----------------------------------------------------------------------
-- awa-mail -- Mail module
-- Copyright (C) 2011, 2012, 2015, 2017, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Mail.Beans;
with AWA.Mail.Components.Factory;
with AWA.Applications;
with Security;
with Servlet.Core;
with Servlet.Sessions;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Log.Loggers;
package body AWA.Mail.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Module");
package Register is new AWA.Modules.Beans (Module => Mail_Module,
Module_Access => Mail_Module_Access);
type Mail_Principal is new Security.Principal with null record;
-- Get the principal name.
overriding
function Get_Name (From : in Mail_Principal) return String;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
overriding
function Get_Name (From : in Mail_Principal) return String is
pragma Unreferenced (From);
begin
return "AWA Mailer";
end Get_Name;
-- ------------------------------
-- Initialize the mail module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Mail_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the mail module");
-- Add the Mail UI components.
App.Add_Components (AWA.Mail.Components.Factory.Definition);
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Mail.Beans.Mail_Bean",
Handler => AWA.Mail.Beans.Create_Mail_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Mail_Module;
Props : in ASF.Applications.Config) is
Mailer : constant String := Props.Get ("mailer", "smtp");
begin
Log.Info ("Mail plugin is using {0} mailer", Mailer);
Plugin.Mailer := AWA.Mail.Clients.Factory (Mailer, Props);
end Configure;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
function Create_Message (Plugin : in Mail_Module)
return AWA.Mail.Clients.Mail_Message_Access is
begin
return Plugin.Mailer.Create_Message;
end Create_Message;
-- ------------------------------
-- Receive an event sent by another module with <b>Send_Event</b> method.
-- Format and send an email.
-- ------------------------------
procedure Send_Mail (Plugin : in Mail_Module;
Template : in String;
Props : in Util.Beans.Objects.Maps.Map;
Params : in Util.Beans.Objects.Maps.Map;
Content : in AWA.Events.Module_Event'Class) is
Name : constant String := Content.Get_Parameter ("name");
Locale : constant String := Content.Get_Parameter ("locale");
App : constant AWA.Modules.Application_Access := Plugin.Get_Application;
begin
Log.Info ("Receive event {0} with template {1}", Name, Template);
if Template = "" then
Log.Debug ("No email template associated with event {0}", Name);
return;
end if;
declare
use Util.Beans.Objects;
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Session : Servlet.Sessions.Session;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := Content'Unrestricted_Access;
Bean : constant Object := To_Object (Ptr, STATIC);
Dispatcher : constant Servlet.Core.Request_Dispatcher
:= App.Get_Request_Dispatcher (Template);
Iter : Maps.Cursor := Params.First;
begin
App.Create_Session (Session);
Session.Set_Principal (new Mail_Principal);
Req.Set_Session (Session);
Req.Set_Request_URI (Template);
Req.Set_Method ("GET");
Req.Set_Attribute (Name => "event", Value => Bean);
Req.Set_Attributes (Props);
if Locale'Length > 0 then
Req.Set_Header ("Accept-Language", Locale);
end if;
-- Setup the request parameters.
while Maps.Has_Element (Iter) loop
Req.Set_Parameter (Maps.Key (Iter), To_String (Maps.Element (Iter)));
Maps.Next (Iter);
end loop;
Servlet.Core.Forward (Dispatcher, Req, Reply);
App.Delete_Session (Session);
end;
end Send_Mail;
-- ------------------------------
-- Get the mail module instance associated with the current application.
-- ------------------------------
function Get_Mail_Module return Mail_Module_Access is
function Get is new AWA.Modules.Get (Mail_Module, Mail_Module_Access, NAME);
begin
return Get;
end Get_Mail_Module;
end AWA.Mail.Modules;
|
Update Send_Mail to setup some request parameters by using the new Params parameter
|
Update Send_Mail to setup some request parameters by using the new Params parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7f6f8c6c120f439f0e5a3b4dfcb9bd294bbb5059
|
awa/plugins/awa-wikis/src/awa-wikis-servlets.adb
|
awa/plugins/awa-wikis/src/awa-wikis-servlets.adb
|
-----------------------------------------------------------------------
-- awa-wikis-servlets -- Serve files saved in the storage service
-- 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.Strings.Unbounded;
with Ada.Calendar;
with Util.Log.Loggers;
with ADO.Objects;
with ASF.Streams;
with AWA.Wikis.Modules;
package body AWA.Wikis.Servlets is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Servlets");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
overriding
procedure Initialize (Server : in out Image_Servlet;
Context : in ASF.Servlets.Servlet_Registry'Class) is
begin
null;
end Initialize;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
overriding
procedure Do_Get (Server : in Image_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (Server);
Data : ADO.Blob_Ref;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
Module : constant AWA.Wikis.Modules.Wiki_Module_Access := Wikis.Modules.Get_Wiki_Module;
Wiki : constant String := Request.Get_Path_Parameter (1);
File : constant String := Request.Get_Path_Parameter (2);
Name : constant String := Request.Get_Path_Parameter (3);
Wiki_Id : ADO.Identifier;
File_Id : ADO.Identifier;
begin
Wiki_Id := ADO.Identifier'Value (Wiki);
File_Id := ADO.Identifier'Value (File);
Log.Info ("GET storage file {0}/{1}/{2}", Wiki, File, Name);
Module.Load_Image (Wiki_Id => Wiki_Id,
Image_Id => File_Id,
Mime => Mime,
Date => Date,
Into => Data);
-- Send the file.
Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime));
declare
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write (Data.Value.Data);
end;
exception
when ADO.Objects.NOT_FOUND | Constraint_Error =>
Log.Info ("Storage file {0}/{1}/{2} not found", Wiki, File, Name);
Response.Send_Error (ASF.Responses.SC_NOT_FOUND);
return;
end Do_Get;
end AWA.Wikis.Servlets;
|
-----------------------------------------------------------------------
-- awa-wikis-servlets -- Serve files saved in the storage service
-- 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 Util.Log.Loggers;
with AWA.Images.Services;
with AWA.Wikis.Modules;
package body AWA.Wikis.Servlets is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Servlets");
-- ------------------------------
-- Load the data content that correspond to the GET request and get the name as well
-- as mime-type and date.
-- ------------------------------
overriding
procedure Load (Server : in Image_Servlet;
Request : in out ASF.Requests.Request'Class;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Data : out ADO.Blob_Ref) is
Wiki : constant String := Request.Get_Path_Parameter (1);
File : constant String := Request.Get_Path_Parameter (2);
Size : constant String := Request.Get_Path_Parameter (3);
File_Name : constant String := Request.Get_Path_Parameter (4);
Module : constant AWA.Wikis.Modules.Wiki_Module_Access := Wikis.Modules.Get_Wiki_Module;
Wiki_Id : ADO.Identifier;
File_Id : ADO.Identifier;
Width : Natural;
Height : Natural;
begin
Wiki_Id := ADO.Identifier'Value (Wiki);
File_Id := ADO.Identifier'Value (File);
AWA.Images.Services.Get_Sizes (Dimension => Size,
Width => Width,
Height => Height);
Module.Load_Image (Wiki_Id => Wiki_Id,
Image_Id => File_Id,
Mime => Mime,
Date => Date,
Into => Data);
end Load;
end AWA.Wikis.Servlets;
|
Implement the Image_Servlet by using the AWA storage servlet and overloading the Load procedure
|
Implement the Image_Servlet by using the AWA storage servlet and overloading the Load procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b67932b923527acdad6589c0c926bc963da0ecd4
|
awt/src/wayland/orka-contexts-egl-wayland-awt.adb
|
awt/src/wayland/orka-contexts-egl-wayland-awt.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 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.Strings.Fixed;
with Orka.Logging;
with Orka.Terminals;
with EGL.Objects.Configs;
with EGL.Objects.Surfaces;
with Wayland.Protocols.Client.AWT;
package body Orka.Contexts.EGL.Wayland.AWT is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
procedure Print_Monitor (Monitor : Standard.AWT.Monitors.Monitor'Class) is
State : constant Standard.AWT.Monitors.Monitor_State := Monitor.State;
use Standard.AWT.Monitors;
begin
Messages.Log (Debug, "Window visible on monitor");
Messages.Log (Debug, " name: " & (+State.Name));
Messages.Log (Debug, " offset: " &
Trim (State.X'Image) & ", " & Trim (State.Y'Image));
Messages.Log (Debug, " size: " &
Trim (State.Width'Image) & " × " & Trim (State.Height'Image));
Messages.Log (Debug, " refresh: " & Orka.Terminals.Image (State.Refresh));
end Print_Monitor;
----------------------------------------------------------------------------
overriding
function Width (Object : AWT_Window) return Positive is
State : Standard.AWT.Windows.Framebuffer_State renames Object.State;
begin
return State.Width;
end Width;
overriding
function Height (Object : AWT_Window) return Positive is
State : Standard.AWT.Windows.Framebuffer_State renames Object.State;
begin
return State.Height;
end Height;
----------------------------------------------------------------------------
overriding
procedure On_Move
(Object : in out AWT_Window;
Monitor : Standard.AWT.Monitors.Monitor'Class;
Presence : Standard.AWT.Windows.Monitor_Presence)
is
use all type Standard.AWT.Windows.Monitor_Presence;
use Standard.AWT.Monitors;
begin
case Presence is
when Entered =>
Print_Monitor (Monitor);
when Left =>
Messages.Log (Debug, "Window no longer visible on monitor");
Messages.Log (Debug, " name: " & (+Monitor.State.Name));
end case;
end On_Move;
----------------------------------------------------------------------------
overriding
procedure Make_Current
(Object : AWT_Context;
Window : in out Orka.Windows.Window'Class) is
begin
if Window not in AWT_Window'Class then
raise Constraint_Error;
end if;
AWT_Window (Window).Make_Current (Object.Context);
end Make_Current;
overriding
function Create_Context
(Version : Orka.Contexts.Context_Version;
Flags : Orka.Contexts.Context_Flags := (others => False)) return AWT_Context is
begin
if not Standard.AWT.Is_Initialized then
Standard.AWT.Initialize;
end if;
return Create_Context
(Standard.Wayland.Protocols.Client.AWT.Get_Display (Standard.AWT.Wayland.Get_Display.all),
Version, Flags);
end Create_Context;
overriding
function Create_Window
(Context : Orka.Contexts.Surface_Context'Class;
Width, Height : Positive;
Title : String := "";
Samples : Natural := 0;
Visible, Resizable : Boolean := True;
Transparent : Boolean := False) return AWT_Window
is
package EGL_Configs renames Standard.EGL.Objects.Configs;
package EGL_Surfaces renames Standard.EGL.Objects.Surfaces;
use all type Standard.EGL.Objects.Contexts.Buffer_Kind;
use type EGL_Configs.Config;
package SF renames Ada.Strings.Fixed;
Object : AWT_Context renames AWT_Context (Context);
begin
return Result : AWT_Window do
declare
Configs : constant EGL_Configs.Config_Array :=
EGL_Configs.Get_Configs
(Object.Context.Display,
8, 8, 8, (if Transparent then 8 else 0),
24, 8, EGL_Configs.Sample_Size (Samples));
Used_Config : EGL_Configs.Config renames Configs (Configs'First);
begin
Messages.Log (Debug, "EGL configs: (" & Trim (Natural'Image (Configs'Length)) & ")");
Messages.Log (Debug, " Re Gr Bl Al De St Ms");
Messages.Log (Debug, " --------------------");
for Config of Configs loop
declare
State : constant EGL_Configs.Config_State := Config.State;
begin
Messages.Log (Debug, " - " &
SF.Tail (Trim (State.Red'Image), 2) & " " &
SF.Tail (Trim (State.Green'Image), 2) & " " &
SF.Tail (Trim (State.Blue'Image), 2) & " " &
SF.Tail (Trim (State.Alpha'Image), 2) & " " &
SF.Tail (Trim (State.Depth'Image), 2) & " " &
SF.Tail (Trim (State.Stencil'Image), 2) & " " &
SF.Tail (Trim (State.Samples'Image), 2) &
(if Config = Used_Config then " (used)" else ""));
end;
end loop;
Result.Set_EGL_Data (Object.Context, Used_Config, sRGB => True);
Result.Create_Window ("", Title, Width, Height,
Visible => Visible,
Resizable => Resizable,
Decorated => True,
Transparent => Transparent);
Result.Make_Current (Object.Context);
pragma Assert (Object.Context.Buffer = Back);
Messages.Log (Debug, "Created AWT window");
Messages.Log (Debug, " size: " &
Trim (Width'Image) & " × " & Trim (Height'Image));
Messages.Log (Debug, " visible: " & (if Visible then "yes" else "no"));
Messages.Log (Debug, " resizable: " & (if Resizable then "yes" else "no"));
Messages.Log (Debug, " transparent: " & (if Transparent then "yes" else "no"));
end;
end return;
end Create_Window;
end Orka.Contexts.EGL.Wayland.AWT;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 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.Strings.Fixed;
with Orka.Logging;
with Orka.Terminals;
with EGL.Objects.Configs;
with EGL.Objects.Surfaces;
with Wayland.Protocols.Client.AWT;
package body Orka.Contexts.EGL.Wayland.AWT is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
procedure Print_Monitor (Monitor : Standard.AWT.Monitors.Monitor'Class) is
State : constant Standard.AWT.Monitors.Monitor_State := Monitor.State;
use Standard.AWT.Monitors;
begin
Messages.Log (Debug, "Window visible on monitor " & (+State.Name));
Messages.Log (Debug, " offset: " &
Trim (State.X'Image) & ", " & Trim (State.Y'Image));
Messages.Log (Debug, " size: " &
Trim (State.Width'Image) & " × " & Trim (State.Height'Image));
Messages.Log (Debug, " refresh: " & Orka.Terminals.Image (State.Refresh));
end Print_Monitor;
----------------------------------------------------------------------------
overriding
function Width (Object : AWT_Window) return Positive is
State : Standard.AWT.Windows.Framebuffer_State renames Object.State;
begin
return State.Width;
end Width;
overriding
function Height (Object : AWT_Window) return Positive is
State : Standard.AWT.Windows.Framebuffer_State renames Object.State;
begin
return State.Height;
end Height;
----------------------------------------------------------------------------
overriding
procedure On_Move
(Object : in out AWT_Window;
Monitor : Standard.AWT.Monitors.Monitor'Class;
Presence : Standard.AWT.Windows.Monitor_Presence)
is
use all type Standard.AWT.Windows.Monitor_Presence;
use Standard.AWT.Monitors;
begin
case Presence is
when Entered =>
Print_Monitor (Monitor);
when Left =>
Messages.Log (Debug, "Window no longer visible on monitor " & (+Monitor.State.Name));
end case;
end On_Move;
----------------------------------------------------------------------------
overriding
procedure Make_Current
(Object : AWT_Context;
Window : in out Orka.Windows.Window'Class) is
begin
if Window not in AWT_Window'Class then
raise Constraint_Error;
end if;
AWT_Window (Window).Make_Current (Object.Context);
end Make_Current;
overriding
function Create_Context
(Version : Orka.Contexts.Context_Version;
Flags : Orka.Contexts.Context_Flags := (others => False)) return AWT_Context is
begin
if not Standard.AWT.Is_Initialized then
Standard.AWT.Initialize;
end if;
return Create_Context
(Standard.Wayland.Protocols.Client.AWT.Get_Display (Standard.AWT.Wayland.Get_Display.all),
Version, Flags);
end Create_Context;
overriding
function Create_Window
(Context : Orka.Contexts.Surface_Context'Class;
Width, Height : Positive;
Title : String := "";
Samples : Natural := 0;
Visible, Resizable : Boolean := True;
Transparent : Boolean := False) return AWT_Window
is
package EGL_Configs renames Standard.EGL.Objects.Configs;
package EGL_Surfaces renames Standard.EGL.Objects.Surfaces;
use all type Standard.EGL.Objects.Contexts.Buffer_Kind;
use type EGL_Configs.Config;
package SF renames Ada.Strings.Fixed;
Object : AWT_Context renames AWT_Context (Context);
begin
return Result : AWT_Window do
declare
Configs : constant EGL_Configs.Config_Array :=
EGL_Configs.Get_Configs
(Object.Context.Display,
8, 8, 8, (if Transparent then 8 else 0),
24, 8, EGL_Configs.Sample_Size (Samples));
Used_Config : EGL_Configs.Config renames Configs (Configs'First);
begin
Messages.Log (Debug, "EGL configs: (" & Trim (Natural'Image (Configs'Length)) & ")");
Messages.Log (Debug, " Re Gr Bl Al De St Ms");
Messages.Log (Debug, " --------------------");
for Config of Configs loop
declare
State : constant EGL_Configs.Config_State := Config.State;
begin
Messages.Log (Debug, " - " &
SF.Tail (Trim (State.Red'Image), 2) & " " &
SF.Tail (Trim (State.Green'Image), 2) & " " &
SF.Tail (Trim (State.Blue'Image), 2) & " " &
SF.Tail (Trim (State.Alpha'Image), 2) & " " &
SF.Tail (Trim (State.Depth'Image), 2) & " " &
SF.Tail (Trim (State.Stencil'Image), 2) & " " &
SF.Tail (Trim (State.Samples'Image), 2) &
(if Config = Used_Config then " (used)" else ""));
end;
end loop;
Result.Set_EGL_Data (Object.Context, Used_Config, sRGB => True);
Result.Create_Window ("", Title, Width, Height,
Visible => Visible,
Resizable => Resizable,
Decorated => True,
Transparent => Transparent);
Result.Make_Current (Object.Context);
pragma Assert (Object.Context.Buffer = Back);
Messages.Log (Debug, "Created AWT window");
Messages.Log (Debug, " size: " &
Trim (Width'Image) & " × " & Trim (Height'Image));
Messages.Log (Debug, " visible: " & (if Visible then "yes" else "no"));
Messages.Log (Debug, " resizable: " & (if Resizable then "yes" else "no"));
Messages.Log (Debug, " transparent: " & (if Transparent then "yes" else "no"));
end;
end return;
end Create_Window;
end Orka.Contexts.EGL.Wayland.AWT;
|
Simplify log output of whether window is visible/hidden on a monitor
|
awt: Simplify log output of whether window is visible/hidden on a monitor
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
02c74b1e9fefc67187b2eb44b9714cfaa0779777
|
src/gen-commands-info.adb
|
src/gen-commands-info.adb
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- 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.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Files;
package body Gen.Commands.Info is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector);
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean);
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition);
procedure Print_Dynamo_Projects (Project : in out Gen.Model.Projects.Root_Project_Definition);
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count);
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition);
List : Gen.Utils.String_List.Vector;
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector) is
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String);
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String) is
Path : constant String := Util.Files.Compose (Base_Dir, Dir);
begin
if not Result.Contains (Path)
and then Ada.Directories.Exists (Path) then
Result.Append (Path);
end if;
end Add_Model_Dir;
Iter : Gen.Utils.String_List.Cursor := List.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Add_Model_Dir (Dir, "db");
Add_Model_Dir (Dir, "db/regtests");
Add_Model_Dir (Dir, "db/samples");
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Collect_Directories;
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
begin
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (File);
Done := False;
end Print_Model_File;
-- ------------------------------
-- Print the list of GNAT projects used by the main project.
-- ------------------------------
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is
use Gen.Utils.GNAT;
Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First;
Info : Project_Info;
begin
if Project_Info_Vectors.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("GNAT project files:");
while Project_Info_Vectors.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Info := Project_Info_Vectors.Element (Iter);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path));
Project_Info_Vectors.Next (Iter);
end loop;
end if;
end Print_GNAT_Projects;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := Project.Modules.First;
Ref : Model.Projects.Project_Reference;
begin
if Project_Vectors.Has_Element (Iter) then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name));
Ada.Text_IO.Set_Col (Indent + 30);
if Ref.Project /= null then
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path));
else
Ada.Text_IO.Put_Line ("?");
end if;
Project_Vectors.Next (Iter);
end loop;
Iter := Project.Modules.First;
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
if Ref.Project /= null then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("== " & Ada.Strings.Unbounded.To_String (Ref.Name));
Print_Modules (Ref.Project.all, Indent + 4);
end if;
Project_Vectors.Next (Iter);
end loop;
end if;
end Print_Modules;
-- ------------------------------
-- Print the list of Dynamo projects used by the main project.
-- ------------------------------
procedure Print_Dynamo_Projects (Project : in out Gen.Model.Projects.Root_Project_Definition) is
Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First;
begin
if Gen.Utils.String_List.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("Dynamo project files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Gen.Utils.String_List.Next (Iter);
end loop;
end if;
end Print_Dynamo_Projects;
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is
begin
Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project));
Print_Dynamo_Projects (Project);
Print_Modules (Project, 1);
declare
Model_Dirs : Gen.Utils.String_List.Vector;
begin
Collect_Directories (List, Model_Dirs);
declare
Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First;
begin
Ada.Text_IO.Put_Line ("ADO model files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Util.Files.Iterate_Files_Path (Pattern => "*.xml",
Path => Gen.Utils.String_List.Element (Iter),
Process => Print_Model_File'Access);
Gen.Utils.String_List.Next (Iter);
end loop;
end;
end;
end Print_Project;
begin
Generator.Read_Project ("dynamo.xml", True);
Generator.Update_Project (Print_Project'Access);
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);
begin
Ada.Text_IO.Put_Line ("info: Print information about the current project");
Ada.Text_IO.Put_Line ("Usage: info");
Ada.Text_IO.New_Line;
end Help;
end Gen.Commands.Info;
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- 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.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Files;
package body Gen.Commands.Info is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector);
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean);
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition);
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition);
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count);
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition);
List : Gen.Utils.String_List.Vector;
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector) is
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String);
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String) is
Path : constant String := Util.Files.Compose (Base_Dir, Dir);
begin
if not Result.Contains (Path)
and then Ada.Directories.Exists (Path) then
Result.Append (Path);
end if;
end Add_Model_Dir;
Iter : Gen.Utils.String_List.Cursor := List.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Add_Model_Dir (Dir, "db");
Add_Model_Dir (Dir, "db/regtests");
Add_Model_Dir (Dir, "db/samples");
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Collect_Directories;
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
begin
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (File);
Done := False;
end Print_Model_File;
-- ------------------------------
-- Print the list of GNAT projects used by the main project.
-- ------------------------------
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is
use Gen.Utils.GNAT;
Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First;
Info : Project_Info;
begin
if Project_Info_Vectors.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("GNAT project files:");
while Project_Info_Vectors.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Info := Project_Info_Vectors.Element (Iter);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path));
Project_Info_Vectors.Next (Iter);
end loop;
end if;
end Print_GNAT_Projects;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := Project.Modules.First;
Ref : Model.Projects.Project_Reference;
begin
if Project_Vectors.Has_Element (Iter) then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name));
Ada.Text_IO.Set_Col (Indent + 30);
if Ref.Project /= null then
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path));
else
Ada.Text_IO.Put_Line ("?");
end if;
Project_Vectors.Next (Iter);
end loop;
Iter := Project.Modules.First;
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("== " & Ada.Strings.Unbounded.To_String (Ref.Name));
Print_Modules (Ref.Project.all, Indent + 4);
end if;
Project_Vectors.Next (Iter);
end loop;
end if;
end Print_Modules;
-- ------------------------------
-- Print the list of Dynamo projects used by the main project.
-- ------------------------------
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is
Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First;
begin
if Gen.Utils.String_List.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("Dynamo project files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Gen.Utils.String_List.Next (Iter);
end loop;
end if;
end Print_Dynamo_Projects;
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is
begin
Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project));
Print_Dynamo_Projects (Project);
Print_Modules (Project, 1);
declare
Model_Dirs : Gen.Utils.String_List.Vector;
begin
Collect_Directories (List, Model_Dirs);
declare
Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First;
begin
Ada.Text_IO.Put_Line ("ADO model files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Util.Files.Iterate_Files_Path (Pattern => "*.xml",
Path => Gen.Utils.String_List.Element (Iter),
Process => Print_Model_File'Access);
Gen.Utils.String_List.Next (Iter);
end loop;
end;
end;
end Print_Project;
begin
Generator.Read_Project ("dynamo.xml", True);
Generator.Update_Project (Print_Project'Access);
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);
begin
Ada.Text_IO.Put_Line ("info: Print information about the current project");
Ada.Text_IO.Put_Line ("Usage: info");
Ada.Text_IO.New_Line;
end Help;
end Gen.Commands.Info;
|
Fix compilation warnings and simplify the output
|
Fix compilation warnings and simplify the output
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
5e85d5fc570613bfcf7df08990d778caf8d8062c
|
awa/plugins/awa-images/regtests/awa-images-modules-tests.adb
|
awa/plugins/awa-images/regtests/awa-images-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-storages-modules-tests -- Unit tests for storage service
-- Copyright (C) 2012, 2013, 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 Ada.Strings.Unbounded;
with Util.Test_Caller;
with Security.Contexts;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with Servlet.Responses;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Images.Modules;
with AWA.Storages.Beans;
with AWA.Storages.Services;
with AWA.Storages.Modules;
package body AWA.Images.Modules.Tests is
use type AWA.Storages.Services.Storage_Service_Access;
package Caller is new Util.Test_Caller (Test, "Images.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Create_Image",
Test_Create_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Get_Sizes",
Test_Get_Sizes'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Scale",
Test_Scale'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.On_Create",
Test_Store_Image'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Image (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg");
Thumb : constant String
:= Util.Tests.Get_Test_Path ("regtests/result/bast-12-thumb.jpg");
Width : Natural := 64;
Height : Natural := 64;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Images.Modules.Get_Image_Module;
T.Manager.Create_Thumbnail (Source, Thumb, Width, Height);
Util.Tests.Assert_Equals (T, 1720, Width, "Invalid image width");
Util.Tests.Assert_Equals (T, 1098, Height, "Invalid image height");
end Test_Create_Image;
-- ------------------------------
-- Test the Get_Sizes operation.
-- ------------------------------
procedure Test_Get_Sizes (T : in out Test) is
Width : Natural;
Height : Natural;
begin
AWA.Images.Modules.Get_Sizes ("default", Width, Height);
Util.Tests.Assert_Equals (T, 800, Width, "Default width should be 800");
Util.Tests.Assert_Equals (T, 0, Height, "Default height should be 0");
AWA.Images.Modules.Get_Sizes ("123x456", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 456, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("x56", Width, Height);
Util.Tests.Assert_Equals (T, 0, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 56, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("123x", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("123xtoto", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("xtoto", Width, Height);
Util.Tests.Assert_Equals (T, 0, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("original", Width, Height);
Util.Tests.Assert_Equals (T, Natural'Last, Width, "Invalid width");
Util.Tests.Assert_Equals (T, Natural'Last, Height, "Invalid height");
end Test_Get_Sizes;
-- ------------------------------
-- Test the Scale operation.
-- ------------------------------
procedure Test_Scale (T : in out Test) is
Width : Natural;
Height : Natural;
begin
Width := 0;
Height := 0;
AWA.Images.Modules.Scale (123, 456, Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 456, Height, "Invalid height");
Width := 100;
Height := 0;
AWA.Images.Modules.Scale (10000, 2000, Width, Height);
Util.Tests.Assert_Equals (T, 100, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 20, Height, "Invalid height");
Width := 0;
Height := 200;
AWA.Images.Modules.Scale (10000, 2000, Width, Height);
Util.Tests.Assert_Equals (T, 1000, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 200, Height, "Invalid height");
end Test_Scale;
-- ------------------------------
-- Test the creation of an image through the storage service.
-- ------------------------------
procedure Test_Store_Image (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Folder : AWA.Storages.Beans.Folder_Bean;
Store : AWA.Storages.Models.Storage_Ref;
Mgr : AWA.Storages.Services.Storage_Service_Access;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Path : constant String
:= Util.Tests.Get_Path ("regtests/files/images/Ada-Lovelace.jpg");
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Mgr := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (Mgr /= null, "Null storage manager");
-- Make a storage folder.
Folder.Module := AWA.Storages.Modules.Get_Storage_Module;
Folder.Set_Name ("Image folder");
Folder.Save (Outcome);
Store.Set_Folder (Folder);
Store.Set_Mime_Type ("image/jpg");
Store.Set_Name ("Ada-Lovelace.jpg");
Mgr.Save (Store, Path, AWA.Storages.Models.FILE);
declare
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Id : constant String := ADO.Identifier'Image (Store.Get_Id);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply,
"/storages/images/" & Id (Id'First + 1 .. Id'Last)
& "/view/Ada-Lovelace.jpg",
"image-get-Ada-Lovelace.jpg");
ASF.Tests.Assert_Header (T, "Content-Type", "image/jpg", Reply);
Util.Tests.Assert_Equals (T, Servlet.Responses.SC_OK,
Reply.Get_Status,
"Invalid response for image");
-- Try to get an invalid image
ASF.Tests.Do_Get (Request, Reply,
"/storages/images/plop"
& "/view/Ada-Lovelace.jpg",
"image-get-plop.jpg");
Util.Tests.Assert_Equals (T, Servlet.Responses.SC_NOT_FOUND,
Reply.Get_Status,
"Invalid response for image");
end;
end Test_Store_Image;
end AWA.Images.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-storages-modules-tests -- Unit tests for storage service
-- Copyright (C) 2012, 2013, 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 Ada.Strings.Unbounded;
with Util.Test_Caller;
with Security.Contexts;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with Servlet.Responses;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Storages.Beans;
with AWA.Storages.Services;
with AWA.Storages.Modules;
package body AWA.Images.Modules.Tests is
use type AWA.Storages.Services.Storage_Service_Access;
package Caller is new Util.Test_Caller (Test, "Images.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Create_Image",
Test_Create_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Get_Sizes",
Test_Get_Sizes'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.Scale",
Test_Scale'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Modules.On_Create",
Test_Store_Image'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Image (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg");
Thumb : constant String
:= Util.Tests.Get_Test_Path ("regtests/result/bast-12-thumb.jpg");
Width : Natural := 64;
Height : Natural := 64;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Images.Modules.Get_Image_Module;
T.Manager.Create_Thumbnail (Source, Thumb, Width, Height);
Util.Tests.Assert_Equals (T, 1720, Width, "Invalid image width");
Util.Tests.Assert_Equals (T, 1098, Height, "Invalid image height");
end Test_Create_Image;
-- ------------------------------
-- Test the Get_Sizes operation.
-- ------------------------------
procedure Test_Get_Sizes (T : in out Test) is
Width : Natural;
Height : Natural;
begin
AWA.Images.Modules.Get_Sizes ("default", Width, Height);
Util.Tests.Assert_Equals (T, 800, Width, "Default width should be 800");
Util.Tests.Assert_Equals (T, 0, Height, "Default height should be 0");
AWA.Images.Modules.Get_Sizes ("123x456", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 456, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("x56", Width, Height);
Util.Tests.Assert_Equals (T, 0, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 56, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("123x", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("123xtoto", Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("xtoto", Width, Height);
Util.Tests.Assert_Equals (T, 0, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 0, Height, "Invalid height");
AWA.Images.Modules.Get_Sizes ("original", Width, Height);
Util.Tests.Assert_Equals (T, Natural'Last, Width, "Invalid width");
Util.Tests.Assert_Equals (T, Natural'Last, Height, "Invalid height");
end Test_Get_Sizes;
-- ------------------------------
-- Test the Scale operation.
-- ------------------------------
procedure Test_Scale (T : in out Test) is
Width : Natural;
Height : Natural;
begin
Width := 0;
Height := 0;
AWA.Images.Modules.Scale (123, 456, Width, Height);
Util.Tests.Assert_Equals (T, 123, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 456, Height, "Invalid height");
Width := 100;
Height := 0;
AWA.Images.Modules.Scale (10000, 2000, Width, Height);
Util.Tests.Assert_Equals (T, 100, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 20, Height, "Invalid height");
Width := 0;
Height := 200;
AWA.Images.Modules.Scale (10000, 2000, Width, Height);
Util.Tests.Assert_Equals (T, 1000, Width, "Invalid width");
Util.Tests.Assert_Equals (T, 200, Height, "Invalid height");
end Test_Scale;
-- ------------------------------
-- Test the creation of an image through the storage service.
-- ------------------------------
procedure Test_Store_Image (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Folder : AWA.Storages.Beans.Folder_Bean;
Store : AWA.Storages.Models.Storage_Ref;
Mgr : AWA.Storages.Services.Storage_Service_Access;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Path : constant String
:= Util.Tests.Get_Path ("regtests/files/images/Ada-Lovelace.jpg");
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Mgr := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (Mgr /= null, "Null storage manager");
-- Make a storage folder.
Folder.Module := AWA.Storages.Modules.Get_Storage_Module;
Folder.Set_Name ("Image folder");
Folder.Save (Outcome);
Store.Set_Folder (Folder);
Store.Set_Mime_Type ("image/jpg");
Store.Set_Name ("Ada-Lovelace.jpg");
Mgr.Save (Store, Path, AWA.Storages.Models.FILE);
declare
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Id : constant String := ADO.Identifier'Image (Store.Get_Id);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply,
"/storages/images/" & Id (Id'First + 1 .. Id'Last)
& "/view/Ada-Lovelace.jpg",
"image-get-Ada-Lovelace.jpg");
ASF.Tests.Assert_Header (T, "Content-Type", "image/jpg", Reply);
Util.Tests.Assert_Equals (T, Servlet.Responses.SC_OK,
Reply.Get_Status,
"Invalid response for image");
-- Try to get an invalid image
ASF.Tests.Do_Get (Request, Reply,
"/storages/images/plop"
& "/view/Ada-Lovelace.jpg",
"image-get-plop.jpg");
Util.Tests.Assert_Equals (T, Servlet.Responses.SC_NOT_FOUND,
Reply.Get_Status,
"Invalid response for image");
end;
end Test_Store_Image;
end AWA.Images.Modules.Tests;
|
Remove unused with clause
|
Remove unused with clause
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
dc45f95a8f1dcdb88351ac098da90116b177c253
|
src/statements/adabase-statement-base-mysql.ads
|
src/statements/adabase-statement-base-mysql.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
with AdaBase.Connection.Base.MySQL;
with AdaBase.Bindings.MySQL;
with Ada.Containers.Vectors;
package AdaBase.Statement.Base.MySQL is
package ACM renames AdaBase.Connection.Base.MySQL;
package ABM renames AdaBase.Bindings.MySQL;
package ARS renames AdaBase.Results.Sets;
package AC renames Ada.Containers;
type MySQL_statement (type_of_statement : stmt_type;
log_handler : ALF.LogFacility_access;
mysql_conn : ACM.MySQL_Connection_Access;
initial_sql : SQL_access;
con_error_mode : ErrorMode;
con_case_mode : CaseMode;
con_max_blob : BLOB_maximum;
con_buffered : Boolean)
is new Base_Statement and AIS.iStatement with private;
type MySQL_statement_access is access MySQL_statement;
overriding
function column_count (Stmt : MySQL_statement) return Natural;
overriding
function last_insert_id (Stmt : MySQL_statement) return TraxID;
overriding
function last_sql_state (Stmt : MySQL_statement) return TSqlState;
overriding
function last_driver_code (Stmt : MySQL_statement) return DriverCodes;
overriding
function last_driver_message (Stmt : MySQL_statement) return String;
overriding
procedure discard_rest (Stmt : out MySQL_statement);
overriding
function execute (Stmt : out MySQL_statement) return Boolean;
overriding
function execute (Stmt : out MySQL_statement; parameters : String;
delimiter : Character := '|') return Boolean;
overriding
function rows_returned (Stmt : MySQL_statement) return AffectedRows;
overriding
function column_name (Stmt : MySQL_statement; index : Positive)
return String;
overriding
function column_table (Stmt : MySQL_statement; index : Positive)
return String;
overriding
function column_native_type (Stmt : MySQL_statement; index : Positive)
return field_types;
overriding
function fetch_next (Stmt : out MySQL_statement) return ARS.DataRow;
overriding
function fetch_all (Stmt : out MySQL_statement) return ARS.DataRowSet;
overriding
function fetch_bound (Stmt : out MySQL_statement) return Boolean;
overriding
procedure fetch_next_set (Stmt : out MySQL_statement;
data_present : out Boolean;
data_fetched : out Boolean);
overriding
procedure iterate (Stmt : out MySQL_statement;
process : not null access procedure);
overriding
procedure iterate (Stmt : out MySQL_statement;
process : not null access procedure (row : ARS.DataRow));
private
type mysql_canvas;
procedure initialize (Object : in out MySQL_statement);
procedure Adjust (Object : in out MySQL_statement);
procedure finalize (Object : in out MySQL_statement);
procedure internal_post_prep_stmt (Stmt : out MySQL_statement);
procedure internal_direct_post_exec (Stmt : out MySQL_statement;
newset : Boolean := False);
procedure process_direct_result (Stmt : out MySQL_statement);
procedure scan_column_information (Stmt : out MySQL_statement);
procedure clear_column_information (Stmt : out MySQL_statement);
procedure construct_bind_slot (Stmt : MySQL_statement;
struct : out ABM.MYSQL_BIND;
canvas : out mysql_canvas;
marker : Positive);
procedure auto_assign (Stmt : out MySQL_statement;
index : Positive;
value : String);
function internal_fetch_bound (Stmt : out MySQL_statement) return Boolean;
function internal_fetch_row (Stmt : out MySQL_statement)
return ARS.DataRow;
function internal_ps_fetch_row (Stmt : out MySQL_statement)
return ARS.DataRow;
function internal_ps_fetch_bound (Stmt : out MySQL_statement)
return Boolean;
function num_set_items (nv : String) return Natural;
function bincopy (data : ABM.ICS.char_array_access;
datalen, max_size : Natural)
return String;
function bincopy (data : ABM.ICS.char_array_access;
datalen, max_size : Natural;
hard_limit : Natural := 0)
return AR.chain;
procedure log_problem
(statement : MySQL_statement;
category : LogCategory;
message : String;
pull_codes : Boolean := False;
break : Boolean := False);
type column_info is record
table : CT.Text;
field_name : CT.Text;
field_type : field_types;
field_size : Natural;
null_possible : Boolean;
mysql_type : ABM.enum_field_types;
end record;
type fetch_status is (pending, progressing, completed);
package VColumns is new AC.Vectors (Index_Type => Positive,
Element_Type => column_info);
-- mysql_canvas is used by prepared statement execution
-- The Ada types are converted to C types and stored in this record which
-- MySQL finds through pointers.
type mysql_canvas is record
length : aliased ABM.IC.unsigned_long := 0;
is_null : aliased ABM.my_bool := 0;
error : aliased ABM.my_bool := 0;
buffer_uint8 : ABM.IC.unsigned_char := 0;
buffer_uint16 : ABM.IC.unsigned_short := 0;
buffer_uint32 : ABM.IC.unsigned := 0;
buffer_uint64 : ABM.IC.unsigned_long := 0;
buffer_int8 : ABM.IC.signed_char := 0;
buffer_int16 : ABM.IC.short := 0;
buffer_int32 : ABM.IC.int := 0;
buffer_int64 : ABM.IC.long := 0;
buffer_float : ABM.IC.C_float := 0.0;
buffer_double : ABM.IC.double := 0.0;
buffer_binary : ABM.ICS.char_array_access := null;
buffer_time : ABM.MYSQL_TIME;
end record;
type mysql_canvases is array (Positive range <>) of aliased mysql_canvas;
type mysql_canvases_Access is access all mysql_canvases;
procedure free_canvas is new Ada.Unchecked_Deallocation
(mysql_canvases, mysql_canvases_Access);
procedure free_binary is new Ada.Unchecked_Deallocation
(ABM.IC.char_array, ABM.ICS.char_array_access);
procedure free_sql is new Ada.Unchecked_Deallocation
(String, SQL_access);
procedure reclaim_canvas (Stmt : out MySQL_statement);
type MySQL_statement (type_of_statement : stmt_type;
log_handler : ALF.LogFacility_access;
mysql_conn : ACM.MySQL_Connection_Access;
initial_sql : SQL_access;
con_error_mode : ErrorMode;
con_case_mode : CaseMode;
con_max_blob : BLOB_maximum;
con_buffered : Boolean)
is new Base_Statement and AIS.iStatement with
record
delivery : fetch_status := completed;
result_handle : ABM.MYSQL_RES_Access := null;
stmt_handle : ABM.MYSQL_STMT_Access := null;
bind_canvas : mysql_canvases_Access := null;
assign_counter : Natural := 0;
num_columns : Natural := 0;
size_of_rowset : TraxID := 0;
column_info : VColumns.Vector;
sql_final : SQL_access;
end record;
end AdaBase.Statement.Base.MySQL;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
with AdaBase.Connection.Base.MySQL;
with AdaBase.Bindings.MySQL;
with Ada.Containers.Vectors;
package AdaBase.Statement.Base.MySQL is
package ACM renames AdaBase.Connection.Base.MySQL;
package ABM renames AdaBase.Bindings.MySQL;
package ARS renames AdaBase.Results.Sets;
package AC renames Ada.Containers;
type MySQL_statement (type_of_statement : stmt_type;
log_handler : ALF.LogFacility_access;
mysql_conn : ACM.MySQL_Connection_Access;
initial_sql : SQL_access;
con_error_mode : ErrorMode;
con_case_mode : CaseMode;
con_max_blob : BLOB_maximum;
con_buffered : Boolean)
is new Base_Statement and AIS.iStatement with private;
type MySQL_statement_access is access all MySQL_statement;
overriding
function column_count (Stmt : MySQL_statement) return Natural;
overriding
function last_insert_id (Stmt : MySQL_statement) return TraxID;
overriding
function last_sql_state (Stmt : MySQL_statement) return TSqlState;
overriding
function last_driver_code (Stmt : MySQL_statement) return DriverCodes;
overriding
function last_driver_message (Stmt : MySQL_statement) return String;
overriding
procedure discard_rest (Stmt : out MySQL_statement);
overriding
function execute (Stmt : out MySQL_statement) return Boolean;
overriding
function execute (Stmt : out MySQL_statement; parameters : String;
delimiter : Character := '|') return Boolean;
overriding
function rows_returned (Stmt : MySQL_statement) return AffectedRows;
overriding
function column_name (Stmt : MySQL_statement; index : Positive)
return String;
overriding
function column_table (Stmt : MySQL_statement; index : Positive)
return String;
overriding
function column_native_type (Stmt : MySQL_statement; index : Positive)
return field_types;
overriding
function fetch_next (Stmt : out MySQL_statement) return ARS.DataRow;
overriding
function fetch_all (Stmt : out MySQL_statement) return ARS.DataRowSet;
overriding
function fetch_bound (Stmt : out MySQL_statement) return Boolean;
overriding
procedure fetch_next_set (Stmt : out MySQL_statement;
data_present : out Boolean;
data_fetched : out Boolean);
overriding
procedure iterate (Stmt : out MySQL_statement;
process : not null access procedure);
overriding
procedure iterate (Stmt : out MySQL_statement;
process : not null access procedure (row : ARS.DataRow));
private
type mysql_canvas;
procedure initialize (Object : in out MySQL_statement);
procedure Adjust (Object : in out MySQL_statement);
procedure finalize (Object : in out MySQL_statement);
procedure internal_post_prep_stmt (Stmt : out MySQL_statement);
procedure internal_direct_post_exec (Stmt : out MySQL_statement;
newset : Boolean := False);
procedure process_direct_result (Stmt : out MySQL_statement);
procedure scan_column_information (Stmt : out MySQL_statement);
procedure clear_column_information (Stmt : out MySQL_statement);
procedure construct_bind_slot (Stmt : MySQL_statement;
struct : out ABM.MYSQL_BIND;
canvas : out mysql_canvas;
marker : Positive);
procedure auto_assign (Stmt : out MySQL_statement;
index : Positive;
value : String);
function internal_fetch_bound (Stmt : out MySQL_statement) return Boolean;
function internal_fetch_row (Stmt : out MySQL_statement)
return ARS.DataRow;
function internal_ps_fetch_row (Stmt : out MySQL_statement)
return ARS.DataRow;
function internal_ps_fetch_bound (Stmt : out MySQL_statement)
return Boolean;
function num_set_items (nv : String) return Natural;
function bincopy (data : ABM.ICS.char_array_access;
datalen, max_size : Natural)
return String;
function bincopy (data : ABM.ICS.char_array_access;
datalen, max_size : Natural;
hard_limit : Natural := 0)
return AR.chain;
procedure log_problem
(statement : MySQL_statement;
category : LogCategory;
message : String;
pull_codes : Boolean := False;
break : Boolean := False);
type column_info is record
table : CT.Text;
field_name : CT.Text;
field_type : field_types;
field_size : Natural;
null_possible : Boolean;
mysql_type : ABM.enum_field_types;
end record;
type fetch_status is (pending, progressing, completed);
package VColumns is new AC.Vectors (Index_Type => Positive,
Element_Type => column_info);
-- mysql_canvas is used by prepared statement execution
-- The Ada types are converted to C types and stored in this record which
-- MySQL finds through pointers.
type mysql_canvas is record
length : aliased ABM.IC.unsigned_long := 0;
is_null : aliased ABM.my_bool := 0;
error : aliased ABM.my_bool := 0;
buffer_uint8 : ABM.IC.unsigned_char := 0;
buffer_uint16 : ABM.IC.unsigned_short := 0;
buffer_uint32 : ABM.IC.unsigned := 0;
buffer_uint64 : ABM.IC.unsigned_long := 0;
buffer_int8 : ABM.IC.signed_char := 0;
buffer_int16 : ABM.IC.short := 0;
buffer_int32 : ABM.IC.int := 0;
buffer_int64 : ABM.IC.long := 0;
buffer_float : ABM.IC.C_float := 0.0;
buffer_double : ABM.IC.double := 0.0;
buffer_binary : ABM.ICS.char_array_access := null;
buffer_time : ABM.MYSQL_TIME;
end record;
type mysql_canvases is array (Positive range <>) of aliased mysql_canvas;
type mysql_canvases_Access is access all mysql_canvases;
procedure free_canvas is new Ada.Unchecked_Deallocation
(mysql_canvases, mysql_canvases_Access);
procedure free_binary is new Ada.Unchecked_Deallocation
(ABM.IC.char_array, ABM.ICS.char_array_access);
procedure free_sql is new Ada.Unchecked_Deallocation
(String, SQL_access);
procedure reclaim_canvas (Stmt : out MySQL_statement);
type MySQL_statement (type_of_statement : stmt_type;
log_handler : ALF.LogFacility_access;
mysql_conn : ACM.MySQL_Connection_Access;
initial_sql : SQL_access;
con_error_mode : ErrorMode;
con_case_mode : CaseMode;
con_max_blob : BLOB_maximum;
con_buffered : Boolean)
is new Base_Statement and AIS.iStatement with
record
delivery : fetch_status := completed;
result_handle : ABM.MYSQL_RES_Access := null;
stmt_handle : ABM.MYSQL_STMT_Access := null;
bind_canvas : mysql_canvases_Access := null;
assign_counter : Natural := 0;
num_columns : Natural := 0;
size_of_rowset : TraxID := 0;
column_info : VColumns.Vector;
sql_final : SQL_access;
end record;
end AdaBase.Statement.Base.MySQL;
|
set mysql statement access type "all" attribute
|
set mysql statement access type "all" attribute
|
Ada
|
isc
|
jrmarino/AdaBase
|
21efd9a782d41de18ae6374fbdfdbc1cffd186e5
|
matp/src/mat-expressions.ads
|
matp/src/mat-expressions.ads
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for event and memory slot selection
-- Copyright (C) 2014, 2015, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events;
package MAT.Expressions is
type Resolver_Type is limited interface;
type Resolver_Type_Access is access all Resolver_Type'Class;
-- Find the region that matches the given name.
function Find_Region (Resolver : in Resolver_Type;
Name : in String) return MAT.Memory.Region_Info is abstract;
-- Find the symbol in the symbol table and return the start and end address.
function Find_Symbol (Resolver : in Resolver_Type;
Name : in String) return MAT.Memory.Region_Info is abstract;
-- Find the symbol region in the symbol table that contains the given address
-- and return the start and end address of that region.
function Find_Symbol (Resolver : in Resolver_Type;
Addr : in MAT.Types.Target_Addr) return MAT.Memory.Region_Info is abstract;
-- Get the start time for the tick reference.
function Get_Start_Time (Resolver : in Resolver_Type)
return MAT.Types.Target_Tick_Ref is abstract;
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_REGION,
INSIDE_DIRECT_REGION,
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;
function Create_Inside (Addr : in Mat.Types.Uint64;
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.Event_Id_Type;
Max : in MAT.Events.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.Probe_Index_Type)
return Expression_Type;
-- Create an expression node to keep allocation events which don't have any associated free.
function Create_No_Free 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.Target_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String;
Resolver : in Resolver_Type_Access) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
type yystype is record
low : MAT.Types.Uint64 := 0;
high : MAT.Types.Uint64 := 0;
bval : Boolean := False;
name : Ada.Strings.Unbounded.Unbounded_String;
expr : Expression_Type;
end record;
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_HAS_ADDR,
N_CONDITION, N_THREAD, N_TYPE, N_NO_FREE);
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 =>
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 | N_HAS_ADDR
| N_IN_FUNC | N_IN_FUNC_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.Event_Id_Type;
Max_Event : MAT.Events.Event_Id_Type;
when N_TYPE =>
Event_Kind : MAT.Events.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.Target_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 event and memory slot selection
-- Copyright (C) 2014, 2015, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events;
package MAT.Expressions is
type Resolver_Type is limited interface;
type Resolver_Type_Access is access all Resolver_Type'Class;
-- Find the region that matches the given name.
function Find_Region (Resolver : in Resolver_Type;
Name : in String) return MAT.Memory.Region_Info is abstract;
-- Find the symbol in the symbol table and return the start and end address.
function Find_Symbol (Resolver : in Resolver_Type;
Name : in String) return MAT.Memory.Region_Info is abstract;
-- Find the symbol region in the symbol table that contains the given address
-- and return the start and end address of that region.
function Find_Symbol (Resolver : in Resolver_Type;
Addr : in MAT.Types.Target_Addr)
return MAT.Memory.Region_Info is abstract;
-- Get the start time for the tick reference.
function Get_Start_Time (Resolver : in Resolver_Type)
return MAT.Types.Target_Tick_Ref is abstract;
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_REGION,
INSIDE_DIRECT_REGION,
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;
function Create_Inside (Addr : in MAT.Types.Uint64;
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.Event_Id_Type;
Max : in MAT.Events.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.Probe_Index_Type)
return Expression_Type;
-- Create an expression node to keep allocation events which don't have any associated free.
function Create_No_Free 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.Target_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String;
Resolver : in Resolver_Type_Access) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
type yystype is record
low : MAT.Types.Uint64 := 0;
high : MAT.Types.Uint64 := 0;
bval : Boolean := False;
name : Ada.Strings.Unbounded.Unbounded_String;
expr : Expression_Type;
end record;
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_HAS_ADDR,
N_CONDITION, N_THREAD, N_TYPE, N_NO_FREE);
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 =>
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 | N_HAS_ADDR
| N_IN_FUNC | N_IN_FUNC_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.Event_Id_Type;
Max_Event : MAT.Events.Event_Id_Type;
when N_TYPE =>
Event_Kind : MAT.Events.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.Target_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
098fde61c07deae55ee254be7c1c94499b7485e1
|
src/util-serialize-io.ads
|
src/util-serialize-io.ads
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 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 Ada.Strings.Unbounded;
with Ada.Calendar;
with Util.Beans.Objects;
with Util.Streams;
with Util.Streams.Buffered;
with Util.Serialize.Contexts;
with Util.Serialize.Mappers;
with Util.Log.Loggers;
with Util.Stacks;
package Util.Serialize.IO is
Parse_Error : exception;
-- ------------------------------
-- Output stream for serialization
-- ------------------------------
-- The <b>Output_Stream</b> interface defines the abstract operations for
-- the serialization framework to write objects on the stream according to
-- a target format such as XML or JSON.
type Output_Stream is limited interface and Util.Streams.Output_Stream;
-- Start a document.
procedure Start_Document (Stream : in out Output_Stream) is null;
-- Finish a document.
procedure End_Document (Stream : in out Output_Stream) is null;
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is null;
-- Write the attribute name/value pair.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
-- Write the entity value.
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is abstract;
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is abstract;
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Start_Array (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Array (Stream : in out Output_Stream;
Name : in String) is null;
type Parser is abstract new Util.Serialize.Contexts.Context with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is abstract;
-- Read the file and parse it using the parser.
procedure Parse (Handler : in out Parser;
File : in String);
-- Parse the content string.
procedure Parse_String (Handler : in out Parser;
Content : in String);
-- Returns true if the <b>Parse</b> operation detected at least one error.
function Has_Error (Handler : in Parser) return Boolean;
-- Set the error logger to report messages while parsing and reading the input file.
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access);
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
procedure Finish_Object (Handler : in out Parser;
Name : in String);
procedure Start_Array (Handler : in out Parser;
Name : in String);
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural);
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
procedure Set_Member (Handler : in out Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
procedure Error (Handler : in out Parser;
Message : in String);
procedure Add_Mapping (Handler : in out Parser;
Path : in String;
Mapper : in Util.Serialize.Mappers.Mapper_Access);
-- Dump the mapping tree on the logger using the INFO log level.
procedure Dump (Handler : in Parser'Class;
Logger : in Util.Log.Loggers.Logger'Class);
private
-- Implementation limitation: the max number of active mapping nodes
MAX_NODES : constant Positive := 10;
type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access;
procedure Push (Handler : in out Parser);
-- Pop the context and restore the previous context when leaving an element
procedure Pop (Handler : in out Parser);
function Find_Mapper (Handler : in Parser;
Name : in String) return Util.Serialize.Mappers.Mapper_Access;
type Element_Context is record
-- The object mapper being process.
Object_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The active mapping nodes.
Active_Nodes : Mapper_Access_Array;
end record;
type Element_Context_Access is access all Element_Context;
package Context_Stack is new Util.Stacks (Element_Type => Element_Context,
Element_Type_Access => Element_Context_Access);
type Parser is abstract new Util.Serialize.Contexts.Context with record
Error_Flag : Boolean := False;
Stack : Context_Stack.Stack;
Mapping_Tree : aliased Mappers.Mapper;
Current_Mapper : Util.Serialize.Mappers.Mapper_Access;
-- The file name to use when reporting errors.
File : Ada.Strings.Unbounded.Unbounded_String;
-- The logger which is used to report error messages when parsing an input file.
Error_Logger : Util.Log.Loggers.Logger_Access := null;
end record;
end Util.Serialize.IO;
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 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 Ada.Strings.Unbounded;
with Ada.Calendar;
with Util.Beans.Objects;
with Util.Streams;
with Util.Streams.Buffered;
with Util.Serialize.Contexts;
-- with Util.Serialize.Mappers;
with Util.Log.Loggers;
-- with Util.Stacks;
package Util.Serialize.IO is
Parse_Error : exception;
-- ------------------------------
-- Output stream for serialization
-- ------------------------------
-- The <b>Output_Stream</b> interface defines the abstract operations for
-- the serialization framework to write objects on the stream according to
-- a target format such as XML or JSON.
type Output_Stream is limited interface and Util.Streams.Output_Stream;
-- Start a document.
procedure Start_Document (Stream : in out Output_Stream) is null;
-- Finish a document.
procedure End_Document (Stream : in out Output_Stream) is null;
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is null;
-- Write the attribute name/value pair.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
-- Write the entity value.
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is abstract;
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is abstract;
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Start_Array (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Array (Stream : in out Output_Stream;
Name : in String) is null;
type Reader is limited interface;
-- Start a document.
procedure Start_Document (Stream : in out Reader) is null;
-- Finish a document.
procedure End_Document (Stream : in out Reader) is null;
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
procedure Start_Object (Handler : in out Reader;
Name : in String) is abstract;
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
procedure Finish_Object (Handler : in out Reader;
Name : in String) is abstract;
procedure Start_Array (Handler : in out Reader;
Name : in String) is abstract;
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural) is abstract;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is abstract;
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
procedure Error (Handler : in out Reader;
Message : in String) is abstract;
type Parser is abstract new Util.Serialize.Contexts.Context with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class) is abstract;
-- Read the file and parse it using the parser.
procedure Parse (Handler : in out Parser;
File : in String;
Sink : in out Reader'Class);
-- Parse the content string.
procedure Parse_String (Handler : in out Parser;
Content : in String;
Sink : in out Reader'Class);
-- Returns true if the <b>Parse</b> operation detected at least one error.
function Has_Error (Handler : in Parser) return Boolean;
-- Set the error logger to report messages while parsing and reading the input file.
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
procedure Error (Handler : in out Parser;
Message : in String);
private
type Parser is abstract new Util.Serialize.Contexts.Context with record
Error_Flag : Boolean := False;
-- The file name to use when reporting errors.
File : Ada.Strings.Unbounded.Unbounded_String;
-- The logger which is used to report error messages when parsing an input file.
Error_Logger : Util.Log.Loggers.Logger_Access := null;
end record;
end Util.Serialize.IO;
|
Declare the Reader interface Change the Parser type to avoid dependency with Mappers package
|
Declare the Reader interface
Change the Parser type to avoid dependency with Mappers package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f73ebf25f0ae9b182b70eff4d42a4176529c8bd2
|
src/wiki-filters-toc.adb
|
src/wiki-filters-toc.adb
|
-----------------------------------------------------------------------
-- wiki-filters-toc -- Filter for the creation of Table Of Contents
-- 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.Nodes;
package body Wiki.Filters.TOC is
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
T : Wiki.Nodes.Node_List_Ref;
begin
Document.Get_TOC (T);
Wiki.Nodes.Append (T, new Wiki.Nodes.Node_Type '(Kind => Wiki.Nodes.N_TOC_ENTRY,
Len => Header'Length,
Header => Header,
Level => Level));
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
end Wiki.Filters.TOC;
|
-----------------------------------------------------------------------
-- wiki-filters-toc -- Filter for the creation of Table Of Contents
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Fixed;
with Wiki.Nodes;
package body Wiki.Filters.TOC is
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
use Ada.Strings.Wide_Wide_Fixed;
First : Natural := Text'First;
Pos : Natural;
begin
while First <= Text'Last loop
Pos := Index (Text (First .. Text'Last), "__TOC__");
if Pos > 0 then
Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format);
Filter.Add_Node (Document, Wiki.Nodes.N_TOC_DISPLAY);
First := Pos + 7;
else
Filter_Type (Filter).Add_Text (Document, Text (First .. Text'Last), Format);
exit;
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
T : Wiki.Nodes.Node_List_Ref;
begin
Document.Get_TOC (T);
Wiki.Nodes.Append (T, new Wiki.Nodes.Node_Type '(Kind => Wiki.Nodes.N_TOC_ENTRY,
Len => Header'Length,
Header => Header,
Level => Level));
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
end Wiki.Filters.TOC;
|
Implement the Add_Text procedure to identify the __TOC__ keywords and emit a N_TOC_DISPLAY node in the document
|
Implement the Add_Text procedure to identify the __TOC__ keywords and
emit a N_TOC_DISPLAY node in the document
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
eaee6c6af3825f2e83e5e58c50bcd6d1e5df6169
|
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.Streams;
with Wiki.Strings;
-- == 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);
-- 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 Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- 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 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);
-- 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.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.Streams;
with Wiki.Strings;
-- == 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);
-- Render a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Render_Blockquote (Engine : in out Text_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 Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- 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);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Text_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- 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.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;
|
Rename Add_Blockquote into Render_Blockquote Rename Add_Preformatted into Render_Preformatted
|
Rename Add_Blockquote into Render_Blockquote
Rename Add_Preformatted into Render_Preformatted
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
d71c47a94cf2143b0ab6a793db2a4030828bd3e4
|
matp/src/events/mat-events-tools.adb
|
matp/src/events/mat-events-tools.adb
|
-----------------------------------------------------------------------
-- mat-events-tools - Profiler Events Description
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Tools is
-- ------------------------------
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
-- ------------------------------
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Target_Event_Type is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event_Type;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
function "<" (Left, Right : in Frame_Key_Type) return Boolean is
begin
if Left.Addr < Right.Addr then
return True;
elsif Left.Addr > Right.Addr then
return False;
else
return Left.Level < Right.Level;
end if;
end "<";
-- ------------------------------
-- Collect statistics information about events.
-- ------------------------------
procedure Collect_Info (Into : in out Event_Info_Type;
Event : in MAT.Events.Target_Event_Type) is
begin
Into.Count := Into.Count + 1;
Into.Last_Event := Event;
if Event.Index = MAT.Events.MSG_MALLOC then
Into.Malloc_Count := Into.Malloc_Count + 1;
Into.Alloc_Size := Into.Alloc_Size + Event.Size;
elsif Event.Index = MAT.Events.MSG_REALLOC then
Into.Realloc_Count := Into.Realloc_Count + 1;
Into.Alloc_Size := Into.Alloc_Size + Event.Size;
Into.Free_Size := Into.Free_Size + Event.Old_Size;
elsif Event.Index = MAT.Events.MSG_FREE then
Into.Free_Count := Into.Free_Count + 1;
Into.Free_Size := Into.Free_Size + Event.Size;
end if;
end Collect_Info;
-- ------------------------------
-- Extract from the frame info map, the list of event info sorted on the count.
-- ------------------------------
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
begin
return Left.Count < Right.Count;
end "<";
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Extract from the frame info map, the list of frame event info sorted
-- on the frame level and slot size.
-- ------------------------------
procedure Build_Frame_Info (Map : in Frame_Event_Info_Map;
List : in out Frame_Info_Vector) is
function "<" (Left, Right : in Frame_Info_Type) return Boolean;
function "<" (Left, Right : in Frame_Info_Type) return Boolean is
begin
if Left.Key.Level < Right.Key.Level then
return True;
else
return False;
end if;
end "<";
package Sort_Frame_Info is new Frame_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Frame_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item.Key := Frame_Event_Info_Maps.Key (Iter);
Item.Info := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Frame_Info.Sort (List);
end Build_Frame_Info;
end MAT.Events.Tools;
|
-----------------------------------------------------------------------
-- mat-events-tools - Profiler Events Description
-- Copyright (C) 2014, 2015, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Tools is
-- ------------------------------
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
-- ------------------------------
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Target_Event_Type is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event_Type;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
function "<" (Left, Right : in Frame_Key_Type) return Boolean is
begin
if Left.Addr < Right.Addr then
return True;
elsif Left.Addr > Right.Addr then
return False;
else
return Left.Level < Right.Level;
end if;
end "<";
-- ------------------------------
-- Collect statistics information about events.
-- ------------------------------
procedure Collect_Info (Into : in out Event_Info_Type;
Event : in MAT.Events.Target_Event_Type) is
begin
Into.Count := Into.Count + 1;
Into.Last_Event := Event;
if Event.Index = MAT.Events.MSG_MALLOC then
Into.Malloc_Count := Into.Malloc_Count + 1;
Into.Alloc_Size := Into.Alloc_Size + Event.Size;
elsif Event.Index = MAT.Events.MSG_REALLOC then
Into.Realloc_Count := Into.Realloc_Count + 1;
Into.Alloc_Size := Into.Alloc_Size + Event.Size;
Into.Free_Size := Into.Free_Size + Event.Old_Size;
elsif Event.Index = MAT.Events.MSG_FREE then
Into.Free_Count := Into.Free_Count + 1;
Into.Free_Size := Into.Free_Size + Event.Size;
end if;
end Collect_Info;
-- ------------------------------
-- Extract from the frame info map, the list of event info sorted on the count.
-- ------------------------------
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
(Left.Count < Right.Count);
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Extract from the frame info map, the list of frame event info sorted
-- on the frame level and slot size.
-- ------------------------------
procedure Build_Frame_Info (Map : in Frame_Event_Info_Map;
List : in out Frame_Info_Vector) is
function "<" (Left, Right : in Frame_Info_Type) return Boolean;
function "<" (Left, Right : in Frame_Info_Type) return Boolean is
begin
if Left.Key.Level < Right.Key.Level then
return True;
else
return False;
end if;
end "<";
package Sort_Frame_Info is new Frame_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Frame_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item.Key := Frame_Event_Info_Maps.Key (Iter);
Item.Info := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Frame_Info.Sort (List);
end Build_Frame_Info;
end MAT.Events.Tools;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
db6fcb876c53a3836c759d0c6d0f5dc9d6e7fe6f
|
src/util-commands.ads
|
src/util-commands.ads
|
-----------------------------------------------------------------------
-- util-commands -- 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.Strings.Vectors;
package Util.Commands is
subtype Argument_List is Util.Strings.Vectors.Vector;
end Util.Commands;
|
-----------------------------------------------------------------------
-- util-commands -- 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.
-----------------------------------------------------------------------
package Util.Commands is
-- The argument list interface that gives access to command arguments.
type Argument_List is limited interface;
-- Get the number of arguments available.
function Get_Count (List : in Argument_List) return Natural is abstract;
-- Get the argument at the given position.
function Get_Argument (List : in Argument_List;
Pos : in Positive) return String is abstract;
end Util.Commands;
|
Change the Argument_List to an interface with a Get_Count and Get_Argument operation
|
Change the Argument_List to an interface with a Get_Count and Get_Argument operation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f2fab1a083e144af7dc4eff00e8cc0e69cb017ae
|
src/ado-schemas-entities.adb
|
src/ado-schemas-entities.adb
|
-----------------------------------------------------------------------
-- ado-schemas-entities -- Entity types cache
-- 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.Log.Loggers;
with ADO.SQL;
with ADO.Statements;
with ADO.Model;
package body ADO.Schemas.Entities is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Schemas.Entities");
-- ------------------------------
-- Expand the name into a target parameter value to be used in the SQL query.
-- The Expander can return a T_NULL when a value is not found or
-- it may also raise some exception.
-- ------------------------------
overriding
function Expand (Instance : in out Entity_Cache;
Name : in String) return ADO.Parameters.Parameter is
Pos : constant Entity_Map.Cursor := Instance.Entities.Find (Name);
begin
if not Entity_Map.Has_Element (Pos) then
Log.Error ("No entity type associated with table {0}", Name);
raise No_Entity_Type with "No entity type associated with table " & Name;
end if;
return ADO.Parameters.Parameter '(T => ADO.Parameters.T_INTEGER,
Len => 0, Value_Len => 0, Position => 0,
Name => "",
Num => Entity_Type'Pos (Entity_Map.Element (Pos)));
end Expand;
-- ------------------------------
-- Find the entity type index associated with the given database table.
-- Raises the No_Entity_Type exception if no such mapping exist.
-- ------------------------------
function Find_Entity_Type (Cache : in Entity_Cache;
Table : in Class_Mapping_Access) return ADO.Entity_Type is
begin
return Find_Entity_Type (Cache, Table.Table);
end Find_Entity_Type;
-- ------------------------------
-- Find the entity type index associated with the given database table.
-- Raises the No_Entity_Type exception if no such mapping exist.
-- ------------------------------
function Find_Entity_Type (Cache : in Entity_Cache;
Name : in Util.Strings.Name_Access) return ADO.Entity_Type is
Pos : constant Entity_Map.Cursor := Cache.Entities.Find (Name.all);
begin
if not Entity_Map.Has_Element (Pos) then
Log.Error ("No entity type associated with table {0}", Name.all);
raise No_Entity_Type with "No entity type associated with table " & Name.all;
end if;
return Entity_Type (Entity_Map.Element (Pos));
end Find_Entity_Type;
-- ------------------------------
-- Initialize the entity cache by reading the database entity table.
-- ------------------------------
procedure Initialize (Cache : in out Entity_Cache;
Session : in out ADO.Sessions.Session'Class) is
use type Ada.Containers.Count_Type;
Query : ADO.SQL.Query;
Stmt : ADO.Statements.Query_Statement
:= Session.Create_Statement (ADO.Model.ENTITY_TYPE_TABLE'Access);
begin
Stmt.Set_Parameters (Query);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
Id : constant ADO.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (0));
Name : constant String := Stmt.Get_String (1);
begin
Cache.Entities.Insert (Key => Name, New_Item => Id);
end;
Stmt.Next;
end loop;
exception
when others =>
null;
end Initialize;
end ADO.Schemas.Entities;
|
-----------------------------------------------------------------------
-- ado-schemas-entities -- Entity types cache
-- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ADO.SQL;
with ADO.Statements;
with ADO.Model;
package body ADO.Schemas.Entities is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Schemas.Entities");
-- ------------------------------
-- Expand the name into a target parameter value to be used in the SQL query.
-- The Expander can return a T_NULL when a value is not found or
-- it may also raise some exception.
-- ------------------------------
overriding
function Expand (Instance : in out Entity_Cache;
Name : in String) return ADO.Parameters.Parameter is
Pos : constant Entity_Map.Cursor := Instance.Entities.Find (Name);
begin
if not Entity_Map.Has_Element (Pos) then
Log.Error ("No entity type associated with table {0}", Name);
raise No_Entity_Type with "No entity type associated with table " & Name;
end if;
return ADO.Parameters.Parameter '(T => ADO.Parameters.T_INTEGER,
Len => 0, Value_Len => 0, Position => 0,
Name => "",
Num => Entity_Type'Pos (Entity_Map.Element (Pos)));
end Expand;
-- ------------------------------
-- Find the entity type index associated with the given database table.
-- Raises the No_Entity_Type exception if no such mapping exist.
-- ------------------------------
function Find_Entity_Type (Cache : in Entity_Cache;
Table : in Class_Mapping_Access) return ADO.Entity_Type is
begin
return Find_Entity_Type (Cache, Table.Table);
end Find_Entity_Type;
-- ------------------------------
-- Find the entity type index associated with the given database table.
-- Raises the No_Entity_Type exception if no such mapping exist.
-- ------------------------------
function Find_Entity_Type (Cache : in Entity_Cache;
Name : in Util.Strings.Name_Access) return ADO.Entity_Type is
Pos : constant Entity_Map.Cursor := Cache.Entities.Find (Name.all);
begin
if not Entity_Map.Has_Element (Pos) then
Log.Error ("No entity type associated with table {0}", Name.all);
raise No_Entity_Type with "No entity type associated with table " & Name.all;
end if;
return Entity_Type (Entity_Map.Element (Pos));
end Find_Entity_Type;
-- ------------------------------
-- Initialize the entity cache by reading the database entity table.
-- ------------------------------
procedure Initialize (Cache : in out Entity_Cache;
Session : in out ADO.Sessions.Session'Class) is
Query : ADO.SQL.Query;
Stmt : ADO.Statements.Query_Statement
:= Session.Create_Statement (ADO.Model.ENTITY_TYPE_TABLE'Access);
begin
Stmt.Set_Parameters (Query);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
Id : constant ADO.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (0));
Name : constant String := Stmt.Get_String (1);
begin
Cache.Entities.Insert (Key => Name, New_Item => Id);
end;
Stmt.Next;
end loop;
exception
when others =>
null;
end Initialize;
end ADO.Schemas.Entities;
|
Remove unecessary use clause
|
Remove unecessary use clause
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
f975dbcf647e8332b927fb295d8ec0537fdbc4f4
|
regtests/util-streams-buffered-encoders-tests.adb
|
regtests/util-streams-buffered-encoders-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-encoders-tests -- Unit tests for encoding buffered streams
-- 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.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Encoders.Tests is
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Encoders");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Encoders.Write, Read",
Test_Base64_Stream'Access);
end Add_Tests;
procedure Test_Base64_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Encoders.Encoding_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.b64");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64");
begin
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Stream.Create (Mode => Out_File, Name => Path);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "Base64 stream");
end Test_Base64_Stream;
end Util.Streams.Buffered.Encoders.Tests;
|
-----------------------------------------------------------------------
-- util-streams-buffered-encoders-tests -- Unit tests for encoding buffered streams
-- 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.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Encoders.Tests is
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Encoders");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Encoders.Write, Read",
Test_Base64_Stream'Access);
end Add_Tests;
procedure Test_Base64_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Encoders.Encoding_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.b64");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64");
begin
Print.Initialize (Output => Buffer'Access, Size => 5);
Buffer.Initialize (Output => Stream'Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Stream.Create (Mode => Out_File, Name => Path);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "Base64 stream");
end Test_Base64_Stream;
end Util.Streams.Buffered.Encoders.Tests;
|
Replace Unchecked_Access by Access in stream initialization
|
Replace Unchecked_Access by Access in stream initialization
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8efe2e1d53465267b475240da807ff9c9e866cf8
|
mat/src/frames/mat-frames.adb
|
mat/src/frames/mat-frames.adb
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Interfaces; use Interfaces;
with MAT.Types; use MAT.Types;
package body MAT.Frames is
procedure Free is
new Ada.Unchecked_Deallocation (Frame, Frame_Type);
-- ------------------------------
-- Return the parent frame.
-- ------------------------------
function Parent (Frame : in Frame_Type) return Frame_Type is
begin
if Frame = null then
return null;
else
return Frame.Parent;
end if;
end Parent;
-- ------------------------------
-- Returns the backtrace of the current frame (up to the root).
-- ------------------------------
function Backtrace (Frame : in Frame_Type) return Frame_Table is
Pc : Frame_Table (1 .. Frame.Depth);
Current : Frame_Type := Frame;
Pos : Natural := Current.Depth;
New_Pos : Natural;
begin
while Current /= null and Pos /= 0 loop
New_Pos := Pos - Current.Local_Depth + 1;
Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth);
Pos := New_Pos - 1;
Current := Current.Parent;
end loop;
return Pc;
end Backtrace;
-- ------------------------------
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
-- ------------------------------
function Count_Children (Frame : in Frame_Type;
Recursive : in Boolean := False) return Natural is
Count : Natural := 0;
Child : Frame_Type;
begin
if Frame /= null then
Child := Frame.Children;
while Child /= null loop
Count := Count + 1;
if Recursive then
declare
N : Natural := Count_Children (Child, True);
begin
if N > 0 then
N := N - 1;
end if;
Count := Count + N;
end;
end if;
Child := Child.Next;
end loop;
end if;
return Count;
end Count_Children;
-- ------------------------------
-- Returns all the direct calls made by the current frame.
-- ------------------------------
function Calls (Frame : in Frame_Type) return Frame_Table is
Nb_Calls : Natural := Count_Children (Frame);
Pc : Frame_Table (1 .. Nb_Calls);
begin
if Frame /= null then
declare
Child : Frame_Type := Frame.Children;
Pos : Natural := 1;
begin
while Child /= null loop
Pc (Pos) := Child.Calls (1);
Pos := Pos + 1;
Child := Child.Next;
end loop;
end;
end if;
return Pc;
end Calls;
-- ------------------------------
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
-- ------------------------------
function Current_Depth (Frame : in Frame_Type) return Natural is
begin
if Frame = null then
return 0;
else
return Frame.Depth;
end if;
end Current_Depth;
-- ------------------------------
-- Create a root for stack frame representation.
-- ------------------------------
function Create_Root return Frame_Type is
begin
return new Frame;
end Create_Root;
-- ------------------------------
-- Destroy the frame tree recursively.
-- ------------------------------
procedure Destroy (Frame : in out Frame_Type) is
F : Frame_Type;
begin
if Frame = null then
return;
end if;
-- Destroy its children recursively.
while Frame.Children /= null loop
F := Frame.Children;
Destroy (F);
end loop;
-- Unlink from parent list.
if Frame.Parent /= null then
F := Frame.Parent.Children;
if F = Frame then
Frame.Parent.Children := Frame.Next;
else
while F /= null and F.Next /= Frame loop
F := F.Next;
end loop;
if F = null then
raise Program_Error;
end if;
F.Next := Frame.Next;
end if;
end if;
Free (Frame);
end Destroy;
-- ------------------------------
-- Release the frame when its reference is no longer necessary.
-- ------------------------------
procedure Release (Frame : in Frame_Type) is
Current : Frame_Type := Frame;
begin
-- Scan the frame until the root is reached
-- and decrement the used counter. Free the frames
-- when the used counter reaches 0.
while Current /= null loop
if Current.Used <= 1 then
declare
Tree : Frame_Type := Current;
begin
Current := Current.Parent;
Destroy (Tree);
end;
else
Current.Used := Current.Used - 1;
Current := Current.Parent;
end if;
end loop;
end Release;
-- Split the node pointed to by `F' at the position `Pos'
-- in the caller chain. A new parent is created for the node
-- and the brothers of the node become the brothers of the
-- new parent.
--
-- Returns in `F' the new parent node.
procedure Split (F : in out Frame_Ptr; Pos : in Positive) is
-- Before: After:
--
-- +-------+ +-------+
-- /-| P | /-| P |
-- | +-------+ | +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ...>| node |... ....>| new |... (0..N brothers)
-- +-------+ +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ->| c | ->| node |-->0 (0 brother)
-- +-------+ +-------+
-- |
-- +-------+
-- | c |
-- +-------+
--
New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent,
Next => F.Next,
Children => F,
Used => F.Used,
Depth => F.Depth,
Local_Depth => Pos,
Calls => (others => 0));
Child : Frame_Ptr := F.Parent.Children;
begin
-- Move the PC values in the new parent.
New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos);
F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth);
F.Parent := New_Parent;
F.Next := null;
New_Parent.Depth := F.Depth - F.Local_Depth + Pos;
F.Local_Depth := F.Local_Depth - Pos;
-- Remove F from its parent children list and replace if with New_Parent.
if Child = F then
New_Parent.Parent.Children := New_Parent;
else
while Child.Next /= F loop
Child := Child.Next;
end loop;
Child.Next := New_Parent;
end if;
F := New_Parent;
end Split;
procedure Add_Frame (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Current_Depth : Natural := F.Depth;
Cnt : Local_Depth_Type;
begin
while Pos <= Pc'Last loop
Cnt := Frame_Group_Size;
if Pos + Cnt > Pc'Last then
Cnt := Pc'Last - Pos + 1;
end if;
Current_Depth := Current_Depth + Cnt;
Child := new Frame '(Parent => Child,
Next => Child.Children,
Children => null,
Used => 1,
Depth => Current_Depth,
Local_Depth => Cnt,
Calls => (others => 0));
Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1);
Pos := Pos + Cnt;
Child.Parent.Children := Child;
end loop;
Result := Child;
end Add_Frame;
procedure Insert (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Current : Frame_Ptr := F;
Child : Frame_Ptr;
Pos : Positive := Pc'First;
Lpos : Positive := 1;
Addr : Target_Addr;
begin
while Pos <= Pc'Last loop
Addr := Pc (Pos);
if Lpos <= Current.Local_Depth then
if Addr = Current.Calls (Lpos) then
Lpos := Lpos + 1;
Pos := Pos + 1;
-- Split this node
else
if Lpos > 1 then
Split (Current, Lpos - 1);
end if;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
else
-- Find the first child which has the address.
Child := Current.Children;
while Child /= null loop
exit when Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
if Child = null then
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
Current := Child;
Lpos := 2;
Pos := Pos + 1;
Current.Used := Current.Used + 1;
end if;
end loop;
if Lpos <= Current.Local_Depth then
Split (Current, Lpos - 1);
end if;
Result := Current;
end Insert;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then
return Child;
end if;
Child := Child.Next;
end loop;
raise Not_Found;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
while Pos <= Pc'Last loop
Child := Find (Child, Pc (Pos));
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop
if Child.Calls (Lpos) /= Pc (Pos) then
raise Not_Found;
end if;
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end loop;
return Child;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (F : in Frame_Ptr;
Pc : in PC_Table;
Result : out Frame_Ptr;
Last_Pc : out Natural) is
Current : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
Main_Search:
while Pos <= Pc'Last loop
declare
Addr : Target_Addr := Pc (Pos);
Child : Frame_Ptr := Current.Children;
begin
-- Find the child which has the corresponding PC.
loop
exit Main_Search when Child = null;
exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
Current := Child;
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop
exit Main_Search when Current.Calls (Lpos) /= Pc (Pos);
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end;
end loop Main_Search;
Result := Current;
if Pos > Pc'Last then
Last_Pc := 0;
else
Last_Pc := Pos;
end if;
end Find;
end MAT.Frames;
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Interfaces; use Interfaces;
with MAT.Types; use MAT.Types;
package body MAT.Frames is
procedure Free is
new Ada.Unchecked_Deallocation (Frame, Frame_Type);
-- ------------------------------
-- Return the parent frame.
-- ------------------------------
function Parent (Frame : in Frame_Type) return Frame_Type is
begin
if Frame = null then
return null;
else
return Frame.Parent;
end if;
end Parent;
-- ------------------------------
-- Returns the backtrace of the current frame (up to the root).
-- ------------------------------
function Backtrace (Frame : in Frame_Type) return Frame_Table is
Pc : Frame_Table (1 .. Frame.Depth);
Current : Frame_Type := Frame;
Pos : Natural := Current.Depth;
New_Pos : Natural;
begin
while Current /= null and Pos /= 0 loop
New_Pos := Pos - Current.Local_Depth + 1;
Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth);
Pos := New_Pos - 1;
Current := Current.Parent;
end loop;
return Pc;
end Backtrace;
-- ------------------------------
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
-- ------------------------------
function Count_Children (Frame : in Frame_Type;
Recursive : in Boolean := False) return Natural is
Count : Natural := 0;
Child : Frame_Type;
begin
if Frame /= null then
Child := Frame.Children;
while Child /= null loop
Count := Count + 1;
if Recursive then
declare
N : Natural := Count_Children (Child, True);
begin
if N > 0 then
N := N - 1;
end if;
Count := Count + N;
end;
end if;
Child := Child.Next;
end loop;
end if;
return Count;
end Count_Children;
-- ------------------------------
-- Returns all the direct calls made by the current frame.
-- ------------------------------
function Calls (Frame : in Frame_Type) return Frame_Table is
Nb_Calls : constant Natural := Count_Children (Frame);
Pc : Frame_Table (1 .. Nb_Calls);
begin
if Frame /= null then
declare
Child : Frame_Type := Frame.Children;
Pos : Natural := 1;
begin
while Child /= null loop
Pc (Pos) := Child.Calls (1);
Pos := Pos + 1;
Child := Child.Next;
end loop;
end;
end if;
return Pc;
end Calls;
-- ------------------------------
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
-- ------------------------------
function Current_Depth (Frame : in Frame_Type) return Natural is
begin
if Frame = null then
return 0;
else
return Frame.Depth;
end if;
end Current_Depth;
-- ------------------------------
-- Create a root for stack frame representation.
-- ------------------------------
function Create_Root return Frame_Type is
begin
return new Frame;
end Create_Root;
-- ------------------------------
-- Destroy the frame tree recursively.
-- ------------------------------
procedure Destroy (Frame : in out Frame_Type) is
F : Frame_Type;
begin
if Frame = null then
return;
end if;
-- Destroy its children recursively.
while Frame.Children /= null loop
F := Frame.Children;
Destroy (F);
end loop;
-- Unlink from parent list.
if Frame.Parent /= null then
F := Frame.Parent.Children;
if F = Frame then
Frame.Parent.Children := Frame.Next;
else
while F /= null and F.Next /= Frame loop
F := F.Next;
end loop;
if F = null then
raise Program_Error;
end if;
F.Next := Frame.Next;
end if;
end if;
Free (Frame);
end Destroy;
-- ------------------------------
-- Release the frame when its reference is no longer necessary.
-- ------------------------------
procedure Release (Frame : in Frame_Type) is
Current : Frame_Type := Frame;
begin
-- Scan the frame until the root is reached
-- and decrement the used counter. Free the frames
-- when the used counter reaches 0.
while Current /= null loop
if Current.Used <= 1 then
declare
Tree : Frame_Type := Current;
begin
Current := Current.Parent;
Destroy (Tree);
end;
else
Current.Used := Current.Used - 1;
Current := Current.Parent;
end if;
end loop;
end Release;
-- ------------------------------
-- Split the node pointed to by `F' at the position `Pos'
-- in the caller chain. A new parent is created for the node
-- and the brothers of the node become the brothers of the
-- new parent.
--
-- Returns in `F' the new parent node.
-- ------------------------------
procedure Split (F : in out Frame_Type;
Pos : in Positive) is
-- Before: After:
--
-- +-------+ +-------+
-- /-| P | /-| P |
-- | +-------+ | +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ...>| node |... ....>| new |... (0..N brothers)
-- +-------+ +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ->| c | ->| node |-->0 (0 brother)
-- +-------+ +-------+
-- |
-- +-------+
-- | c |
-- +-------+
--
New_Parent : constant Frame_Type := new Frame '(Parent => F.Parent,
Next => F.Next,
Children => F,
Used => F.Used,
Depth => F.Depth,
Local_Depth => Pos,
Calls => (others => 0));
Child : Frame_Type := F.Parent.Children;
begin
-- Move the PC values in the new parent.
New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos);
F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth);
F.Parent := New_Parent;
F.Next := null;
New_Parent.Depth := F.Depth - F.Local_Depth + Pos;
F.Local_Depth := F.Local_Depth - Pos;
-- Remove F from its parent children list and replace if with New_Parent.
if Child = F then
New_Parent.Parent.Children := New_Parent;
else
while Child.Next /= F loop
Child := Child.Next;
end loop;
Child.Next := New_Parent;
end if;
F := New_Parent;
end Split;
procedure Add_Frame (F : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type) is
Child : Frame_Type := F;
Pos : Positive := Pc'First;
Current_Depth : Natural := F.Depth;
Cnt : Local_Depth_Type;
begin
while Pos <= Pc'Last loop
Cnt := Frame_Group_Size;
if Pos + Cnt > Pc'Last then
Cnt := Pc'Last - Pos + 1;
end if;
Current_Depth := Current_Depth + Cnt;
Child := new Frame '(Parent => Child,
Next => Child.Children,
Children => null,
Used => 1,
Depth => Current_Depth,
Local_Depth => Cnt,
Calls => (others => 0));
Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1);
Pos := Pos + Cnt;
Child.Parent.Children := Child;
end loop;
Result := Child;
end Add_Frame;
procedure Insert (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Current : Frame_Ptr := F;
Child : Frame_Ptr;
Pos : Positive := Pc'First;
Lpos : Positive := 1;
Addr : Target_Addr;
begin
while Pos <= Pc'Last loop
Addr := Pc (Pos);
if Lpos <= Current.Local_Depth then
if Addr = Current.Calls (Lpos) then
Lpos := Lpos + 1;
Pos := Pos + 1;
-- Split this node
else
if Lpos > 1 then
Split (Current, Lpos - 1);
end if;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
else
-- Find the first child which has the address.
Child := Current.Children;
while Child /= null loop
exit when Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
if Child = null then
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
Current := Child;
Lpos := 2;
Pos := Pos + 1;
Current.Used := Current.Used + 1;
end if;
end loop;
if Lpos <= Current.Local_Depth then
Split (Current, Lpos - 1);
end if;
Result := Current;
end Insert;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then
return Child;
end if;
Child := Child.Next;
end loop;
raise Not_Found;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
while Pos <= Pc'Last loop
Child := Find (Child, Pc (Pos));
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop
if Child.Calls (Lpos) /= Pc (Pos) then
raise Not_Found;
end if;
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end loop;
return Child;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (F : in Frame_Ptr;
Pc : in PC_Table;
Result : out Frame_Ptr;
Last_Pc : out Natural) is
Current : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
Main_Search:
while Pos <= Pc'Last loop
declare
Addr : Target_Addr := Pc (Pos);
Child : Frame_Ptr := Current.Children;
begin
-- Find the child which has the corresponding PC.
loop
exit Main_Search when Child = null;
exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
Current := Child;
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop
exit Main_Search when Current.Calls (Lpos) /= Pc (Pos);
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end;
end loop Main_Search;
Result := Current;
if Pos > Pc'Last then
Last_Pc := 0;
else
Last_Pc := Pos;
end if;
end Find;
end MAT.Frames;
|
Refactor the Split operation
|
Refactor the Split operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
c7db1e32f038f0f5e728cdd414a4ff2f9fb45bf9
|
tests/natools-chunked_strings-tests-bugfixes.adb
|
tests/natools-chunked_strings-tests-bugfixes.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2013, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Strings.Maps;
procedure Natools.Chunked_Strings.Tests.Bugfixes
(Report : in out Natools.Tests.Reporter'Class)
is
package NT renames Natools.Tests;
begin
Report.Section ("Extra tests for complete coverage");
declare
Name : constant String := "Overreach of Index";
CS : Chunked_String := To_Chunked_String ("abcd0123");
N : Natural;
begin
CS.Head (4);
N := CS.Index (Ada.Strings.Maps.To_Set ("0123456789"));
if N /= 0 then
Report.Item (Name, NT.Fail);
Report.Info ("Index of digit" & Natural'Image (N) & ", expected 0.");
else
Report.Item (Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
Report.End_Section;
end Natools.Chunked_Strings.Tests.Bugfixes;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Strings.Maps;
procedure Natools.Chunked_Strings.Tests.Bugfixes
(Report : in out Natools.Tests.Reporter'Class)
is
package NT renames Natools.Tests;
begin
Report.Section ("Tests for known bugs");
declare
Name : constant String := "Overreach of Index";
CS : Chunked_String := To_Chunked_String ("abcd0123");
N : Natural;
begin
CS.Head (4);
N := CS.Index (Ada.Strings.Maps.To_Set ("0123456789"));
if N /= 0 then
Report.Item (Name, NT.Fail);
Report.Info ("Index of digit" & Natural'Image (N) & ", expected 0.");
else
Report.Item (Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
Report.End_Section;
end Natools.Chunked_Strings.Tests.Bugfixes;
|
Fix test suite description
|
chunked_strings-tests-bugfixes: Fix test suite description
|
Ada
|
isc
|
faelys/natools
|
93f2e15eecf65166b9a63e04ed39db43461d84c8
|
awa/plugins/awa-images/src/awa-images-services.adb
|
awa/plugins/awa-images/src/awa-images-services.adb
|
-----------------------------------------------------------------------
-- awa-images-services -- Image service
-- Copyright (C) 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 Util.Processes;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Streams.Pipes;
with Util.Streams.Texts;
with ADO;
with ADO.Sessions;
with AWA.Images.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
with AWA.Storages.Modules;
with Ada.Strings.Unbounded;
with EL.Variables.Default;
with EL.Contexts.Default;
-- == 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.
package body AWA.Images.Services is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Image Service
-- ------------------------------
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services");
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Image_Service;
Module : in AWA.Modules.Module'Class) is
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND);
end Initialize;
procedure Create_Thumbnail (Service : in Image_Service;
Source : in String;
Into : in String;
Width : out Natural;
Height : out Natural) is
Ctx : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
Proc : Util.Processes.Process;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
begin
Variables.Bind ("src", Util.Beans.Objects.To_Object (Source));
Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into));
Ctx.Set_Variable_Mapper (Variables'Unchecked_Access);
declare
Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx);
Command : constant String := Util.Beans.Objects.To_String (Cmd);
Input : Util.Streams.Texts.Reader_Stream;
begin
Width := 0;
Height := 0;
Pipe.Open (Command, Util.Processes.READ_ALL);
Input.Initialize (null, Pipe'Unchecked_Access, 1024);
while not Input.Is_Eof loop
declare
use Ada.Strings;
Line : Ada.Strings.Unbounded.Unbounded_String;
Pos : Natural;
Sep : Natural;
Last : Natural;
begin
Input.Read_Line (Into => Line, Strip => False);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Log.Info ("Received: {0}", Line);
-- The '-verbose' option of ImageMagick reports information about the original
-- image. Extract the picture width and height.
-- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018
Pos := Ada.Strings.Unbounded.Index (Line, " ");
if Pos > 0 and Width = 0 then
Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1);
if Pos > 0 then
Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1);
Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1);
if Sep > 0 and Sep < Last then
Log.Info ("Dimension {0} - {1}..{2}",
Ada.Strings.Unbounded.Slice (Line, Pos, Last),
Natural'Image (Pos), Natural'Image (Last));
Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1));
Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1));
end if;
end if;
end if;
end;
end loop;
Pipe.Close;
Util.Processes.Wait (Proc);
if Pipe.Get_Exit_Status /= 0 then
Log.Error ("Command {0} exited with status {1}", Command,
Integer'Image (Pipe.Get_Exit_Status));
end if;
end;
end Create_Thumbnail;
-- Build a thumbnail for the image identified by the Id.
procedure Build_Thumbnail (Service : in Image_Service;
Id : in ADO.Identifier) is
Storage_Service : constant AWA.Storages.Services.Storage_Service_Access
:= AWA.Storages.Modules.Get_Storage_Manager;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
Target_File : AWA.Storages.Storage_File;
Local_File : AWA.Storages.Storage_File;
Width : Natural;
Height : Natural;
begin
Img.Load (DB, Id);
Storage_Service.Get_Local_File (From => Img.Get_Storage.Get_Id, Into => Local_File);
Storage_Service.Create_Local_File (Target_File);
Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File),
AWA.Storages.Get_Path (Target_File), Width, Height);
Img.Set_Width (Width);
Img.Set_Height (Height);
Img.Set_Thumb_Width (64);
Img.Set_Thumb_Height (64);
Ctx.Start;
Img.Save (DB);
Ctx.Commit;
end Build_Thumbnail;
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Create_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
begin
Ctx.Start;
Img.Set_Width (0);
Img.Set_Height (0);
Img.Set_Thumb_Height (0);
Img.Set_Thumb_Width (0);
Img.Set_Storage (File);
Img.Set_Folder (File.Get_Folder);
Img.Set_Owner (File.Get_Owner);
Img.Save (DB);
Ctx.Commit;
end Create_Image;
-- Deletes the storage instance.
procedure Delete_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
begin
null;
end Delete_Image;
end AWA.Images.Services;
|
-----------------------------------------------------------------------
-- awa-images-services -- Image service
-- Copyright (C) 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 Util.Processes;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Streams.Pipes;
with Util.Streams.Texts;
with ADO;
with ADO.Sessions;
with AWA.Images.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
with AWA.Storages.Modules;
with Ada.Strings.Unbounded;
with EL.Variables.Default;
with EL.Contexts.Default;
-- == 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.
package body AWA.Images.Services is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Image Service
-- ------------------------------
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services");
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Image_Service;
Module : in AWA.Modules.Module'Class) is
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND);
end Initialize;
procedure Create_Thumbnail (Service : in Image_Service;
Source : in String;
Into : in String;
Width : out Natural;
Height : out Natural) is
Ctx : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
Proc : Util.Processes.Process;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
begin
Variables.Bind ("src", Util.Beans.Objects.To_Object (Source));
Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into));
Ctx.Set_Variable_Mapper (Variables'Unchecked_Access);
declare
Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx);
Command : constant String := Util.Beans.Objects.To_String (Cmd);
Input : Util.Streams.Texts.Reader_Stream;
begin
Width := 0;
Height := 0;
Pipe.Open (Command, Util.Processes.READ_ALL);
Input.Initialize (null, Pipe'Unchecked_Access, 1024);
while not Input.Is_Eof loop
declare
use Ada.Strings;
Line : Ada.Strings.Unbounded.Unbounded_String;
Pos : Natural;
Sep : Natural;
Last : Natural;
begin
Input.Read_Line (Into => Line, Strip => False);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Log.Info ("Received: {0}", Line);
-- The '-verbose' option of ImageMagick reports information about the original
-- image. Extract the picture width and height.
-- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018
Pos := Ada.Strings.Unbounded.Index (Line, " ");
if Pos > 0 and Width = 0 then
Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1);
if Pos > 0 then
Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1);
Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1);
if Sep > 0 and Sep < Last then
Log.Info ("Dimension {0} - {1}..{2}",
Ada.Strings.Unbounded.Slice (Line, Pos, Last),
Natural'Image (Pos), Natural'Image (Last));
Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1));
Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1));
end if;
end if;
end if;
end;
end loop;
Pipe.Close;
Util.Processes.Wait (Proc);
if Pipe.Get_Exit_Status /= 0 then
Log.Error ("Command {0} exited with status {1}", Command,
Integer'Image (Pipe.Get_Exit_Status));
end if;
end;
end Create_Thumbnail;
-- Build a thumbnail for the image identified by the Id.
procedure Build_Thumbnail (Service : in Image_Service;
Id : in ADO.Identifier) is
Storage_Service : constant AWA.Storages.Services.Storage_Service_Access
:= AWA.Storages.Modules.Get_Storage_Manager;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
Thumb : AWA.Images.Models.Image_Ref;
Target_File : AWA.Storages.Storage_File;
Local_File : AWA.Storages.Storage_File;
Thumbnail : AWA.Storages.Models.Storage_Ref;
Width : Natural;
Height : Natural;
Name : Ada.Strings.Unbounded.Unbounded_String;
begin
Img.Load (DB, Id);
declare
Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage;
begin
Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File);
Storage_Service.Create_Local_File (Target_File);
Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File),
AWA.Storages.Get_Path (Target_File), Width, Height);
Thumbnail.Set_Mime_Type ("image/jpeg");
Thumbnail.Set_Original (Image_File);
Thumbnail.Set_Workspace (Image_File.Get_Workspace);
Thumbnail.Set_Folder (Image_File.Get_Folder);
Thumbnail.Set_Owner (Image_File.Get_Owner);
Thumbnail.Set_Name (String '(Image_File.Get_Name));
Storage_Service.Save (Thumbnail, Target_File, AWA.Storages.Models.DATABASE);
Thumb.Set_Width (64);
Thumb.Set_Height (64);
Thumb.Set_Owner (Image_File.Get_Owner);
Thumb.Set_Folder (Image_File.Get_Folder);
Thumb.Set_Storage (Thumbnail);
Img.Set_Width (Width);
Img.Set_Height (Height);
Img.Set_Thumb_Width (64);
Img.Set_Thumb_Height (64);
Img.Set_Thumbnail (Thumbnail);
Ctx.Start;
Img.Save (DB);
Thumb.Save (DB);
Ctx.Commit;
end;
end Build_Thumbnail;
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Create_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
begin
Ctx.Start;
Img.Set_Width (0);
Img.Set_Height (0);
Img.Set_Thumb_Height (0);
Img.Set_Thumb_Width (0);
Img.Set_Storage (File);
Img.Set_Folder (File.Get_Folder);
Img.Set_Owner (File.Get_Owner);
Img.Save (DB);
Ctx.Commit;
end Create_Image;
-- Deletes the storage instance.
procedure Delete_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
begin
null;
end Delete_Image;
end AWA.Images.Services;
|
Fix Build_Thumbnail to create the database information after a thumbnail image is created
|
Fix Build_Thumbnail to create the database information after a thumbnail image is created
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b7ebce09821a92becd7334df25e32aad2c5499dd
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Abstract_Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Role_Type) return Boolean is abstract;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Abstract_Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Abstract_Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Abstract_Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Abstract_Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Abstract_Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
Remove the Principal
|
Remove the Principal
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
183becfb63b8e492f5c68ada712c50dab92d1c31
|
boards/stm32f429_discovery/framebuffer_ili9341.ads
|
boards/stm32f429_discovery/framebuffer_ili9341.ads
|
with HAL; use HAL;
with HAL.Framebuffer; use HAL.Framebuffer;
with Framebuffer_LTDC;
private with ILI9341;
private with STM32.GPIO;
private with STM32.Device;
package Framebuffer_ILI9341 is
type Frame_Buffer is limited
new Framebuffer_LTDC.Frame_Buffer with private;
procedure Initialize
(Display : in out Frame_Buffer;
Orientation : HAL.Framebuffer.Display_Orientation := Default;
Mode : HAL.Framebuffer.Wait_Mode := Interrupt);
private
-- Chip select and Data/Command select fot the LCD screen
LCD_CSX : STM32.GPIO.GPIO_Point renames STM32.Device.PC2;
LCD_WRX_DCX : STM32.GPIO.GPIO_Point renames STM32.Device.PD13;
LCD_RESET : STM32.GPIO.GPIO_Point renames STM32.Device.PD12;
type Frame_Buffer
is limited new Framebuffer_LTDC.Frame_Buffer with record
Device : ILI9341.ILI9341_Device (STM32.Device.SPI_5'Access,
Chip_Select => LCD_CSX'Access,
WRX => LCD_WRX_DCX'Access,
Reset => LCD_RESET'Access);
end record;
end Framebuffer_ILI9341;
|
with HAL; use HAL;
with HAL.Framebuffer; use HAL.Framebuffer;
with Framebuffer_LTDC;
private with ILI9341;
private with STM32.GPIO;
private with STM32.Device;
package Framebuffer_ILI9341 is
type Frame_Buffer is limited
new Framebuffer_LTDC.Frame_Buffer with private;
procedure Initialize
(Display : in out Frame_Buffer;
Orientation : HAL.Framebuffer.Display_Orientation := Default;
Mode : HAL.Framebuffer.Wait_Mode := Interrupt);
private
-- Chip select and Data/Command select for the LCD screen
LCD_CSX : STM32.GPIO.GPIO_Point renames STM32.Device.PC2;
LCD_WRX_DCX : STM32.GPIO.GPIO_Point renames STM32.Device.PD13;
LCD_RESET : STM32.GPIO.GPIO_Point renames STM32.Device.PD12;
type Frame_Buffer
is limited new Framebuffer_LTDC.Frame_Buffer with record
Device : ILI9341.ILI9341_Device (STM32.Device.SPI_5'Access,
Chip_Select => LCD_CSX'Access,
WRX => LCD_WRX_DCX'Access,
Reset => LCD_RESET'Access);
end record;
end Framebuffer_ILI9341;
|
Correct typo in comment
|
Correct typo in comment
|
Ada
|
bsd-3-clause
|
ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
de1370cd550744c387373dd96e0ac47b74ae1ee9
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014, 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.Strings.Unbounded;
with Ada.Calendar;
with ASF.Applications;
with ADO;
with Wiki.Strings;
with AWA.Modules;
with AWA.Blogs.Models;
with AWA.Counters.Definition;
with AWA.Blogs.Servlets;
with Security.Permissions;
-- == Integration ==
-- To be able to use the `Blogs` module, you will need to add the following line in your
-- GNAT project file:
--
-- with "awa_blogs";
--
-- The `Blog_Module` type manages the creation, update, removal of blog posts in an application.
-- It provides operations that are used by the blog beans or other services to create and update
-- posts. An instance of the `Blog_Module` must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- with AWA.Blogs.Modules;
-- ...
-- type Application is new AWA.Applications.Application with record
-- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Blogs.Modules.NAME,
-- URI => "blogs",
-- Module => App.Blog_Module'Access);
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
-- Define the read post counter.
package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Get the image prefix that was configured for the Blog module.
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
private
type Blog_Module is new AWA.Modules.Module with record
Image_Prefix : Wiki.Strings.UString;
Image_Servlet : aliased AWA.Blogs.Servlets.Image_Servlet;
end record;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with ASF.Applications;
with ADO;
with Wiki.Strings;
with AWA.Modules;
with AWA.Blogs.Models;
with AWA.Counters.Definition;
with AWA.Blogs.Servlets;
with Security.Permissions;
-- == Integration ==
-- To be able to use the `Blogs` module, you will need to add the following line in your
-- GNAT project file:
--
-- with "awa_blogs";
--
-- The `Blog_Module` type manages the creation, update, removal of blog posts in an application.
-- It provides operations that are used by the blog beans or other services to create and update
-- posts. An instance of the `Blog_Module` must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- with AWA.Blogs.Modules;
-- ...
-- type Application is new AWA.Applications.Application with record
-- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Blogs.Modules.NAME,
-- URI => "blogs",
-- Module => App.Blog_Module'Access);
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
-- Define the read post counter.
package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Get the image prefix that was configured for the Blog module.
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Summary : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
Summary : in String;
URI : in String;
Text : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
private
type Blog_Module is new AWA.Modules.Module with record
Image_Prefix : Wiki.Strings.UString;
Image_Servlet : aliased AWA.Blogs.Servlets.Image_Servlet;
end record;
end AWA.Blogs.Modules;
|
Update Create_Post and Update_Post to setup the summary and post format
|
Update Create_Post and Update_Post to setup the summary and post format
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1dfc8717ec6e163356486ecaf3387ce0642b67a7
|
src/gen-generator.ads
|
src/gen-generator.ads
|
-----------------------------------------------------------------------
-- gen-generator -- Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Ada.Containers.Hashed_Maps;
with Util.Beans.Objects;
with Util.Properties;
with ASF.Applications.Main;
with ASF.Contexts.Faces;
with Gen.Model.Packages;
with Gen.Model.Projects;
with Gen.Artifacts.Hibernate;
with Gen.Artifacts.Query;
with Gen.Artifacts.Mappings;
with Gen.Artifacts.Distribs;
with Gen.Artifacts.XMI;
package Gen.Generator is
-- A fatal error that prevents the generator to proceed has occurred.
Fatal_Error : exception;
G_URI : constant String := "http://code.google.com/p/ada-ado/generator";
type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS);
type Mapping_File is record
Path : Ada.Strings.Unbounded.Unbounded_String;
Output : Ada.Text_IO.File_Type;
end record;
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private;
-- Initialize the generator
procedure Initialize (H : in out Handler;
Config_Dir : in Ada.Strings.Unbounded.Unbounded_String;
Debug : in Boolean);
-- Get the configuration properties.
function Get_Properties (H : in Handler) return Util.Properties.Manager;
-- Report an error and set the exit status accordingly
procedure Error (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "");
-- Report an info message.
procedure Info (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
-- Read the XML package file
procedure Read_Package (H : in out Handler;
File : in String);
-- Read the model mapping types and initialize the hibernate artifact.
procedure Read_Mappings (H : in out Handler);
-- Read the XML model file
procedure Read_Model (H : in out Handler;
File : in String;
Silent : in Boolean);
-- Read the model and query files stored in the application directory <b>db</b>.
procedure Read_Models (H : in out Handler;
Dirname : in String);
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (H : in out Handler;
File : in String;
Recursive : in Boolean := False);
-- Prepare the model by checking, verifying and initializing it after it is completely known.
procedure Prepare (H : in out Handler);
-- Finish the generation. Some artifacts could generate other files that take into
-- account files generated previously.
procedure Finish (H : in out Handler);
-- Tell the generator to activate the generation of the given template name.
-- The name is a property name that must be defined in generator.properties to
-- indicate the template file. Several artifacts can trigger the generation
-- of a given template. The template is generated only once.
procedure Add_Generation (H : in out Handler;
Name : in String;
Mode : in Gen.Artifacts.Iteration_Mode;
Mapping : in String);
-- Enable the generation of the Ada package given by the name. By default all the Ada
-- packages found in the model are generated. When called, this enables the generation
-- only for the Ada packages registered here.
procedure Enable_Package_Generation (H : in out Handler;
Name : in String);
-- Save the content generated by the template generator.
procedure Save_Content (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String);
-- Generate the code using the template file
procedure Generate (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
File : in String;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate the code using the template file
procedure Generate (H : in out Handler;
File : in String;
Model : in Gen.Model.Definition_Access;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate all the code for the templates activated through <b>Add_Generation</b>.
procedure Generate_All (H : in out Handler);
-- Generate all the code generation files stored in the directory
procedure Generate_All (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
Name : in String);
-- Set the directory where template files are stored.
procedure Set_Template_Directory (H : in out Handler;
Path : in Ada.Strings.Unbounded.Unbounded_String);
-- Set the directory where results files are generated.
procedure Set_Result_Directory (H : in out Handler;
Path : in String);
-- Get the result directory path.
function Get_Result_Directory (H : in Handler) return String;
-- Get the project plugin directory path.
function Get_Plugin_Directory (H : in Handler) return String;
-- Get the config directory path.
function Get_Config_Directory (H : in Handler) return String;
-- Get the dynamo installation directory path.
function Get_Install_Directory (H : in Handler) return String;
-- Return the search directories that the AWA application can use to find files.
-- The search directories is built by using the project dependencies.
function Get_Search_Directories (H : in Handler) return String;
-- Get the exit status
-- Returns 0 if the generation was successful
-- Returns 1 if there was a generation error
function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in Boolean := False) return Boolean;
-- Set the force-save file mode. When False, if the generated file exists already,
-- an error message is reported.
procedure Set_Force_Save (H : in out Handler;
To : in Boolean);
-- Set the project name.
procedure Set_Project_Name (H : in out Handler;
Name : in String);
-- Get the project name.
function Get_Project_Name (H : in Handler) return String;
-- Set the project property.
procedure Set_Project_Property (H : in out Handler;
Name : in String;
Value : in String);
-- Get the project property identified by the given name. If the project property
-- does not exist, returns the default value. Project properties are loaded
-- by <b>Read_Project</b>.
function Get_Project_Property (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Save the project description and parameters.
procedure Save_Project (H : in out Handler);
-- Get the path of the last generated file.
function Get_Generated_File (H : in Handler) return String;
-- Update the project model through the <b>Process</b> procedure.
procedure Update_Project (H : in out Handler;
Process : not null access
procedure (P : in out Model.Projects.Root_Project_Definition));
-- Scan the dynamo directories and execute the <b>Process</b> procedure with the
-- directory path.
procedure Scan_Directories (H : in Handler;
Process : not null access
procedure (Dir : in String));
private
use Ada.Strings.Unbounded;
use Gen.Artifacts;
type Template_Context is record
Mode : Gen.Artifacts.Iteration_Mode;
Mapping : Unbounded_String;
end record;
package Template_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Template_Context,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record
Conf : ASF.Applications.Config;
-- Config directory.
Config_Dir : Ada.Strings.Unbounded.Unbounded_String;
-- Output base directory.
Output_Dir : Ada.Strings.Unbounded.Unbounded_String;
Model : aliased Gen.Model.Packages.Model_Definition;
Status : Ada.Command_Line.Exit_Status := 0;
-- The file that must be saved (the file attribute in <f:view>.
File : access Util.Beans.Objects.Object;
-- Indicates whether the file must be saved at each generation or only once.
-- This is the mode attribute in <f:view>.
Mode : access Util.Beans.Objects.Object;
-- Indicates whether the file must be ignored after the generation.
-- This is the ignore attribute in <f:view>. It is intended to be used for the package
-- body generation to skip that in some cases when it turns out there is no operation.
Ignore : access Util.Beans.Objects.Object;
-- Whether the AdaMappings.xml file was loaded or not.
Type_Mapping_Loaded : Boolean := False;
-- The root project document.
Project : aliased Gen.Model.Projects.Root_Project_Definition;
-- Hibernate XML artifact
Hibernate : Gen.Artifacts.Hibernate.Artifact;
-- Query generation artifact.
Query : Gen.Artifacts.Query.Artifact;
-- Type mapping artifact.
Mappings : Gen.Artifacts.Mappings.Artifact;
-- The distribution artifact.
Distrib : Gen.Artifacts.Distribs.Artifact;
-- Ada generation from UML-XMI models.
XMI : Gen.Artifacts.XMI.Artifact;
-- The list of templates that must be generated.
Templates : Template_Map.Map;
-- Force the saving of a generated file, even if a file already exist.
Force_Save : Boolean := True;
end record;
-- Execute the lifecycle phases on the faces context.
overriding
procedure Execute_Lifecycle (App : in Handler;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end Gen.Generator;
|
-----------------------------------------------------------------------
-- gen-generator -- Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Ada.Containers.Hashed_Maps;
with Util.Beans.Objects;
with Util.Properties;
with ASF.Applications.Main;
with ASF.Contexts.Faces;
with ASF.Servlets.Files;
with Gen.Model.Packages;
with Gen.Model.Projects;
with Gen.Artifacts.Hibernate;
with Gen.Artifacts.Query;
with Gen.Artifacts.Mappings;
with Gen.Artifacts.Distribs;
with Gen.Artifacts.XMI;
package Gen.Generator is
-- A fatal error that prevents the generator to proceed has occurred.
Fatal_Error : exception;
G_URI : constant String := "http://code.google.com/p/ada-ado/generator";
type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS);
type Mapping_File is record
Path : Ada.Strings.Unbounded.Unbounded_String;
Output : Ada.Text_IO.File_Type;
end record;
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private;
-- Initialize the generator
procedure Initialize (H : in out Handler;
Config_Dir : in Ada.Strings.Unbounded.Unbounded_String;
Debug : in Boolean);
-- Get the configuration properties.
function Get_Properties (H : in Handler) return Util.Properties.Manager;
-- Report an error and set the exit status accordingly
procedure Error (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "");
-- Report an info message.
procedure Info (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "");
-- Read the XML package file
procedure Read_Package (H : in out Handler;
File : in String);
-- Read the model mapping types and initialize the hibernate artifact.
procedure Read_Mappings (H : in out Handler);
-- Read the XML model file
procedure Read_Model (H : in out Handler;
File : in String;
Silent : in Boolean);
-- Read the model and query files stored in the application directory <b>db</b>.
procedure Read_Models (H : in out Handler;
Dirname : in String);
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (H : in out Handler;
File : in String;
Recursive : in Boolean := False);
-- Prepare the model by checking, verifying and initializing it after it is completely known.
procedure Prepare (H : in out Handler);
-- Finish the generation. Some artifacts could generate other files that take into
-- account files generated previously.
procedure Finish (H : in out Handler);
-- Tell the generator to activate the generation of the given template name.
-- The name is a property name that must be defined in generator.properties to
-- indicate the template file. Several artifacts can trigger the generation
-- of a given template. The template is generated only once.
procedure Add_Generation (H : in out Handler;
Name : in String;
Mode : in Gen.Artifacts.Iteration_Mode;
Mapping : in String);
-- Enable the generation of the Ada package given by the name. By default all the Ada
-- packages found in the model are generated. When called, this enables the generation
-- only for the Ada packages registered here.
procedure Enable_Package_Generation (H : in out Handler;
Name : in String);
-- Save the content generated by the template generator.
procedure Save_Content (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String);
-- Generate the code using the template file
procedure Generate (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
File : in String;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate the code using the template file
procedure Generate (H : in out Handler;
File : in String;
Model : in Gen.Model.Definition_Access;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String));
-- Generate all the code for the templates activated through <b>Add_Generation</b>.
procedure Generate_All (H : in out Handler);
-- Generate all the code generation files stored in the directory
procedure Generate_All (H : in out Handler;
Mode : in Gen.Artifacts.Iteration_Mode;
Name : in String);
-- Set the directory where template files are stored.
procedure Set_Template_Directory (H : in out Handler;
Path : in Ada.Strings.Unbounded.Unbounded_String);
-- Set the directory where results files are generated.
procedure Set_Result_Directory (H : in out Handler;
Path : in String);
-- Get the result directory path.
function Get_Result_Directory (H : in Handler) return String;
-- Get the project plugin directory path.
function Get_Plugin_Directory (H : in Handler) return String;
-- Get the config directory path.
function Get_Config_Directory (H : in Handler) return String;
-- Get the dynamo installation directory path.
function Get_Install_Directory (H : in Handler) return String;
-- Return the search directories that the AWA application can use to find files.
-- The search directories is built by using the project dependencies.
function Get_Search_Directories (H : in Handler) return String;
-- Get the exit status
-- Returns 0 if the generation was successful
-- Returns 1 if there was a generation error
function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Get the configuration parameter.
function Get_Parameter (H : in Handler;
Name : in String;
Default : in Boolean := False) return Boolean;
-- Set the force-save file mode. When False, if the generated file exists already,
-- an error message is reported.
procedure Set_Force_Save (H : in out Handler;
To : in Boolean);
-- Set the project name.
procedure Set_Project_Name (H : in out Handler;
Name : in String);
-- Get the project name.
function Get_Project_Name (H : in Handler) return String;
-- Set the project property.
procedure Set_Project_Property (H : in out Handler;
Name : in String;
Value : in String);
-- Get the project property identified by the given name. If the project property
-- does not exist, returns the default value. Project properties are loaded
-- by <b>Read_Project</b>.
function Get_Project_Property (H : in Handler;
Name : in String;
Default : in String := "") return String;
-- Save the project description and parameters.
procedure Save_Project (H : in out Handler);
-- Get the path of the last generated file.
function Get_Generated_File (H : in Handler) return String;
-- Update the project model through the <b>Process</b> procedure.
procedure Update_Project (H : in out Handler;
Process : not null access
procedure (P : in out Model.Projects.Root_Project_Definition));
-- Scan the dynamo directories and execute the <b>Process</b> procedure with the
-- directory path.
procedure Scan_Directories (H : in Handler;
Process : not null access
procedure (Dir : in String));
private
use Ada.Strings.Unbounded;
use Gen.Artifacts;
type Template_Context is record
Mode : Gen.Artifacts.Iteration_Mode;
Mapping : Unbounded_String;
end record;
package Template_Map is
new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Template_Context,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record
Conf : ASF.Applications.Config;
-- Config directory.
Config_Dir : Ada.Strings.Unbounded.Unbounded_String;
-- Output base directory.
Output_Dir : Ada.Strings.Unbounded.Unbounded_String;
Model : aliased Gen.Model.Packages.Model_Definition;
Status : Ada.Command_Line.Exit_Status := 0;
-- The file that must be saved (the file attribute in <f:view>.
File : access Util.Beans.Objects.Object;
-- Indicates whether the file must be saved at each generation or only once.
-- This is the mode attribute in <f:view>.
Mode : access Util.Beans.Objects.Object;
-- Indicates whether the file must be ignored after the generation.
-- This is the ignore attribute in <f:view>. It is intended to be used for the package
-- body generation to skip that in some cases when it turns out there is no operation.
Ignore : access Util.Beans.Objects.Object;
-- Whether the AdaMappings.xml file was loaded or not.
Type_Mapping_Loaded : Boolean := False;
-- The root project document.
Project : aliased Gen.Model.Projects.Root_Project_Definition;
-- Hibernate XML artifact
Hibernate : Gen.Artifacts.Hibernate.Artifact;
-- Query generation artifact.
Query : Gen.Artifacts.Query.Artifact;
-- Type mapping artifact.
Mappings : Gen.Artifacts.Mappings.Artifact;
-- The distribution artifact.
Distrib : Gen.Artifacts.Distribs.Artifact;
-- Ada generation from UML-XMI models.
XMI : Gen.Artifacts.XMI.Artifact;
-- The list of templates that must be generated.
Templates : Template_Map.Map;
-- Force the saving of a generated file, even if a file already exist.
Force_Save : Boolean := True;
-- A fake servlet for template evaluation.
Servlet : ASF.Servlets.Servlet_Access;
end record;
-- Execute the lifecycle phases on the faces context.
overriding
procedure Execute_Lifecycle (App : in Handler;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end Gen.Generator;
|
Add a file servlet to be able to use the <util:file> component in templates
|
Add a file servlet to be able to use the <util:file> component in templates
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
52a252d973031d542870214cf0517696761e88b3
|
regtests/asf-routes-tests.adb
|
regtests/asf-routes-tests.adb
|
-----------------------------------------------------------------------
-- asf-routes-tests - Unit tests for ASF.Routes
-- 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.Log.Loggers;
with Util.Test_Caller;
with EL.Contexts.Default;
package body ASF.Routes.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests");
package Caller is new Util.Test_Caller (Test, "Routes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)",
Test_Add_Route_With_Path'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)",
Test_Add_Route_With_Param'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)",
Test_Add_Route_With_Ext'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)",
Test_Add_Route_With_EL'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Iterate",
Test_Iterate'Access);
end Add_Tests;
overriding
function Get_Value (Bean : in Test_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return Util.Beans.Objects.To_Object (Bean.Id);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (Bean.Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
overriding
procedure Set_Value (Bean : in out Test_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" then
Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "name" then
Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
begin
T.Bean := new Test_Bean;
ASF.Tests.EL_Test (T).Set_Up;
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"),
Util.Beans.Objects.To_Object (T.Bean.all'Access));
for I in T.Routes'Range loop
T.Routes (I).Index := I;
end loop;
end Set_Up;
-- ------------------------------
-- Verify that the path matches the given route.
-- ------------------------------
procedure Verify_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
Route : constant Route_Type_Access := T.Routes (Index)'Unchecked_Access;
R : Route_Context_Type;
begin
Router.Find_Route (Path, R);
declare
P : constant String := Get_Path_Info (R);
begin
T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path);
T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path);
T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path);
-- Inject the path parameters in the bean instance.
Inject_Parameters (R, Bean, T.ELContext.all);
end;
end Verify_Route;
-- ------------------------------
-- Add the route associted with the path pattern.
-- ------------------------------
procedure Add_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
Route : constant Route_Type_Access := T.Routes (Index)'Unchecked_Access;
begin
Router.Add_Route (Path, Route, T.ELContext.all);
Verify_Route (T, Router, Path, Index, Bean);
end Add_Route;
-- ------------------------------
-- Test the Add_Route with simple fixed path components.
-- Example: /list/index.html
-- ------------------------------
procedure Test_Add_Route_With_Path (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/page.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
Verify_Route (T, Router, "/list/index.html", 3, Bean);
end Test_Add_Route_With_Path;
-- ------------------------------
-- Test the Add_Route with extension mapping.
-- Example: /list/*.html
-- ------------------------------
procedure Test_Add_Route_With_Ext (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/*.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean);
Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean);
Add_Route (T, Router, "/view/page/content/*.html", 6, Bean);
-- Verify precedence and wildcard matching.
Verify_Route (T, Router, "/list/index.html", 3, Bean);
Verify_Route (T, Router, "/list/admin.html", 2, Bean);
Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean);
Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean);
end Test_Add_Route_With_Ext;
-- ------------------------------
-- Test the Add_Route with fixed path components and path parameters.
-- Example: /users/:id/view.html
-- ------------------------------
procedure Test_Add_Route_With_Param (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/users/:id/view.html", 1, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/list.html", 2, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/index.html", 3, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path");
Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name");
Add_Route (T, Router, "/users/list/index.html", 8, Bean);
Verify_Route (T, Router, "/users/1234/view.html", 1, Bean);
T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id");
Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean);
T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_Param;
-- ------------------------------
-- Test the Add_Route with fixed path components and EL path injection.
-- Example: /users/#{user.id}/view.html
-- ------------------------------
procedure Test_Add_Route_With_EL (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : aliased Test_Bean;
begin
Add_Route (T, Router, "/users/#{user.id}", 1, Bean);
Add_Route (T, Router, "/users/view.html", 2, Bean);
Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean);
Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean);
-- Verify that the path parameters are injected in the 'user' bean (= T.Bean).
Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean);
T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_EL;
P_1 : aliased constant String := "/list/index.html";
P_2 : aliased constant String := "/users/:id";
P_3 : aliased constant String := "/users/:id/view";
P_4 : aliased constant String := "/users/index.html";
P_5 : aliased constant String := "/users/:id/:name";
P_6 : aliased constant String := "/users/:id/:name/view.html";
P_7 : aliased constant String := "/users/:id/list";
P_8 : aliased constant String := "/users/test.html";
P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html";
P_10 : aliased constant String := "/admin/*.html";
P_11 : aliased constant String := "/admin/*.png";
P_12 : aliased constant String := "/admin/*.jpg";
P_13 : aliased constant String := "/users/:id/page/*.xml";
P_14 : aliased constant String := "/*.jsf";
type Const_String_Access is access constant String;
type String_Array is array (Positive range <>) of Const_String_Access;
Path_Array : constant String_Array :=
(P_1'Access, P_2'Access, P_3'Access, P_4'Access,
P_5'Access, P_6'Access, P_7'Access, P_8'Access,
P_9'Access, P_10'Access, P_11'Access, P_12'Access,
P_13'Access, P_14'Access);
-- ------------------------------
-- Test the Iterate over several paths.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
procedure Process (Pattern : in String;
Route : in Route_Type_Access) is
begin
T.Assert (Route /= null, "The route is null for " & Pattern);
T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern);
Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index));
T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all,
"Invalid route for " & Pattern);
end Process;
begin
for I in Path_Array'Range loop
Add_Route (T, Router, Path_Array (I).all, I, Bean);
end loop;
Router.Iterate (Process'Access);
end Test_Iterate;
end ASF.Routes.Tests;
|
-----------------------------------------------------------------------
-- asf-routes-tests - Unit tests for ASF.Routes
-- 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.Measures;
with Util.Log.Loggers;
with Util.Test_Caller;
with EL.Contexts.Default;
package body ASF.Routes.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests");
package Caller is new Util.Test_Caller (Test, "Routes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)",
Test_Add_Route_With_Path'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)",
Test_Add_Route_With_Param'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)",
Test_Add_Route_With_Ext'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)",
Test_Add_Route_With_EL'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Iterate",
Test_Iterate'Access);
end Add_Tests;
overriding
function Get_Value (Bean : in Test_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return Util.Beans.Objects.To_Object (Bean.Id);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (Bean.Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
overriding
procedure Set_Value (Bean : in out Test_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" then
Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "name" then
Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
begin
T.Bean := new Test_Bean;
ASF.Tests.EL_Test (T).Set_Up;
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"),
Util.Beans.Objects.To_Object (T.Bean.all'Access));
for I in T.Routes'Range loop
T.Routes (I).Index := I;
end loop;
end Set_Up;
-- ------------------------------
-- Verify that the path matches the given route.
-- ------------------------------
procedure Verify_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
Route : constant Route_Type_Access := T.Routes (Index)'Unchecked_Access;
R : Route_Context_Type;
begin
Router.Find_Route (Path, R);
declare
P : constant String := Get_Path_Info (R);
begin
T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path);
T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path);
T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path);
-- Inject the path parameters in the bean instance.
Inject_Parameters (R, Bean, T.ELContext.all);
end;
end Verify_Route;
-- ------------------------------
-- Add the route associted with the path pattern.
-- ------------------------------
procedure Add_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
Route : constant Route_Type_Access := T.Routes (Index)'Unchecked_Access;
begin
Router.Add_Route (Path, Route, T.ELContext.all);
Verify_Route (T, Router, Path, Index, Bean);
end Add_Route;
-- ------------------------------
-- Test the Add_Route with simple fixed path components.
-- Example: /list/index.html
-- ------------------------------
procedure Test_Add_Route_With_Path (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/page.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
Verify_Route (T, Router, "/list/index.html", 3, Bean);
end Test_Add_Route_With_Path;
-- ------------------------------
-- Test the Add_Route with extension mapping.
-- Example: /list/*.html
-- ------------------------------
procedure Test_Add_Route_With_Ext (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/*.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean);
Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean);
Add_Route (T, Router, "/view/page/content/*.html", 6, Bean);
-- Verify precedence and wildcard matching.
Verify_Route (T, Router, "/list/index.html", 3, Bean);
Verify_Route (T, Router, "/list/admin.html", 2, Bean);
Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean);
Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean);
end Test_Add_Route_With_Ext;
-- ------------------------------
-- Test the Add_Route with fixed path components and path parameters.
-- Example: /users/:id/view.html
-- ------------------------------
procedure Test_Add_Route_With_Param (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/users/:id/view.html", 1, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/list.html", 2, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/index.html", 3, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path");
Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name");
Add_Route (T, Router, "/users/list/index.html", 8, Bean);
Verify_Route (T, Router, "/users/1234/view.html", 1, Bean);
T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id");
Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean);
T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_Param;
-- ------------------------------
-- Test the Add_Route with fixed path components and EL path injection.
-- Example: /users/#{user.id}/view.html
-- ------------------------------
procedure Test_Add_Route_With_EL (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : aliased Test_Bean;
begin
Add_Route (T, Router, "/users/#{user.id}", 1, Bean);
Add_Route (T, Router, "/users/view.html", 2, Bean);
Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean);
Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean);
-- Verify that the path parameters are injected in the 'user' bean (= T.Bean).
Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean);
T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_EL;
P_1 : aliased constant String := "/list/index.html";
P_2 : aliased constant String := "/users/:id";
P_3 : aliased constant String := "/users/:id/view";
P_4 : aliased constant String := "/users/index.html";
P_5 : aliased constant String := "/users/:id/:name";
P_6 : aliased constant String := "/users/:id/:name/view.html";
P_7 : aliased constant String := "/users/:id/list";
P_8 : aliased constant String := "/users/test.html";
P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html";
P_10 : aliased constant String := "/admin/*.html";
P_11 : aliased constant String := "/admin/*.png";
P_12 : aliased constant String := "/admin/*.jpg";
P_13 : aliased constant String := "/users/:id/page/*.xml";
P_14 : aliased constant String := "/*.jsf";
type Const_String_Access is access constant String;
type String_Array is array (Positive range <>) of Const_String_Access;
Path_Array : constant String_Array :=
(P_1'Access, P_2'Access, P_3'Access, P_4'Access,
P_5'Access, P_6'Access, P_7'Access, P_8'Access,
P_9'Access, P_10'Access, P_11'Access, P_12'Access,
P_13'Access, P_14'Access);
-- ------------------------------
-- Test the Iterate over several paths.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
procedure Process (Pattern : in String;
Route : in Route_Type_Access) is
begin
T.Assert (Route /= null, "The route is null for " & Pattern);
T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern);
Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index));
T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all,
"Invalid route for " & Pattern);
end Process;
begin
for I in Path_Array'Range loop
Add_Route (T, Router, Path_Array (I).all, I, Bean);
end loop;
Router.Iterate (Process'Access);
declare
R : Route_Context_Type;
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.html", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (fixed path)");
end;
declare
R : Route_Context_Type;
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (extension)");
end;
end Test_Iterate;
end ASF.Routes.Tests;
|
Add some performance tests for the ASF.Routes
|
Add some performance tests for the ASF.Routes
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
6857c1b9aee2caeef57a94885806ae805cdc07a9
|
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, 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;
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
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.
-- -----------------------
overriding
procedure Initialize (Stream : in out Encoder_Stream;
Output : access Output_Stream'Class;
Size : in Positive) is
begin
Util.Streams.Buffered.Output_Buffer_Stream (Stream).Initialize (Output, Size);
end Initialize;
-- -----------------------
-- Close the sink.
-- -----------------------
overriding
procedure Close (Stream : in out Encoder_Stream) is
begin
Stream.Flush;
Stream.Output.Close;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Encoder_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;
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 Encoder_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;
Output_Buffer_Stream (Stream).Flush;
end Flush;
end Util.Streams.Buffered.Encoders;
|
Change the package to a generic package Fix the Write and Flush operations
|
Change the package to a generic package
Fix the Write and Flush operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
35d9b8bbb78efadaac78a186a6d6d70b8fb6f60e
|
awa/src/awa-commands-info.adb
|
awa/src/awa-commands-info.adb
|
-----------------------------------------------------------------------
-- akt-commands-info -- Info command to describe the current configuration
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body AWA.Commands.Info is
use type AWA.Modules.Module_Access;
-- ------------------------------
-- Print the configuration identified by the given name.
-- ------------------------------
procedure Print (Command : in out Command_Type;
Name : in String;
Value : in String;
Default : in String;
Context : in out Context_Type) is
pragma Unreferenced (Default);
Pos : Natural;
begin
Context.Console.Start_Row;
Context.Console.Print_Field (1, Name);
Pos := Value'First;
while Pos <= Value'Last loop
if Value'Last - Pos > Command.Value_Length then
Context.Console.Print_Field (2, Value (Pos .. Pos + Command.Value_Length - 1));
Pos := Pos + Command.Value_Length;
Context.Console.End_Row;
Context.Console.Start_Row;
Context.Console.Print_Field (1, "");
else
Context.Console.Print_Field (2, Value (Pos .. Value'Last));
Pos := Pos + Value'Length;
end if;
end loop;
Context.Console.End_Row;
end Print;
procedure Print (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Application.Get_Init_Parameter (Name, Default);
begin
Command.Print (Name, Value, Default, Context);
end Print;
procedure Print (Command : in out Command_Type;
Module : in AWA.Modules.Module'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Module.Get_Config (Name, Default);
begin
Command.Print (Module.Get_Name & "." & Name, Value, Default, Context);
end Print;
-- ------------------------------
-- Print the configuration about the application.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Args);
Module : AWA.Modules.Module_Access;
begin
if Command.Long_List then
Command.Value_Length := Natural'Last;
end if;
Application.Load_Bundle (Name => "commands",
Locale => "en",
Bundle => Command.Bundle);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Database configuration");
Context.Console.Notice (N_INFO, "----------------------");
Command.Print (Application, "database", "", Context);
Command.Print (Application, "ado.queries.paths", "", Context);
Command.Print (Application, "ado.queries.load", "", Context);
Command.Print (Application, "ado.drivers.load", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Server faces configuration");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "view.dir",
ASF.Applications.DEF_VIEW_DIR, Context);
Command.Print (Application, "view.escape_unknown_tags",
ASF.Applications.DEF_ESCAPE_UNKNOWN_TAGS, Context);
Command.Print (Application, "view.ext",
ASF.Applications.DEF_VIEW_EXT, Context);
Command.Print (Application, "view.file_ext",
ASF.Applications.DEF_VIEW_FILE_EXT, Context);
Command.Print (Application, "view.ignore_spaces",
ASF.Applications.DEF_IGNORE_WHITE_SPACES, Context);
Command.Print (Application, "view.ignore_empty_lines",
ASF.Applications.DEF_IGNORE_EMPTY_LINES, Context);
Command.Print (Application, "view.static.dir",
ASF.Applications.DEF_STATIC_DIR, Context);
Command.Print (Application, "bundle.dir", "bundles", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "AWA Application");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "app_name", "", Context);
Command.Print (Application, "app_search_dirs", ".", Context);
Command.Print (Application, "app.modules.dir", "", Context);
Command.Print (Application, "app_url_base", "", Context);
Command.Print (Application, "awa_url_host", "", Context);
Command.Print (Application, "awa_url_port", "", Context);
Command.Print (Application, "awa_url_scheme", "", Context);
Command.Print (Application, "app.config", "awa.xml", Context);
Command.Print (Application, "app.config.plugins", "", Context);
Command.Print (Application, "contextPath", "", Context);
Command.Print (Application, "awa_dispatcher_count", "", Context);
Command.Print (Application, "awa_dispatcher_priority", "", Context);
Module := Application.Find_Module ("users");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Users Module");
Context.Console.Notice (N_INFO, "------------");
Command.Print (Application, "openid.realm", "", Context);
Command.Print (Application, "openid.callback_url", "", Context);
Command.Print (Application, "openid.success_url", "", Context);
Command.Print (Application, "auth.url.orange", "", Context);
Command.Print (Application, "auth.provider.orange", "", Context);
Command.Print (Application, "auth.url.yahoo", "", Context);
Command.Print (Application, "auth.provider.yahoo", "", Context);
Command.Print (Application, "auth.url.google", "", Context);
Command.Print (Application, "auth.provider.google", "", Context);
Command.Print (Application, "auth.url.facebook", "", Context);
Command.Print (Application, "auth.provider.facebook", "", Context);
Command.Print (Application, "auth.url.google-plus", "", Context);
Command.Print (Application, "auth.provider.google-plus", "", Context);
Command.Print (Application, "facebook.callback_url", "", Context);
Command.Print (Application, "facebook.request_url", "", Context);
Command.Print (Application, "facebook.scope", "", Context);
Command.Print (Application, "facebook.client_id", "", Context);
Command.Print (Application, "facebook.secret", "", Context);
Command.Print (Application, "google-plus.issuer", "", Context);
Command.Print (Application, "google-plus.callback_url", "", Context);
Command.Print (Application, "google-plus.request_url", "", Context);
Command.Print (Application, "google-plus.scope", "", Context);
Command.Print (Application, "google-plus.client_id", "", Context);
Command.Print (Application, "google-plus.secret", "", Context);
Command.Print (Application, "auth-filter.redirect", "", Context);
Command.Print (Application, "verify-filter.redirect", "", Context);
Command.Print (Application, "users.auth_key", "", Context);
Command.Print (Application, "users.server_id", "", Context);
end if;
Module := Application.Find_Module ("mail");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Mail Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Application, "mail.smtp.host", "", Context);
Command.Print (Application, "mail.smtp.port", "", Context);
Command.Print (Application, "mail.smtp.enable", "true", Context);
Command.Print (Application, "mail.mailer", "smtp", Context);
Command.Print (Application, "mail.file.maildir", "mail", Context);
Command.Print (Application, "app_mail_name", "", Context);
Command.Print (Application, "app_mail_from", "", Context);
end if;
Module := Application.Find_Module ("workspaces");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Workspace Module");
Context.Console.Notice (N_INFO, "----------------");
Command.Print (Module.all, "permissions_list", "", Context);
Command.Print (Module.all, "allow_workspace_create", "", Context);
end if;
Module := Application.Find_Module ("storages");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Storage Module");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Module.all, "database_max_size", "100000", Context);
Command.Print (Module.all, "storage_root", "storage", Context);
Command.Print (Module.all, "tmp_storage_root", "tmp", Context);
Module := Application.Find_Module ("images");
if Module /= null then
Command.Print (Module.all, "thumbnail_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("wikis");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Wiki Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Module.all, "image_prefix", "", Context);
Command.Print (Module.all, "page_prefix", "", Context);
Command.Print (Module.all, "wiki_copy_list", "", Context);
Module := Application.Find_Module ("wiki_previews");
if Module /= null then
Command.Print (Module.all, "wiki_preview_tmp", "tmp", Context);
Command.Print (Module.all, "wiki_preview_dir", "web/preview", Context);
Command.Print (Module.all, "wiki_preview_template", "", Context);
Command.Print (Module.all, "wiki_preview_html", "", Context);
Command.Print (Module.all, "wiki_preview_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("counters");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Counter Module");
Context.Console.Notice (N_INFO, "--------------");
Command.Print (Module.all, "counter_age_limit", "300", Context);
Command.Print (Module.all, "counter_limit", "1000", Context);
end if;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Config,
Usage => Command.Get_Name & " [arguments]",
Help => Command.Get_Description);
Command_Drivers.Application_Command_Type (Command).Setup (Config, Context);
GC.Define_Switch (Config => Config,
Output => Command.Long_List'Access,
Switch => "-l",
Long_Switch => "--long-lines",
Help => -("Use long lines to print configuration values"));
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command, Context);
begin
null;
end Help;
begin
Command_Drivers.Driver.Add_Command ("info",
-("report configuration information"),
Command'Access);
end AWA.Commands.Info;
|
-----------------------------------------------------------------------
-- akt-commands-info -- Info command to describe the current configuration
-- Copyright (C) 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body AWA.Commands.Info is
use type AWA.Modules.Module_Access;
-- ------------------------------
-- Print the configuration identified by the given name.
-- ------------------------------
procedure Print (Command : in out Command_Type;
Name : in String;
Value : in String;
Default : in String;
Context : in out Context_Type) is
pragma Unreferenced (Default);
Pos : Natural;
begin
Context.Console.Start_Row;
Context.Console.Print_Field (1, Name);
Pos := Value'First;
while Pos <= Value'Last loop
if Value'Last - Pos > Command.Value_Length then
Context.Console.Print_Field (2, Value (Pos .. Pos + Command.Value_Length - 1));
Pos := Pos + Command.Value_Length;
Context.Console.End_Row;
Context.Console.Start_Row;
Context.Console.Print_Field (1, "");
else
Context.Console.Print_Field (2, Value (Pos .. Value'Last));
Pos := Pos + Value'Length;
end if;
end loop;
Context.Console.End_Row;
end Print;
procedure Print (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Application.Get_Init_Parameter (Name, Default);
begin
Command.Print (Name, Value, Default, Context);
end Print;
procedure Print (Command : in out Command_Type;
Module : in AWA.Modules.Module'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Module.Get_Config (Name, Default);
begin
Command.Print (Module.Get_Name & "." & Name, Value, Default, Context);
end Print;
-- ------------------------------
-- Print the configuration about the application.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Args);
Module : AWA.Modules.Module_Access;
begin
if Command.Long_List then
Command.Value_Length := Natural'Last;
end if;
Application.Load_Bundle (Name => "commands",
Locale => "en",
Bundle => Command.Bundle);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Database configuration");
Context.Console.Notice (N_INFO, "----------------------");
Command.Print (Application, "database", "", Context);
Command.Print (Application, "ado.queries.paths", "", Context);
Command.Print (Application, "ado.queries.load", "", Context);
Command.Print (Application, "ado.drivers.load", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Server faces configuration");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "view.dir",
ASF.Applications.DEF_VIEW_DIR, Context);
Command.Print (Application, "view.escape_unknown_tags",
ASF.Applications.DEF_ESCAPE_UNKNOWN_TAGS, Context);
Command.Print (Application, "view.ext",
ASF.Applications.DEF_VIEW_EXT, Context);
Command.Print (Application, "view.file_ext",
ASF.Applications.DEF_VIEW_FILE_EXT, Context);
Command.Print (Application, "view.ignore_spaces",
ASF.Applications.DEF_IGNORE_WHITE_SPACES, Context);
Command.Print (Application, "view.ignore_empty_lines",
ASF.Applications.DEF_IGNORE_EMPTY_LINES, Context);
Command.Print (Application, "view.static.dir",
ASF.Applications.DEF_STATIC_DIR, Context);
Command.Print (Application, "bundle.dir", "bundles", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "AWA Application");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "app_name", "", Context);
Command.Print (Application, "app_search_dirs", ".", Context);
Command.Print (Application, "app.modules.dir", "", Context);
Command.Print (Application, "app_url_base", "", Context);
Command.Print (Application, "awa_url_host", "", Context);
Command.Print (Application, "awa_url_port", "", Context);
Command.Print (Application, "awa_url_scheme", "", Context);
Command.Print (Application, "app.config", "awa.xml", Context);
Command.Print (Application, "app.config.plugins", "", Context);
Command.Print (Application, "contextPath", "", Context);
Command.Print (Application, "awa_dispatcher_count", "", Context);
Command.Print (Application, "awa_dispatcher_priority", "", Context);
Module := Application.Find_Module ("users");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Users Module");
Context.Console.Notice (N_INFO, "------------");
Command.Print (Application, "app_login_register", "", Context);
Command.Print (Application, "app_login_email", "", Context);
Command.Print (Application, "app_login_openid", "", Context);
Command.Print (Application, "app_login_methods", "", Context);
Command.Print (Application, "openid.realm", "", Context);
Command.Print (Application, "openid.callback_url", "", Context);
Command.Print (Application, "openid.success_url", "", Context);
Command.Print (Application, "auth.url.orange", "", Context);
Command.Print (Application, "auth.provider.orange", "", Context);
Command.Print (Application, "auth.url.yahoo", "", Context);
Command.Print (Application, "auth.provider.yahoo", "", Context);
Command.Print (Application, "auth.url.google", "", Context);
Command.Print (Application, "auth.provider.google", "", Context);
Command.Print (Application, "auth.url.facebook", "", Context);
Command.Print (Application, "auth.provider.facebook", "", Context);
Command.Print (Application, "auth.url.google-plus", "", Context);
Command.Print (Application, "auth.provider.google-plus", "", Context);
Command.Print (Application, "facebook.callback_url", "", Context);
Command.Print (Application, "facebook.request_url", "", Context);
Command.Print (Application, "facebook.scope", "", Context);
Command.Print (Application, "facebook.client_id", "", Context);
Command.Print (Application, "facebook.secret", "", Context);
Command.Print (Application, "google-plus.issuer", "", Context);
Command.Print (Application, "google-plus.callback_url", "", Context);
Command.Print (Application, "google-plus.request_url", "", Context);
Command.Print (Application, "google-plus.scope", "", Context);
Command.Print (Application, "google-plus.client_id", "", Context);
Command.Print (Application, "google-plus.secret", "", Context);
Command.Print (Application, "auth-filter.redirect", "", Context);
Command.Print (Application, "verify-filter.redirect", "", Context);
Command.Print (Application, "users.auth_key", "", Context);
Command.Print (Application, "users.server_id", "", Context);
end if;
Module := Application.Find_Module ("mail");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Mail Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Application, "mail.smtp.host", "", Context);
Command.Print (Application, "mail.smtp.port", "", Context);
Command.Print (Application, "mail.smtp.enable", "true", Context);
Command.Print (Application, "mail.mailer", "smtp", Context);
Command.Print (Application, "mail.file.maildir", "mail", Context);
Command.Print (Application, "app_mail_name", "", Context);
Command.Print (Application, "app_mail_from", "", Context);
end if;
Module := Application.Find_Module ("workspaces");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Workspace Module");
Context.Console.Notice (N_INFO, "----------------");
Command.Print (Module.all, "permissions_list", "", Context);
Command.Print (Module.all, "allow_workspace_create", "", Context);
end if;
Module := Application.Find_Module ("storages");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Storage Module");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Module.all, "database_max_size", "100000", Context);
Command.Print (Module.all, "storage_root", "storage", Context);
Command.Print (Module.all, "tmp_storage_root", "tmp", Context);
Module := Application.Find_Module ("images");
if Module /= null then
Command.Print (Module.all, "thumbnail_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("wikis");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Wiki Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Module.all, "image_prefix", "", Context);
Command.Print (Module.all, "page_prefix", "", Context);
Command.Print (Module.all, "wiki_copy_list", "", Context);
Module := Application.Find_Module ("wiki_previews");
if Module /= null then
Command.Print (Module.all, "wiki_preview_tmp", "tmp", Context);
Command.Print (Module.all, "wiki_preview_dir", "web/preview", Context);
Command.Print (Module.all, "wiki_preview_template", "", Context);
Command.Print (Module.all, "wiki_preview_html", "", Context);
Command.Print (Module.all, "wiki_preview_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("counters");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Counter Module");
Context.Console.Notice (N_INFO, "--------------");
Command.Print (Module.all, "counter_age_limit", "300", Context);
Command.Print (Module.all, "counter_limit", "1000", Context);
end if;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Config,
Usage => Command.Get_Name & " [arguments]",
Help => Command.Get_Description);
Command_Drivers.Application_Command_Type (Command).Setup (Config, Context);
GC.Define_Switch (Config => Config,
Output => Command.Long_List'Access,
Switch => "-l",
Long_Switch => "--long-lines",
Help => -("Use long lines to print configuration values"));
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command, Context);
begin
null;
end Help;
begin
Command_Drivers.Driver.Add_Command ("info",
-("report configuration information"),
Command'Access);
end AWA.Commands.Info;
|
Add information about app_login_* parameters
|
Add information about app_login_* parameters
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f1769af1e477c0876993b072f102f90fbc5e15cc
|
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
|
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
|
-----------------------------------------------------------------------
-- awa-storages-services-tests -- Unit tests for 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.Streams;
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Storages.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Storages.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save",
Test_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete",
Test_Delete_Storage'Access);
end Add_Tests;
-- ------------------------------
-- Save something in a storage element and keep track of the store id in the test <b>Id</b>.
-- ------------------------------
procedure Save (T : in out Test) is
Store : AWA.Storages.Models.Storage_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Save (Into => Store,
Path => "Makefile");
T.Assert (not Store.Is_Null, "Storage object should not be null");
T.Id := Store.Get_Id;
T.Assert (T.Id > 0, "Invalid storage identifier");
end Save;
-- ------------------------------
-- Load the storage element refered to by the test <b>Id</b>.
-- ------------------------------
procedure Load (T : in out Test) is
use type Ada.Streams.Stream_Element_Offset;
Data : ADO.Blob_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Load (From => T.Id, Into => Data);
T.Assert (not Data.Is_Null, "Null blob returned by load");
T.Assert (Data.Value.Len > 100, "Invalid length for the blob data");
end Load;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Load;
end Test_Create_Storage;
-- ------------------------------
-- Test deletion of a storage object
-- ------------------------------
procedure Test_Delete_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Data : ADO.Blob_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Manager.Delete (T.Id);
T.Manager.Load (From => T.Id, Into => Data);
T.Assert (Data.Is_Null, "A non null blob returned by load");
end Test_Delete_Storage;
end AWA.Storages.Services.Tests;
|
-----------------------------------------------------------------------
-- awa-storages-services-tests -- Unit tests for 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.Streams;
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Storages.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Storages.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save",
Test_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete",
Test_Delete_Storage'Access);
end Add_Tests;
-- ------------------------------
-- Save something in a storage element and keep track of the store id in the test <b>Id</b>.
-- ------------------------------
procedure Save (T : in out Test) is
Store : AWA.Storages.Models.Storage_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Save (Into => Store,
Path => "Makefile",
Storage => AWA.Storages.Models.DATABASE);
T.Assert (not Store.Is_Null, "Storage object should not be null");
T.Id := Store.Get_Id;
T.Assert (T.Id > 0, "Invalid storage identifier");
end Save;
-- ------------------------------
-- Load the storage element refered to by the test <b>Id</b>.
-- ------------------------------
procedure Load (T : in out Test) is
use type Ada.Streams.Stream_Element_Offset;
Data : ADO.Blob_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Load (From => T.Id, Into => Data);
T.Assert (not Data.Is_Null, "Null blob returned by load");
T.Assert (Data.Value.Len > 100, "Invalid length for the blob data");
end Load;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Load;
end Test_Create_Storage;
-- ------------------------------
-- Test deletion of a storage object
-- ------------------------------
procedure Test_Delete_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Data : ADO.Blob_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Manager.Delete (T.Id);
T.Manager.Load (From => T.Id, Into => Data);
T.Assert (Data.Is_Null, "A non null blob returned by load");
end Test_Delete_Storage;
end AWA.Storages.Services.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
73182da427e12390ff8c9333889fad0624cce552
|
src/ado.ads
|
src/ado.ads
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Ada.Calendar;
with Util.Refs;
with Util.Nullables;
package ADO is
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
DEFAULT_TIME : constant Ada.Calendar.Time;
-- ------------------------------
-- Database Identifier
-- ------------------------------
--
type Identifier is range -2**47 .. 2**47 - 1;
NO_IDENTIFIER : constant Identifier := -1;
type Entity_Type is range 0 .. 2**16 - 1;
NO_ENTITY_TYPE : constant Entity_Type := 0;
type Object_Id is record
Id : Identifier;
Kind : Entity_Type;
end record;
pragma Pack (Object_Id);
-- ------------------------------
-- Nullable Types
-- ------------------------------
-- Most database allow to store a NULL instead of an actual integer, date or string value.
-- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value.
-- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null
-- or not.
-- An integer which can be null.
subtype Nullable_Integer is Util.Nullables.Nullable_Integer;
function "=" (Left, Right : in Nullable_Integer) return Boolean
renames Util.Nullables."=";
Null_Integer : constant Nullable_Integer;
-- A string which can be null.
subtype Nullable_String is Util.Nullables.Nullable_String;
Null_String : constant Nullable_String;
-- A date which can be null.
subtype Nullable_Time is Util.Nullables.Nullable_Time;
Null_Time : constant Nullable_Time;
-- Return True if the two nullable times are identical (both null or both same time).
function "=" (Left, Right : in Nullable_Time) return Boolean;
type Nullable_Entity_Type is record
Value : Entity_Type := 0;
Is_Null : Boolean := True;
end record;
Null_Entity_Type : constant Nullable_Entity_Type;
-- ------------------------------
-- Blob data type
-- ------------------------------
-- The <b>Blob</b> type is used to represent database blobs. The data is stored
-- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member.
-- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents
-- a reference to the blob data. This is intended to minimize data copy.
type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record
Data : Ada.Streams.Stream_Element_Array (1 .. Len);
end record;
type Blob_Access is access all Blob;
package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access);
subtype Blob_Ref is Blob_References.Ref;
-- Create a blob with an allocated buffer of <b>Size</b> bytes.
function Create_Blob (Size : in Natural) return Blob_Ref;
-- Create a blob initialized with the given data buffer.
function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref;
-- Create a blob initialized with the content from the file whose path is <b>Path</b>.
-- Raises an IO exception if the file does not exist.
function Create_Blob (Path : in String) return Blob_Ref;
-- Return a null blob.
function Null_Blob return Blob_Ref;
private
DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901,
Month => 1,
Day => 2,
Seconds => 0.0);
Null_Integer : constant Nullable_Integer
:= Nullable_Integer '(Is_Null => True,
Value => 0);
Null_String : constant Nullable_String
:= Nullable_String '(Is_Null => True,
Value => Ada.Strings.Unbounded.Null_Unbounded_String);
Null_Time : constant Nullable_Time
:= Nullable_Time '(Is_Null => True,
Value => DEFAULT_TIME);
Null_Entity_Type : constant Nullable_Entity_Type
:= Nullable_Entity_Type '(Is_Null => True,
Value => 0);
end ADO;
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Ada.Calendar;
with Util.Refs;
with Util.Nullables;
package ADO is
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
DEFAULT_TIME : constant Ada.Calendar.Time;
-- ------------------------------
-- Database Identifier
-- ------------------------------
--
type Identifier is range -2**47 .. 2**47 - 1;
NO_IDENTIFIER : constant Identifier := -1;
type Entity_Type is range 0 .. 2**16 - 1;
NO_ENTITY_TYPE : constant Entity_Type := 0;
type Object_Id is record
Id : Identifier;
Kind : Entity_Type;
end record;
pragma Pack (Object_Id);
-- ------------------------------
-- Nullable Types
-- ------------------------------
-- Most database allow to store a NULL instead of an actual integer, date or string value.
-- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value.
-- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null
-- or not.
subtype Nullable_Boolean is Util.Nullables.Nullable_Boolean;
function "=" (Left, Right : in Nullable_Boolean) return Boolean
renames Util.Nullables."=";
Null_Boolean : constant Nullable_Boolean;
-- An integer which can be null.
subtype Nullable_Integer is Util.Nullables.Nullable_Integer;
function "=" (Left, Right : in Nullable_Integer) return Boolean
renames Util.Nullables."=";
Null_Integer : constant Nullable_Integer;
-- A string which can be null.
subtype Nullable_String is Util.Nullables.Nullable_String;
Null_String : constant Nullable_String;
-- A date which can be null.
subtype Nullable_Time is Util.Nullables.Nullable_Time;
Null_Time : constant Nullable_Time;
-- Return True if the two nullable times are identical (both null or both same time).
function "=" (Left, Right : in Nullable_Time) return Boolean;
type Nullable_Entity_Type is record
Value : Entity_Type := 0;
Is_Null : Boolean := True;
end record;
Null_Entity_Type : constant Nullable_Entity_Type;
-- ------------------------------
-- Blob data type
-- ------------------------------
-- The <b>Blob</b> type is used to represent database blobs. The data is stored
-- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member.
-- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents
-- a reference to the blob data. This is intended to minimize data copy.
type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record
Data : Ada.Streams.Stream_Element_Array (1 .. Len);
end record;
type Blob_Access is access all Blob;
package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access);
subtype Blob_Ref is Blob_References.Ref;
-- Create a blob with an allocated buffer of <b>Size</b> bytes.
function Create_Blob (Size : in Natural) return Blob_Ref;
-- Create a blob initialized with the given data buffer.
function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref;
-- Create a blob initialized with the content from the file whose path is <b>Path</b>.
-- Raises an IO exception if the file does not exist.
function Create_Blob (Path : in String) return Blob_Ref;
-- Return a null blob.
function Null_Blob return Blob_Ref;
private
DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901,
Month => 1,
Day => 2,
Seconds => 0.0);
Null_Boolean : constant Nullable_Boolean
:= Nullable_Boolean '(Is_Null => True,
Value => False);
Null_Integer : constant Nullable_Integer
:= Nullable_Integer '(Is_Null => True,
Value => 0);
Null_String : constant Nullable_String
:= Nullable_String '(Is_Null => True,
Value => Ada.Strings.Unbounded.Null_Unbounded_String);
Null_Time : constant Nullable_Time
:= Nullable_Time '(Is_Null => True,
Value => DEFAULT_TIME);
Null_Entity_Type : constant Nullable_Entity_Type
:= Nullable_Entity_Type '(Is_Null => True,
Value => 0);
end ADO;
|
Declare Null_Boolean and Nullable_Boolean type
|
Declare Null_Boolean and Nullable_Boolean type
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
6bdd357bd0b3ffa0fd72fd15b5bc8635ce03056f
|
src/aws/asf-requests-web.adb
|
src/aws/asf-requests-web.adb
|
-----------------------------------------------------------------------
-- asf.requests -- ASF Requests
-- 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 AWS.Attachments.Extend;
with ASF.Parts.Web;
package body ASF.Requests.Web is
function Get_Parameter (R : Request; Name : String) return String is
begin
return AWS.Status.Parameter (R.Data.all, Name);
end Get_Parameter;
-- ------------------------------
-- Set the AWS data received to initialize the request object.
-- ------------------------------
procedure Set_Request (Req : in out Request;
Data : access AWS.Status.Data) is
begin
Req.Data := Data;
Req.Headers := AWS.Status.Header (Data.all);
end Set_Request;
-- ------------------------------
-- Returns the name of the HTTP method with which this request was made,
-- for example, GET, POST, or PUT. Same as the value of the CGI variable
-- REQUEST_METHOD.
-- ------------------------------
function Get_Method (Req : in Request) return String is
begin
return AWS.Status.Method (Req.Data.all);
end Get_Method;
-- ------------------------------
-- Returns the name and version of the protocol the request uses in the form
-- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets,
-- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.
-- ------------------------------
function Get_Protocol (Req : in Request) return String is
begin
return AWS.Status.HTTP_Version (Req.Data.all);
end Get_Protocol;
-- ------------------------------
-- Returns the part of this request's URL from the protocol name up to the query
-- string in the first line of the HTTP request. The web container does not decode
-- this String. For example:
-- First line of HTTP request Returned Value
-- POST /some/path.html HTTP/1.1 /some/path.html
-- GET http://foo.bar/a.html HTTP/1.0 /a.html
-- HEAD /xyz?a=b HTTP/1.1 /xyz
-- ------------------------------
function Get_Request_URI (Req : in Request) return String is
begin
return AWS.Status.URI (Req.Data.all);
end Get_Request_URI;
-- ------------------------------
-- 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 request header.
-- ------------------------------
function Get_Header (Req : in Request;
Name : in String) return String is
Values : constant AWS.Headers.VString_Array := AWS.Headers.Get_Values (Req.Headers, Name);
begin
if Values'Length > 0 then
return To_String (Values (Values'First));
else
return "";
end if;
end Get_Header;
-- ------------------------------
-- Iterate over the request headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
Req.Headers.Iterate_Names (Coupler => ", ",
Process => Process);
end Iterate_Headers;
-- ------------------------------
-- Returns all the values of the specified request header as an Enumeration
-- of String objects.
--
-- Some headers, such as Accept-Language can be sent by clients as several headers
-- each with a different value rather than sending the header as a comma
-- separated list.
--
-- If the request did not include any headers of the specified name, this method
-- returns an empty Enumeration. The header name is case insensitive. You can use
-- this method with any request header.
-- ------------------------------
function Get_Headers (Req : in Request;
Name : in String) return String is
begin
return AWS.Headers.Get_Values (Req.Headers, Name);
end Get_Headers;
-- ------------------------------
-- Returns the Internet Protocol (IP) address of the client or last proxy that
-- sent the request. For HTTP servlets, same as the value of the CGI variable
-- REMOTE_ADDR.
-- ------------------------------
function Get_Remote_Addr (Req : in Request) return String is
begin
return AWS.Status.Peername (Req.Data.all);
end Get_Remote_Addr;
-- ------------------------------
-- Get the number of parts included in the request.
-- ------------------------------
function Get_Part_Count (Req : in Request) return Natural is
begin
return AWS.Attachments.Count (AWS.Status.Attachments (Req.Data.all));
end Get_Part_Count;
-- ------------------------------
-- Process the part at the given position and executes the <b>Process</b> operation
-- with the part object.
-- ------------------------------
procedure Process_Part (Req : in out Request;
Position : in Positive;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class)) is
Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all);
begin
ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Position), Process);
end Process_Part;
-- ------------------------------
-- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation
-- with the part object.
-- ------------------------------
procedure Process_Part (Req : in out Request;
Id : in String;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class)) is
procedure Process_Part (E : in AWS.Attachments.Element);
procedure Process_Part (E : in AWS.Attachments.Element) is
Name : constant String := AWS.Attachments.Extend.Get_Name (E);
begin
if Id = Name then
ASF.Parts.Web.Process_Part (E, Process);
end if;
end Process_Part;
Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all);
begin
AWS.Attachments.Iterate (Attachs, Process_Part'Access);
-- ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Id), Process);
end Process_Part;
end ASF.Requests.Web;
|
-----------------------------------------------------------------------
-- asf.requests -- ASF Requests
-- 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 AWS.Attachments.Extend;
with ASF.Parts.Web;
package body ASF.Requests.Web is
function Get_Parameter (R : Request; Name : String) return String is
begin
return AWS.Status.Parameter (R.Data.all, Name);
end Get_Parameter;
-- ------------------------------
-- Set the AWS data received to initialize the request object.
-- ------------------------------
procedure Set_Request (Req : in out Request;
Data : access AWS.Status.Data) is
begin
Req.Data := Data;
Req.Headers := AWS.Status.Header (Data.all);
end Set_Request;
-- ------------------------------
-- Returns the name of the HTTP method with which this request was made,
-- for example, GET, POST, or PUT. Same as the value of the CGI variable
-- REQUEST_METHOD.
-- ------------------------------
function Get_Method (Req : in Request) return String is
begin
return AWS.Status.Method (Req.Data.all);
end Get_Method;
-- ------------------------------
-- Returns the name and version of the protocol the request uses in the form
-- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets,
-- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.
-- ------------------------------
function Get_Protocol (Req : in Request) return String is
begin
return AWS.Status.HTTP_Version (Req.Data.all);
end Get_Protocol;
-- ------------------------------
-- Returns the part of this request's URL from the protocol name up to the query
-- string in the first line of the HTTP request. The web container does not decode
-- this String. For example:
-- First line of HTTP request Returned Value
-- POST /some/path.html HTTP/1.1 /some/path.html
-- GET http://foo.bar/a.html HTTP/1.0 /a.html
-- HEAD /xyz?a=b HTTP/1.1 /xyz
-- ------------------------------
function Get_Request_URI (Req : in Request) return String is
begin
return AWS.Status.URI (Req.Data.all);
end Get_Request_URI;
-- ------------------------------
-- 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 request header.
-- ------------------------------
function Get_Header (Req : in Request;
Name : in String) return String is
Values : constant AWS.Headers.VString_Array := AWS.Headers.Get_Values (Req.Headers, Name);
begin
if Values'Length > 0 then
return To_String (Values (Values'First));
else
return "";
end if;
end Get_Header;
-- ------------------------------
-- Iterate over the request headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
Req.Headers.Iterate_Names (Coupler => ", ",
Process => Process);
end Iterate_Headers;
-- ------------------------------
-- Returns all the values of the specified request header as an Enumeration
-- of String objects.
--
-- Some headers, such as Accept-Language can be sent by clients as several headers
-- each with a different value rather than sending the header as a comma
-- separated list.
--
-- If the request did not include any headers of the specified name, this method
-- returns an empty Enumeration. The header name is case insensitive. You can use
-- this method with any request header.
-- ------------------------------
function Get_Headers (Req : in Request;
Name : in String) return String is
begin
return AWS.Headers.Get_Values (Req.Headers, Name);
end Get_Headers;
-- ------------------------------
-- Returns the Internet Protocol (IP) address of the client or last proxy that
-- sent the request. For HTTP servlets, same as the value of the CGI variable
-- REMOTE_ADDR.
-- ------------------------------
function Get_Remote_Addr (Req : in Request) return String is
begin
return AWS.Status.Peername (Req.Data.all);
end Get_Remote_Addr;
-- ------------------------------
-- Get the number of parts included in the request.
-- ------------------------------
function Get_Part_Count (Req : in Request) return Natural is
begin
return AWS.Attachments.Count (AWS.Status.Attachments (Req.Data.all));
end Get_Part_Count;
-- ------------------------------
-- Process the part at the given position and executes the <b>Process</b> operation
-- with the part object.
-- ------------------------------
procedure Process_Part (Req : in out Request;
Position : in Positive;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class)) is
Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all);
begin
ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Position), Process);
end Process_Part;
-- ------------------------------
-- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation
-- with the part object.
-- ------------------------------
procedure Process_Part (Req : in out Request;
Id : in String;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class)) is
procedure Process_Part (E : in AWS.Attachments.Element);
procedure Process_Part (E : in AWS.Attachments.Element) is
Name : constant String := AWS.Attachments.Extend.Get_Name (E);
begin
if Id = Name then
ASF.Parts.Web.Process_Part (E, Process);
end if;
end Process_Part;
Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all);
begin
AWS.Attachments.Iterate (Attachs, Process_Part'Access);
-- ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Id), Process);
end Process_Part;
end ASF.Requests.Web;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
0a9da8ea45be02cc3a989a54ba39aeaece96fe75
|
src/aws/asf-requests-web.ads
|
src/aws/asf-requests-web.ads
|
-----------------------------------------------------------------------
-- asf.requests -- ASF Requests
-- 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 AWS.Status;
with AWS.Headers;
package ASF.Requests.Web is
type Request is new ASF.Requests.Request with private;
type Request_Access is access all Request'Class;
function Get_Parameter (R : Request; Name : String) return String;
-- Iterate over the request parameters and executes the <b>Process</b> procedure.
procedure Iterate_Parameters (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Set the AWS data received to initialize the request object.
procedure Set_Request (Req : in out Request;
Data : access AWS.Status.Data);
-- Returns the name of the HTTP method with which this request was made,
-- for example, GET, POST, or PUT. Same as the value of the CGI variable
-- REQUEST_METHOD.
function Get_Method (Req : in Request) return String;
-- Returns the name and version of the protocol the request uses in the form
-- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets,
-- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.
function Get_Protocol (Req : in Request) return String;
-- Returns the part of this request's URL from the protocol name up to the query
-- string in the first line of the HTTP request. The web container does not decode
-- this String. For example:
-- First line of HTTP request Returned Value
-- POST /some/path.html HTTP/1.1 /some/path.html
-- GET http://foo.bar/a.html HTTP/1.0 /a.html
-- HEAD /xyz?a=b HTTP/1.1 /xyz
function Get_Request_URI (Req : in Request) return String;
-- 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 request header.
function Get_Header (Req : in Request;
Name : in String) return String;
-- Returns all the values of the specified request header as an Enumeration
-- of String objects.
--
-- Some headers, such as Accept-Language can be sent by clients as several headers
-- each with a different value rather than sending the header as a comma
-- separated list.
--
-- If the request did not include any headers of the specified name, this method
-- returns an empty Enumeration. The header name is case insensitive. You can use
-- this method with any request header.
function Get_Headers (Req : in Request;
Name : in String) return String;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
procedure Iterate_Headers (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Returns the Internet Protocol (IP) address of the client or last proxy that
-- sent the request. For HTTP servlets, same as the value of the CGI variable
-- REMOTE_ADDR.
function Get_Remote_Addr (Req : in Request) return String;
-- Get the number of parts included in the request.
function Get_Part_Count (Req : in Request) return Natural;
-- Process the part at the given position and executes the <b>Process</b> operation
-- with the part object.
procedure Process_Part (Req : in out Request;
Position : in Positive;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class));
-- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation
-- with the part object.
procedure Process_Part (Req : in out Request;
Id : in String;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class));
private
type Request is new ASF.Requests.Request with record
Data : access AWS.Status.Data;
Headers : AWS.Headers.List;
end record;
end ASF.Requests.Web;
|
-----------------------------------------------------------------------
-- asf.requests -- ASF Requests
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with AWS.Status;
with AWS.Headers;
with Util.Streams;
with ASF.Streams;
package ASF.Requests.Web is
type Request is new ASF.Requests.Request and Util.Streams.Input_Stream with private;
type Request_Access is access all Request'Class;
function Get_Parameter (R : Request; Name : String) return String;
-- Iterate over the request parameters and executes the <b>Process</b> procedure.
procedure Iterate_Parameters (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Set the AWS data received to initialize the request object.
procedure Set_Request (Req : in out Request;
Data : access AWS.Status.Data);
-- Returns the name of the HTTP method with which this request was made,
-- for example, GET, POST, or PUT. Same as the value of the CGI variable
-- REQUEST_METHOD.
function Get_Method (Req : in Request) return String;
-- Returns the name and version of the protocol the request uses in the form
-- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets,
-- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.
function Get_Protocol (Req : in Request) return String;
-- Returns the part of this request's URL from the protocol name up to the query
-- string in the first line of the HTTP request. The web container does not decode
-- this String. For example:
-- First line of HTTP request Returned Value
-- POST /some/path.html HTTP/1.1 /some/path.html
-- GET http://foo.bar/a.html HTTP/1.0 /a.html
-- HEAD /xyz?a=b HTTP/1.1 /xyz
function Get_Request_URI (Req : in Request) return String;
-- 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 request header.
function Get_Header (Req : in Request;
Name : in String) return String;
-- Returns all the values of the specified request header as an Enumeration
-- of String objects.
--
-- Some headers, such as Accept-Language can be sent by clients as several headers
-- each with a different value rather than sending the header as a comma
-- separated list.
--
-- If the request did not include any headers of the specified name, this method
-- returns an empty Enumeration. The header name is case insensitive. You can use
-- this method with any request header.
function Get_Headers (Req : in Request;
Name : in String) return String;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
procedure Iterate_Headers (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Returns the Internet Protocol (IP) address of the client or last proxy that
-- sent the request. For HTTP servlets, same as the value of the CGI variable
-- REMOTE_ADDR.
function Get_Remote_Addr (Req : in Request) return String;
-- Get the number of parts included in the request.
function Get_Part_Count (Req : in Request) return Natural;
-- Process the part at the given position and executes the <b>Process</b> operation
-- with the part object.
procedure Process_Part (Req : in out Request;
Position : in Positive;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class));
-- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation
-- with the part object.
procedure Process_Part (Req : in out Request;
Id : in String;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class));
-- 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 Request;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
overriding
function Create_Input_Stream (Req : in Request) return ASF.Streams.Input_Stream_Access;
private
type Request is new ASF.Requests.Request and Util.Streams.Input_Stream with record
Data : access AWS.Status.Data;
Headers : AWS.Headers.List;
end record;
end ASF.Requests.Web;
|
Add support for the request to read the request body - Implement the Input_Stream interface to give access to the request body - Define the Read procedure to read the request body - Define the Create_Input_Stream function to create the input stream instance
|
Add support for the request to read the request body
- Implement the Input_Stream interface to give access to the request body
- Define the Read procedure to read the request body
- Define the Create_Input_Stream function to create the input stream instance
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
841d842307ace325a89f72bc638e091bb9303db2
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new ASF.Servlets.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Done : Boolean := False;
pragma Atomic (Done);
pragma Volatile (Done);
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and exit the setup.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- 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;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
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.Strings.Unbounded;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new ASF.Servlets.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Db_Host : Util.Beans.Objects.Object;
Db_Port : Util.Beans.Objects.Object;
Has_Error : Boolean := False;
Done : Boolean := False;
pragma Atomic (Done);
pragma Volatile (Done);
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Validate the database configuration parameters.
procedure Validate (From : in out Application);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and exit the setup.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- 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;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
end AWA.Setup.Applications;
|
Declare the Validate procedure and add a Db_Host, Db_Port member to the application
|
Declare the Validate procedure and add a Db_Host, Db_Port member to the application
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7687fc25e07ec827c3923cfb2af0ee793add371b
|
awa/plugins/awa-tags/src/awa-tags-components.ads
|
awa/plugins/awa-tags/src/awa-tags-components.ads
|
-----------------------------------------------------------------------
-- awa-tags-components -- Tags component
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Strings.Vectors;
with EL.Expressions;
with ASF.Components.Html.Forms;
with ASF.Contexts.Faces;
with ASF.Contexts.Writer;
with ASF.Events.Faces;
with ASF.Factory;
-- == Tags Component ==
--
-- === Displaying a list of tags ===
-- The <tt>awa:tagList</tt> component displays a list of tags. Each tag can be rendered as
-- a link if the <tt>tagLink</tt> attribute is defined. The list of tags is passed in the
-- <tt>value</tt> attribute. When rending that list, the <tt>var</tt> attribute is used to
-- setup a variable with the tag value. The <tt>tagLink</tt> attribute is then evaluated
-- against that variable and the result defines the link.
--
-- <awa:tagList value='#{questionList.tags}' id='qtags' styleClass="tagedit-list"
-- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}"
-- var="tagName"
-- tagClass="tagedit-listelement tagedit-listelement-old"/>
--
-- === Tag editing ===
-- The <tt>awa:tagList</tt> component allows to add or remove tags associated with a given
-- database entity. The tag management works with the jQuery plugin <b>Tagedit</b>. For this,
-- the page must include the <b>/js/jquery.tagedit.js</b> Javascript resource.
--
-- The tag edition is active only if the <tt>awa:tagList</tt> component is placed within an
-- <tt>h:form</tt> component. The <tt>value</tt> attribute defines the list of tags. This must
-- be a <tt>Tag_List_Bean</tt> object.
--
-- <awa:tagList value='#{question.tags}' id='qtags'
-- autoCompleteUrl='#{contextPath}/questions/lists/tag-search.html'/>
--
-- When the form is submitted and validated, the procedure <tt>Set_Added</tt> and
-- <tt>Set_Deleted</tt> are called on the value bean with the list of tags that were
-- added and removed. These operations are called in the <tt>UPDATE_MODEL_VALUES</tt>
-- phase (ie, before calling the action's bean operation).
--
package AWA.Tags.Components is
use ASF.Contexts.Writer;
-- Get the Tags component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
-- ------------------------------
-- Input component
-- ------------------------------
-- The AWA input component overrides the ASF input component to build a compact component
-- that displays a label, the input field and the associated error message if necessary.
--
-- The generated HTML looks like:
--
-- <ul class='taglist'>
-- <li><span>tag</span></li>
-- </ul>
--
-- or
--
-- <input type='text' name='' value='tag'/>
--
type Tag_UIInput is new ASF.Components.Html.Forms.UIInput with record
-- List of tags that have been added.
Added : Util.Strings.Vectors.Vector;
-- List of tags that have been removed.
Deleted : Util.Strings.Vectors.Vector;
-- True if the submitted values are correct.
Is_Valid : Boolean := False;
end record;
type Tag_UIInput_Access is access all Tag_UIInput'Class;
-- Returns True if the tag component must be rendered as readonly.
function Is_Readonly (UI : in Tag_UIInput;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean;
-- Get the tag after convertion with the optional converter.
function Get_Tag (UI : in Tag_UIInput;
Tag : in Util.Beans.Objects.Object;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String;
-- Render the tag as a readonly item.
procedure Render_Readonly_Tag (UI : in Tag_UIInput;
Tag : in Util.Beans.Objects.Object;
Class : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the tag as a link.
procedure Render_Link_Tag (UI : in Tag_UIInput;
Name : in String;
Tag : in Util.Beans.Objects.Object;
Link : in EL.Expressions.Expression;
Class : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the tag for an input form.
procedure Render_Form_Tag (UI : in Tag_UIInput;
Id : in String;
Tag : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- a link is rendered for each tag. Otherwise, each tag is rendered as a <tt>span</tt>.
procedure Render_Readonly (UI : in Tag_UIInput;
List : in Util.Beans.Basic.List_Bean_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the list of tags for a form.
procedure Render_Form (UI : in Tag_UIInput;
List : in Util.Beans.Basic.List_Bean_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the javascript to enable the tag edition.
procedure Render_Script (UI : in Tag_UIInput;
Id : in String;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
overriding
procedure Encode_Begin (UI : in Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Get the action method expression to invoke if the command is pressed.
function Get_Action_Expression (UI : in Tag_UIInput;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return EL.Expressions.Method_Expression;
-- Decode any new state of the specified component from the request contained
-- in the specified context and store that state on the component.
--
-- During decoding, events may be enqueued for later processing
-- (by event listeners that have registered an interest), by calling
-- the <b>Queue_Event</b> on the associated component.
overriding
procedure Process_Decodes (UI : in out Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Perform the component tree processing required by the <b>Update Model Values</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows.
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Updates/b> of all facets and children.
-- <ul>
overriding
procedure Process_Updates (UI : in out Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
overriding
procedure Broadcast (UI : in out Tag_UIInput;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end AWA.Tags.Components;
|
-----------------------------------------------------------------------
-- awa-tags-components -- Tags component
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Strings.Vectors;
with EL.Expressions;
with ASF.Components.Html.Forms;
with ASF.Contexts.Faces;
with ASF.Contexts.Writer;
with ASF.Events.Faces;
with ASF.Factory;
with AWA.Tags.Models;
-- == Tags Component ==
--
-- === Displaying a list of tags ===
-- The <tt>awa:tagList</tt> component displays a list of tags. Each tag can be rendered as
-- a link if the <tt>tagLink</tt> attribute is defined. The list of tags is passed in the
-- <tt>value</tt> attribute. When rending that list, the <tt>var</tt> attribute is used to
-- setup a variable with the tag value. The <tt>tagLink</tt> attribute is then evaluated
-- against that variable and the result defines the link.
--
-- <awa:tagList value='#{questionList.tags}' id='qtags' styleClass="tagedit-list"
-- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}"
-- var="tagName"
-- tagClass="tagedit-listelement tagedit-listelement-old"/>
--
-- === Tag editing ===
-- The <tt>awa:tagList</tt> component allows to add or remove tags associated with a given
-- database entity. The tag management works with the jQuery plugin <b>Tagedit</b>. For this,
-- the page must include the <b>/js/jquery.tagedit.js</b> Javascript resource.
--
-- The tag edition is active only if the <tt>awa:tagList</tt> component is placed within an
-- <tt>h:form</tt> component. The <tt>value</tt> attribute defines the list of tags. This must
-- be a <tt>Tag_List_Bean</tt> object.
--
-- <awa:tagList value='#{question.tags}' id='qtags'
-- autoCompleteUrl='#{contextPath}/questions/lists/tag-search.html'/>
--
-- When the form is submitted and validated, the procedure <tt>Set_Added</tt> and
-- <tt>Set_Deleted</tt> are called on the value bean with the list of tags that were
-- added and removed. These operations are called in the <tt>UPDATE_MODEL_VALUES</tt>
-- phase (ie, before calling the action's bean operation).
--
-- === Tag cloud ===
-- The <tt>awa:tagCloud</tt> component displays a list of tags as a tag cloud.
-- The tags list passed in the <tt>value</tt> attribute must inherit from the
-- <tt>Tag_Info_List_Bean</tt> type which indicates for each tag the number of
-- times it is used.
--
-- <awa:tagCloud value='#{questionTagList}' id='cloud' styleClass="tag-cloud"
-- var="tagName" rows="30"
-- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}"
-- tagClass="tag-link"/>
--
package AWA.Tags.Components is
use ASF.Contexts.Writer;
-- Get the Tags component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
-- ------------------------------
-- Input component
-- ------------------------------
-- The AWA input component overrides the ASF input component to build a compact component
-- that displays a label, the input field and the associated error message if necessary.
--
-- The generated HTML looks like:
--
-- <ul class='taglist'>
-- <li><span>tag</span></li>
-- </ul>
--
-- or
--
-- <input type='text' name='' value='tag'/>
--
type Tag_UIInput is new ASF.Components.Html.Forms.UIInput with record
-- List of tags that have been added.
Added : Util.Strings.Vectors.Vector;
-- List of tags that have been removed.
Deleted : Util.Strings.Vectors.Vector;
-- True if the submitted values are correct.
Is_Valid : Boolean := False;
end record;
type Tag_UIInput_Access is access all Tag_UIInput'Class;
-- Returns True if the tag component must be rendered as readonly.
function Is_Readonly (UI : in Tag_UIInput;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean;
-- Get the tag after convertion with the optional converter.
function Get_Tag (UI : in Tag_UIInput;
Tag : in Util.Beans.Objects.Object;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String;
-- Render the tag as a readonly item.
procedure Render_Readonly_Tag (UI : in Tag_UIInput;
Tag : in Util.Beans.Objects.Object;
Class : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the tag as a link.
procedure Render_Link_Tag (UI : in Tag_UIInput;
Name : in String;
Tag : in Util.Beans.Objects.Object;
Link : in EL.Expressions.Expression;
Class : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the tag for an input form.
procedure Render_Form_Tag (UI : in Tag_UIInput;
Id : in String;
Tag : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- a link is rendered for each tag. Otherwise, each tag is rendered as a <tt>span</tt>.
procedure Render_Readonly (UI : in Tag_UIInput;
List : in Util.Beans.Basic.List_Bean_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the list of tags for a form.
procedure Render_Form (UI : in Tag_UIInput;
List : in Util.Beans.Basic.List_Bean_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the javascript to enable the tag edition.
procedure Render_Script (UI : in Tag_UIInput;
Id : in String;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
overriding
procedure Encode_Begin (UI : in Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Get the action method expression to invoke if the command is pressed.
function Get_Action_Expression (UI : in Tag_UIInput;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return EL.Expressions.Method_Expression;
-- Decode any new state of the specified component from the request contained
-- in the specified context and store that state on the component.
--
-- During decoding, events may be enqueued for later processing
-- (by event listeners that have registered an interest), by calling
-- the <b>Queue_Event</b> on the associated component.
overriding
procedure Process_Decodes (UI : in out Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Perform the component tree processing required by the <b>Update Model Values</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows.
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Updates/b> of all facets and children.
-- <ul>
overriding
procedure Process_Updates (UI : in out Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
overriding
procedure Broadcast (UI : in out Tag_UIInput;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Tag Cloud Component
-- ------------------------------
-- The tag cloud component
type Tag_UICloud is new ASF.Components.Html.UIHtmlComponent with null record;
type Tag_Info_Array is array (Positive range <>) of AWA.Tags.Models.Tag_Info;
type Tag_Info_Array_Access is access all Tag_Info_Array;
-- Render the tag cloud component.
overriding
procedure Encode_Children (UI : in Tag_UICloud;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the list of tags. If the <tt>tagLink</tt> attribute is defined, a link
-- is rendered for each tag.
procedure Render_Cloud (UI : in Tag_UICloud;
List : in Tag_Info_Array;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end AWA.Tags.Components;
|
Define the <awa:tagCloud> component to render a list of tags as a cloud
|
Define the <awa:tagCloud> component to render a list of tags as a cloud
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
2ac963b269bda0d0820f5dd39bd78db886e5f968
|
src/gen-artifacts-query.adb
|
src/gen-artifacts-query.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-query -- Query artifact for Code Generator
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Directories;
with Gen.Configs;
with Gen.Utils;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Gen.Model.Mappings;
with Gen.Model.Operations;
with Util.Log.Loggers;
with Util.Encoders.HMAC.SHA1;
-- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of
-- data structures returned by queries.
package body Gen.Artifacts.Query is
use Ada.Strings.Unbounded;
use Gen.Model;
use Gen.Model.Tables;
use Gen.Model.Queries;
use Gen.Configs;
use type DOM.Core.Node;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- 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.
-- ------------------------------
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) is
procedure Register_Sort (Query : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Sorts (Query : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node);
procedure Register_Columns (Table : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Operation (Table : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Operations (Table : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition;
Node : in DOM.Core.Node);
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition;
Node : in DOM.Core.Node);
Hash : Unbounded_String;
-- ------------------------------
-- Register the method definition in the table
-- ------------------------------
procedure Register_Operation (Table : in out Query_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name");
Operation : Gen.Model.Operations.Operation_Definition_Access;
Param : Gen.Model.Operations.Parameter_Definition_Access;
begin
Table.Add_Operation (Name, Operation);
Operation.Add_Parameter (To_Unbounded_String ("Outcome"),
To_Unbounded_String ("String"),
Param);
end Register_Operation;
-- ------------------------------
-- Register all the operations defined in the table
-- ------------------------------
procedure Register_Operations (Table : in out Query_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Operation);
begin
Log.Debug ("Register operations from bean {0}", Table.Name);
Iterate (Table, Node, "method");
end Register_Operations;
-- ------------------------------
-- Register the column definition in the table
-- ------------------------------
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name");
C : Column_Definition_Access;
begin
Table.Add_Column (Name, C);
C.Initialize (Name, Column);
C.Type_Name := To_Unbounded_String (Gen.Utils.Get_Normalized_Type (Column, "type"));
C.Is_Inserted := False;
C.Is_Updated := Gen.Utils.Get_Attribute (Column, "update", True);
C.Not_Null := Gen.Utils.Get_Attribute (Column, "not-null", True);
C.Unique := False;
-- Construct the hash for this column mapping.
Append (Hash, ",type=");
Append (Hash, C.Type_Name);
Append (Hash, ",name=");
Append (Hash, Name);
end Register_Column;
-- ------------------------------
-- Register all the columns defined in the table
-- ------------------------------
procedure Register_Columns (Table : in out Query_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Column);
begin
Log.Debug ("Register columns from query {0}", Table.Name);
Iterate (Table, Node, "property");
end Register_Columns;
-- ------------------------------
-- Register the sort definition in the query
-- ------------------------------
procedure Register_Sort (Query : in out Query_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name");
Sql : constant String := Gen.Utils.Get_Data_Content (Node);
begin
Query.Add_Sort (Name, To_Unbounded_String (Sql));
end Register_Sort;
-- ------------------------------
-- Register all the sort modes defined in the query
-- ------------------------------
procedure Register_Sorts (Query : in out Query_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Sort);
begin
Log.Debug ("Register sorts from query {0}", Query.Name);
Iterate (Query, Node, "order");
end Register_Sorts;
-- ------------------------------
-- Register a new class definition in the model.
-- ------------------------------
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name");
begin
Query.Initialize (Name, Node);
Query.Set_Table_Name (To_String (Name));
if Name /= "" then
Query.Set_Name (Name);
else
Query.Set_Name (Gen.Utils.Get_Query_Name (Path));
end if;
-- Construct the hash for this column mapping.
Append (Hash, "class=");
Append (Hash, Query.Name);
Query.Is_Serializable := Gen.Utils.Get_Attribute (Node, "serializable", False);
Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name);
Register_Columns (Query_Definition (Query), Node);
Register_Operations (Query_Definition (Query), Node);
end Register_Mapping;
-- ------------------------------
-- Register a new query.
-- ------------------------------
procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name");
C : Gen.Model.Queries.Query_Definition_Access;
begin
Query.Add_Query (Name, C);
Register_Sorts (Query_Definition (C.all), Node);
end Register_Query;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate_Mapping is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition,
Process => Register_Mapping);
procedure Iterate_Query is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition,
Process => Register_Query);
Table : constant Query_File_Definition_Access := new Query_File_Definition;
Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package");
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table");
begin
Table.Initialize (Name, Node);
Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path));
Table.Pkg_Name := Pkg;
Iterate_Mapping (Query_File_Definition (Table.all), Node, "class");
Iterate_Query (Query_File_Definition (Table.all), Node, "query");
if Length (Table.Pkg_Name) = 0 then
Context.Error ("Missing or empty package attribute");
else
Model.Register_Query (Table);
end if;
Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash));
Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries",
Data => To_String (Hash));
end Register_Mapping;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
begin
Log.Debug ("Initializing query artifact for the configuration");
Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context);
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping");
end Initialize;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
begin
Log.Debug ("Preparing the model for query");
if Model.Has_Packages then
Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
end if;
end Prepare;
end Gen.Artifacts.Query;
|
-----------------------------------------------------------------------
-- gen-artifacts-query -- Query artifact for Code Generator
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Directories;
with Gen.Configs;
with Gen.Utils;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Gen.Model.Mappings;
with Gen.Model.Operations;
with Util.Log.Loggers;
with Util.Encoders.HMAC.SHA1;
-- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of
-- data structures returned by queries.
package body Gen.Artifacts.Query is
use Ada.Strings.Unbounded;
use Gen.Model;
use Gen.Model.Tables;
use Gen.Model.Queries;
use Gen.Configs;
use type DOM.Core.Node;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- 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.
-- ------------------------------
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) is
procedure Register_Sort (Query : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Sorts (Query : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node);
procedure Register_Columns (Table : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Operation (Table : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Operations (Table : in out Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition;
Node : in DOM.Core.Node);
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition;
Node : in DOM.Core.Node);
Hash : Unbounded_String;
-- ------------------------------
-- Register the method definition in the table
-- ------------------------------
procedure Register_Operation (Table : in out Query_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name");
Operation : Gen.Model.Operations.Operation_Definition_Access;
Param : Gen.Model.Operations.Parameter_Definition_Access;
begin
Table.Add_Operation (Name, Operation);
Operation.Add_Parameter (To_Unbounded_String ("Outcome"),
To_Unbounded_String ("String"),
Param);
end Register_Operation;
-- ------------------------------
-- Register all the operations defined in the table
-- ------------------------------
procedure Register_Operations (Table : in out Query_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Operation);
begin
Log.Debug ("Register operations from bean {0}", Table.Name);
Iterate (Table, Node, "method");
end Register_Operations;
-- ------------------------------
-- Register the column definition in the table
-- ------------------------------
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name");
C : Column_Definition_Access;
begin
Table.Add_Column (Name, C);
C.Initialize (Name, Column);
C.Set_Type (Gen.Utils.Get_Normalized_Type (Column, "type"));
C.Is_Inserted := False;
C.Is_Updated := Gen.Utils.Get_Attribute (Column, "update", True);
C.Not_Null := Gen.Utils.Get_Attribute (Column, "not-null", True);
C.Unique := False;
-- Construct the hash for this column mapping.
Append (Hash, ",type=");
Append (Hash, C.Type_Name);
Append (Hash, ",name=");
Append (Hash, Name);
end Register_Column;
-- ------------------------------
-- Register all the columns defined in the table
-- ------------------------------
procedure Register_Columns (Table : in out Query_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Column);
begin
Log.Debug ("Register columns from query {0}", Table.Name);
Iterate (Table, Node, "property");
end Register_Columns;
-- ------------------------------
-- Register the sort definition in the query
-- ------------------------------
procedure Register_Sort (Query : in out Query_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name");
Sql : constant String := Gen.Utils.Get_Data_Content (Node);
begin
Query.Add_Sort (Name, To_Unbounded_String (Sql));
end Register_Sort;
-- ------------------------------
-- Register all the sort modes defined in the query
-- ------------------------------
procedure Register_Sorts (Query : in out Query_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Sort);
begin
Log.Debug ("Register sorts from query {0}", Query.Name);
Iterate (Query, Node, "order");
end Register_Sorts;
-- ------------------------------
-- Register a new class definition in the model.
-- ------------------------------
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name");
begin
Query.Initialize (Name, Node);
Query.Set_Table_Name (To_String (Name));
if Name /= "" then
Query.Set_Name (Name);
else
Query.Set_Name (Gen.Utils.Get_Query_Name (Path));
end if;
-- Construct the hash for this column mapping.
Append (Hash, "class=");
Append (Hash, Query.Name);
Query.Is_Serializable := Gen.Utils.Get_Attribute (Node, "serializable", False);
Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name);
Register_Columns (Query_Definition (Query), Node);
Register_Operations (Query_Definition (Query), Node);
end Register_Mapping;
-- ------------------------------
-- Register a new query.
-- ------------------------------
procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name");
C : Gen.Model.Queries.Query_Definition_Access;
begin
Query.Add_Query (Name, C);
Register_Sorts (Query_Definition (C.all), Node);
end Register_Query;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate_Mapping is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition,
Process => Register_Mapping);
procedure Iterate_Query is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition,
Process => Register_Query);
Table : constant Query_File_Definition_Access := new Query_File_Definition;
Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package");
Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table");
begin
Table.Initialize (Name, Node);
Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path));
Table.Pkg_Name := Pkg;
Iterate_Mapping (Query_File_Definition (Table.all), Node, "class");
Iterate_Query (Query_File_Definition (Table.all), Node, "query");
if Length (Table.Pkg_Name) = 0 then
Context.Error ("Missing or empty package attribute");
else
Model.Register_Query (Table);
end if;
Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash));
Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries",
Data => To_String (Hash));
end Register_Mapping;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
begin
Log.Debug ("Initializing query artifact for the configuration");
Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context);
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping");
end Initialize;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
begin
Log.Debug ("Preparing the model for query");
if Model.Has_Packages then
Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE,
Mapping => Gen.Model.Mappings.ADA_MAPPING);
end if;
end Prepare;
end Gen.Artifacts.Query;
|
Use the Set_Type procedure to setup the column type
|
Use the Set_Type procedure to setup the column type
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
26479a31c31281a528f603d841588109cca57ef9
|
awa/src/awa-users-filters.ads
|
awa/src/awa-users-filters.ads
|
-----------------------------------------------------------------------
-- awa-users-filters -- Specific filters for authentication and key verification
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Requests;
with ASF.Responses;
with ASF.Sessions;
with ASF.Principals;
with ASF.Filters;
with ASF.Servlets;
with ASF.Security.Filters;
with AWA.Users.Principals;
package AWA.Users.Filters is
-- Set the user principal on the session associated with the ASF request.
procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class;
Principal : in AWA.Users.Principals.Principal_Access);
-- ------------------------------
-- Authentication verification filter
-- ------------------------------
-- The <b>Auth_Filter</b> verifies that the user has the permission to access
-- a given page. If the user is not logged, it tries to login automatically
-- by using some persistent cookie. When this fails, it redirects the
-- user to a login page (configured by AUTH_FILTER_REDIRECT_PARAM property).
type Auth_Filter is new ASF.Security.Filters.Auth_Filter with private;
-- The configuration parameter which controls the redirection page
-- when the user is not logged (this should be the login page).
AUTH_FILTER_REDIRECT_PARAM : constant String := "redirect";
-- A temporary cookie used to store the URL for redirection after the login is successful.
REDIRECT_COOKIE : constant String := "RURL";
-- Initialize the filter and configure the redirection URIs.
overriding
procedure Initialize (Filter : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config);
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
overriding
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access);
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
overriding
procedure Do_Login (Filter : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- ------------------------------
-- Verify access key filter
-- ------------------------------
-- The <b>Verify_Filter</b> filter verifies an access key associated to a user.
-- The access key should have been sent to the user by some mechanism (email).
-- The access key must be valid, that is an <b>Access_Key</b> database entry
-- must exist and it must be associated with an email address and a user.
type Verify_Filter is new ASF.Filters.Filter with private;
-- The request parameter that <b>Verify_Filter</b> will check.
PARAM_ACCESS_KEY : constant String := "key";
-- The configuration parameter which controls the redirection page
-- when the access key is invalid.
VERIFY_FILTER_REDIRECT_PARAM : constant String := "redirect";
-- Initialize the filter and configure the redirection URIs.
procedure Initialize (Filter : in out Verify_Filter;
Config : in ASF.Servlets.Filter_Config);
-- Filter a request which contains an access key and verify that the
-- key is valid and identifies a user. Once the user is known, create
-- a session and setup the user principal.
--
-- If the access key is missing or invalid, redirect to the
-- <b>Invalid_Key_URI</b> associated with the filter.
overriding
procedure Do_Filter (Filter : in Verify_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
private
use Ada.Strings.Unbounded;
type Auth_Filter is new ASF.Security.Filters.Auth_Filter with record
Login_URI : Unbounded_String;
end record;
type Verify_Filter is new ASF.Filters.Filter with record
Invalid_Key_URI : Unbounded_String;
end record;
end AWA.Users.Filters;
|
-----------------------------------------------------------------------
-- awa-users-filters -- Specific filters for authentication and key verification
-- Copyright (C) 2011, 2012, 2015, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Requests;
with ASF.Responses;
with ASF.Sessions;
with ASF.Principals;
with ASF.Filters;
with ASF.Servlets;
with ASF.Security.Filters;
with AWA.Applications;
with AWA.Users.Principals;
package AWA.Users.Filters is
-- Set the user principal on the session associated with the ASF request.
procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class;
Principal : in AWA.Users.Principals.Principal_Access);
-- ------------------------------
-- Authentication verification filter
-- ------------------------------
-- The <b>Auth_Filter</b> verifies that the user has the permission to access
-- a given page. If the user is not logged, it tries to login automatically
-- by using some persistent cookie. When this fails, it redirects the
-- user to a login page (configured by AUTH_FILTER_REDIRECT_PARAM property).
type Auth_Filter is new ASF.Security.Filters.Auth_Filter with private;
-- The configuration parameter which controls the redirection page
-- when the user is not logged (this should be the login page).
AUTH_FILTER_REDIRECT_PARAM : constant String := "redirect";
-- A temporary cookie used to store the URL for redirection after the login is successful.
REDIRECT_COOKIE : constant String := "RURL";
-- Initialize the filter and configure the redirection URIs.
overriding
procedure Initialize (Filter : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config);
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
overriding
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access);
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
overriding
procedure Do_Login (Filter : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- ------------------------------
-- Verify access key filter
-- ------------------------------
-- The <b>Verify_Filter</b> filter verifies an access key associated to a user.
-- The access key should have been sent to the user by some mechanism (email).
-- The access key must be valid, that is an <b>Access_Key</b> database entry
-- must exist and it must be associated with an email address and a user.
type Verify_Filter is new ASF.Filters.Filter with private;
-- The request parameter that <b>Verify_Filter</b> will check.
PARAM_ACCESS_KEY : constant String := "key";
-- The configuration parameter which controls the redirection page
-- when the access key is invalid.
VERIFY_FILTER_REDIRECT_PARAM : constant String := "redirect";
-- Initialize the filter and configure the redirection URIs.
procedure Initialize (Filter : in out Verify_Filter;
Config : in ASF.Servlets.Filter_Config);
-- Filter a request which contains an access key and verify that the
-- key is valid and identifies a user. Once the user is known, create
-- a session and setup the user principal.
--
-- If the access key is missing or invalid, redirect to the
-- <b>Invalid_Key_URI</b> associated with the filter.
overriding
procedure Do_Filter (Filter : in Verify_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
private
use Ada.Strings.Unbounded;
type Auth_Filter is new ASF.Security.Filters.Auth_Filter with record
Login_URI : Unbounded_String;
Application : AWA.Applications.Application_Access;
end record;
type Verify_Filter is new ASF.Filters.Filter with record
Invalid_Key_URI : Unbounded_String;
end record;
end AWA.Users.Filters;
|
Add Application member to the Auth_Filter
|
Add Application member to the Auth_Filter
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
500349ee926b1e0efbf7ea84e300f7d53c0f8bb2
|
awa/plugins/awa-storages/src/awa-storages.ads
|
awa/plugins/awa-storages/src/awa-storages.ads
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Storages</b> module provides a set of storage services allowing an application
-- to store data files, documents, images in a persistent area. The persistent store can
-- be on a file system, in the database or provided by a remote service such as
-- Amazon Simple Storage Service.
--
-- == Creating a storage ==
-- A content in the storage is represented by a `Storage_Ref` instance. The data itself
-- can be physically stored in the file system (`FILE` mode), in the database (`DATABASE`
-- mode) or on a remote server (`URL` mode). To put a file in the storage, first create
-- the storage object instance:
--
-- Data : AWA.Storages.Models.Storage_Ref;
--
-- Then setup the storage mode that you want. The storage service uses this information
-- to save the data in a file, in the database or in a remote service (in the future).
--
-- Data.Set_Storage (AWA.Storages.Models.DATABASE);
--
-- To save a file in the store, we can use the `Save` operation. It will read the file
-- and put in in the corresponding persistent store (the database in this example).
--
-- Service.Save (Data, Path);
--
-- Upon successful completion, the storage instance `Data` will be allocated a unique
-- identifier that can be retrieved by `Get_Id` or `Get_Key`.
--
-- == Ada Beans ==
-- @include storages.xml
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png]
--
-- @include Storages.hbm.xml
package AWA.Storages is
end AWA.Storages;
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Storages</b> module provides a set of storage services allowing an application
-- to store data files, documents, images in a persistent area. The persistent store can
-- be on a file system, in the database or provided by a remote service such as
-- Amazon Simple Storage Service.
--
-- == Creating a storage ==
-- A content in the storage is represented by a `Storage_Ref` instance. The data itself
-- can be physically stored in the file system (`FILE` mode), in the database (`DATABASE`
-- mode) or on a remote server (`URL` mode). To put a file in the storage, first create
-- the storage object instance:
--
-- Data : AWA.Storages.Models.Storage_Ref;
--
-- Then setup the storage mode that you want. The storage service uses this information
-- to save the data in a file, in the database or in a remote service (in the future).
--
-- Data.Set_Storage (Storage => AWA.Storages.Models.DATABASE);
--
-- To save a file in the store, we can use the `Save` operation. It will read the file
-- and put in in the corresponding persistent store (the database in this example).
--
-- Service.Save (Into => Data, Path => Path_To_The_File);
--
-- Upon successful completion, the storage instance `Data` will be allocated a unique
-- identifier that can be retrieved by `Get_Id` or `Get_Key`.
--
-- == Getting the data ==
-- Several operations are defined to retrieve the data. Each of them has been designed
-- to optimize the retrieval and
--
-- * The data can be retrieved in a local file.
-- This mode is useful if an external program must be launched and be able to read
-- the file. If the storage mode of the data is `FILE`, the path of the file on
-- the storage file system is used. For other storage modes, the file is saved
-- in a temporary file. In that case the `Store_Local` database table is used
-- to track such locally saved data.
-- * The data can be returned as a stream.
-- When the application has to read the data, opening a read stream connection is
-- the most efficient mechanism.
--
-- To access the data by using a local file, we must define a local storage reference:
--
-- Data : AWA.Storages.Models.Store_Local_Ref;
--
-- and use the `Load` operation with the storage identifier:
--
-- Service.Load (From => Id, Into => Data);
--
-- Once the load operation succeeded, the data is stored on the file system and
-- the local path is obtained by using the `Get_Path` operation:
--
-- Path : constant String := Data.Get_Path;
--
-- == Ada Beans ==
-- @include storages.xml
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png]
--
-- @include Storages.hbm.xml
package AWA.Storages is
end AWA.Storages;
|
Document how to retrieve the data
|
Document how to retrieve the data
|
Ada
|
apache-2.0
|
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
116037704ae47046cf34d85d5d4e086d02254ea3
|
src/util-encoders-base64.ads
|
src/util-encoders-base64.ads
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in Base64
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Interfaces;
-- The <b>Util.Encodes.Base64</b> packages encodes and decodes streams
-- in Base64 (See rfc4648: The Base16, Base32, and Base64 Data Encodings).
package Util.Encoders.Base64 is
pragma Preelaborate;
-- ------------------------------
-- Base64 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- a Base64 ascii stream.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
procedure Set_URL_Mode (E : in out Encoder;
Mode : in Boolean);
-- Create a base64 encoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
function Create_URL_Encoder return Transformer_Access;
-- ------------------------------
-- Base64 decoder
-- ------------------------------
-- The <b>Decoder</b> decodes a Base64 ascii stream into a binary stream.
type Decoder is new Util.Encoders.Transformer with private;
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
procedure Set_URL_Mode (E : in out Decoder;
Mode : in Boolean);
-- Create a base64 decoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
function Create_URL_Decoder return Transformer_Access;
private
type Alphabet is
array (Interfaces.Unsigned_8 range 0 .. 63) of Ada.Streams.Stream_Element;
type Alphabet_Access is not null access constant Alphabet;
BASE64_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/'));
BASE64_URL_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('-'), Character'Pos ('_'));
type Encoder is new Util.Encoders.Transformer with record
Alphabet : Alphabet_Access := BASE64_ALPHABET'Access;
end record;
type Alphabet_Values is array (Ada.Streams.Stream_Element) of Interfaces.Unsigned_8;
type Alphabet_Values_Access is not null access constant Alphabet_Values;
BASE64_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 36, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('+') => 62, Character'Pos ('/') => 63,
others => 16#FF#);
BASE64_URL_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 36, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('-') => 62, Character'Pos ('_') => 63,
others => 16#FF#);
type Decoder is new Util.Encoders.Transformer with record
Values : Alphabet_Values_Access := BASE64_VALUES'Access;
end record;
end Util.Encoders.Base64;
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in Base64
-- Copyright (C) 2009, 2010, 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Interfaces;
-- The <b>Util.Encodes.Base64</b> packages encodes and decodes streams
-- in Base64 (See rfc4648: The Base16, Base32, and Base64 Data Encodings).
package Util.Encoders.Base64 is
pragma Preelaborate;
-- Encode the 64-bit value to LEB128 and then base64url.
function Encode (Value : in Interfaces.Unsigned_64) return String;
-- Decode the base64url string and then the LEB128 integer.
-- Raise the Encoding_Error if the string is invalid and cannot be decoded.
function Decode (Value : in String) return Interfaces.Unsigned_64;
-- ------------------------------
-- Base64 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- a Base64 ascii stream.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
procedure Set_URL_Mode (E : in out Encoder;
Mode : in Boolean);
-- Create a base64 encoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
function Create_URL_Encoder return Transformer_Access;
-- ------------------------------
-- Base64 decoder
-- ------------------------------
-- The <b>Decoder</b> decodes a Base64 ascii stream into a binary stream.
type Decoder is new Util.Encoders.Transformer with private;
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
procedure Set_URL_Mode (E : in out Decoder;
Mode : in Boolean);
-- Create a base64 decoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
function Create_URL_Decoder return Transformer_Access;
private
type Alphabet is
array (Interfaces.Unsigned_8 range 0 .. 63) of Ada.Streams.Stream_Element;
type Alphabet_Access is not null access constant Alphabet;
BASE64_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/'));
BASE64_URL_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('-'), Character'Pos ('_'));
type Encoder is new Util.Encoders.Transformer with record
Alphabet : Alphabet_Access := BASE64_ALPHABET'Access;
end record;
type Alphabet_Values is array (Ada.Streams.Stream_Element) of Interfaces.Unsigned_8;
type Alphabet_Values_Access is not null access constant Alphabet_Values;
BASE64_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 36, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('+') => 62, Character'Pos ('/') => 63,
others => 16#FF#);
BASE64_URL_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 36, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('-') => 62, Character'Pos ('_') => 63,
others => 16#FF#);
type Decoder is new Util.Encoders.Transformer with record
Values : Alphabet_Values_Access := BASE64_VALUES'Access;
end record;
end Util.Encoders.Base64;
|
Declare the Encode and Decode function for integer <-> string conversion using LEB128 + base64url
|
Declare the Encode and Decode function for integer <-> string conversion
using LEB128 + base64url
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e37d2cc954b15d704d4b7a37da71535b7aadd5c6
|
mat/src/mat-readers-files.ads
|
mat/src/mat-readers-files.ads
|
-----------------------------------------------------------------------
-- mat-readers-files -- Reader for files
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Buffered;
with Util.Streams.Files;
package MAT.Readers.Files is
type File_Reader_Type is new Manager_Base with private;
-- Open the file.
procedure Open (Reader : in out File_Reader_Type;
Path : in String);
procedure Read_All (Reader : in out File_Reader_Type);
private
type File_Reader_Type is new Manager_Base with record
Stream : Util.Streams.Buffered.Buffered_Stream;
File : aliased Util.Streams.Files.File_Stream;
end record;
end MAT.Readers.Files;
|
-----------------------------------------------------------------------
-- mat-readers-files -- Reader for files
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Buffered;
with Util.Streams.Files;
package MAT.Readers.Files is
type File_Reader_Type is new Manager_Base with private;
-- Open the file.
procedure Open (Reader : in out File_Reader_Type;
Path : in String);
procedure Read_All (Reader : in out File_Reader_Type);
private
type File_Reader_Type is new Manager_Base with record
File : aliased Util.Streams.Files.File_Stream;
Stream : Util.Streams.Buffered.Buffered_Stream;
end record;
end MAT.Readers.Files;
|
Fix finalization of File_Reader_Type
|
Fix finalization of File_Reader_Type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
c15b56c64758e8d52edcba42533b07f0fa398b26
|
regtests/util-files-tests.adb
|
regtests/util-files-tests.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/os-none",
Compose_Path ("src;regtests", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
end Util.Files.Tests;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- 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.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File_Missing'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/os-none",
Compose_Path ("src;regtests", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
end Util.Files.Tests;
|
Fix a test case that was not executed
|
Fix a test case that was not executed
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
61cdd5baa47e1d1686326d53e90e039a210998f1
|
src/asm-intrinsic/util-concurrent-counters.adb
|
src/asm-intrinsic/util-concurrent-counters.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 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.
-----------------------------------------------------------------------
package body Util.Concurrent.Counters is
use Interfaces;
function Sync_Add_And_Fetch
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Integer_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Add_And_Fetch,
External_Name => "__sync_add_and_fetch_4");
function Sync_Fetch_And_Add
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Integer_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Fetch_And_Add,
External_Name => "__sync_fetch_and_add_4");
procedure Sync_Add
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Add,
External_Name => "__sync_add_and_fetch_4");
-- ------------------------------
-- Increment the counter atomically.
-- ------------------------------
procedure Increment (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, 1);
end Increment;
-- ------------------------------
-- Increment the counter atomically and return the value before increment.
-- ------------------------------
procedure Increment (C : in out Counter;
Value : out Integer) is
begin
Value := Integer (Sync_Fetch_And_Add (C.Value'Unrestricted_Access, 1));
end Increment;
-- ------------------------------
-- Decrement the counter atomically.
-- ------------------------------
procedure Decrement (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, -1);
end Decrement;
-- ------------------------------
-- Decrement the counter atomically and return a status.
-- ------------------------------
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean) is
Value : Unsigned_32;
begin
Value := Sync_Add_And_Fetch (C.Value'Unrestricted_Access, -1);
Is_Zero := Value /= 0;
end Decrement;
-- ------------------------------
-- Get the counter value
-- ------------------------------
function Value (C : in Counter) return Integer is
begin
return Integer (C.Value);
end Value;
end Util.Concurrent.Counters;
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Concurrent.Counters is
use Interfaces;
function Sync_Add_And_Fetch
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Integer_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Add_And_Fetch,
External_Name => "__sync_add_and_fetch_4");
function Sync_Fetch_And_Add
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Integer_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Fetch_And_Add,
External_Name => "__sync_fetch_and_add_4");
procedure Sync_Add
(Ptr : access Interfaces.Unsigned_32;
Value : Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Add,
External_Name => "__sync_add_and_fetch_4");
-- ------------------------------
-- Increment the counter atomically.
-- ------------------------------
procedure Increment (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, 1);
end Increment;
-- ------------------------------
-- Increment the counter atomically and return the value before increment.
-- ------------------------------
procedure Increment (C : in out Counter;
Value : out Integer) is
begin
Value := Integer (Sync_Fetch_And_Add (C.Value'Unrestricted_Access, 1));
end Increment;
-- ------------------------------
-- Decrement the counter atomically.
-- ------------------------------
procedure Decrement (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, -1);
end Decrement;
-- ------------------------------
-- Decrement the counter atomically and return a status.
-- ------------------------------
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean) is
Value : Unsigned_32;
begin
Value := Sync_Add_And_Fetch (C.Value'Unrestricted_Access, -1);
Is_Zero := Value = 0;
end Decrement;
-- ------------------------------
-- Get the counter value
-- ------------------------------
function Value (C : in Counter) return Integer is
begin
return Integer (C.Value);
end Value;
end Util.Concurrent.Counters;
|
Fix the Is_Zero test
|
Fix the Is_Zero test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e9b341d9b5afdc72244a827afa0264b684bd46f8
|
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;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME, N_EVENT,
N_CONDITION, N_THREAD);
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Thread : MAT.Types.Target_Thread_Ref;
when N_EVENT =>
Min_Event : MAT.Events.Targets.Event_Id_Type;
Max_Event : MAT.Events.Targets.Event_Id_Type;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events.Targets;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE,
INSIDE_DIRECT_FILE,
INSIDE_FUNCTION,
INSIDE_DIRECT_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Create an event ID range expression node.
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type;
-- 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;
|
Declare the Create_Thread function to create a thread id expression node
|
Declare the Create_Thread function to create a thread id expression node
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
d48f44a3e975c77d0c71c60e367a7d38e1d2cae8
|
src/natools-s_expressions-atom_buffers.adb
|
src/natools-s_expressions-atom_buffers.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Atom_Buffers is
procedure Preallocate (Buffer : in out Atom_Buffer; Length : in Count) is
Old_Size, New_Size : Count := 0;
begin
if Buffer.Used + Length <= Buffer.Available then
return;
end if;
Old_Size := Buffer.Available;
New_Size := Buffer.Used + Length;
if Buffer.Ref.Is_Empty then
declare
function Create return Atom;
function Create return Atom is
begin
return Atom'(1 .. New_Size => <>);
end Create;
begin
Buffer.Ref.Replace (Create'Access);
end;
else
declare
function Create return Atom;
Old_Accessor : constant Atom_Refs.Accessor := Buffer.Ref.Query;
function Create return Atom is
begin
return Result : Atom (1 .. New_Size) do
Result (1 .. Old_Size) := Old_Accessor.Data.all;
end return;
end Create;
begin
Buffer.Ref.Replace (Create'Access);
end;
end if;
Buffer.Available := New_Size;
end Preallocate;
procedure Append (Buffer : in out Atom_Buffer; Data : in Atom) is
begin
Preallocate (Buffer, Data'Length);
Buffer.Ref.Update.Data.all (Buffer.Used + 1 .. Buffer.Used + Data'Length)
:= Data;
Buffer.Used := Buffer.Used + Data'Length;
end Append;
procedure Append (Buffer : in out Atom_Buffer; Data : in Octet) is
begin
Preallocate (Buffer, 1);
Buffer.Ref.Update.Data.all (Buffer.Used + 1) := Data;
Buffer.Used := Buffer.Used + 1;
end Append;
function Length (Buffer : Atom_Buffer) return Count is
begin
return Buffer.Used;
end Length;
function Data (Buffer : Atom_Buffer) return Atom is
begin
if Buffer.Ref.Is_Empty then
pragma Assert (Buffer.Available = 0 and Buffer.Used = 0);
return Null_Atom;
else
return Buffer.Ref.Query.Data.all;
end if;
end Data;
function Raw_Query (Buffer : Atom_Buffer) return Atom_Refs.Accessor is
function Create return Atom;
function Create return Atom is
begin
return Null_Atom;
end Create;
begin
if Buffer.Ref.Is_Empty then
return Atom_Refs.Create (Create'Access).Query;
else
return Buffer.Ref.Query;
end if;
end Raw_Query;
procedure Query
(Buffer : in Atom_Buffer;
Process : not null access procedure (Data : in Atom)) is
begin
if Buffer.Ref.Is_Empty then
Process.all (Null_Atom);
else
Buffer.Ref.Query (Process);
end if;
end Query;
procedure Read
(Buffer : in Atom_Buffer;
Data : out Atom;
Length : out Count)
is
Transmit : constant Count := Count'Min (Data'Length, Buffer.Used);
begin
Length := Buffer.Used;
if Buffer.Ref.Is_Empty then
pragma Assert (Length = 0);
null;
else
Data (Data'First .. Data'First + Transmit - 1)
:= Buffer.Ref.Query.Data.all (1 .. Transmit);
end if;
end Read;
function Element (Buffer : Atom_Buffer; Position : Count) return Octet is
begin
return Buffer.Ref.Query.Data.all (Position);
end Element;
procedure Hard_Reset (Buffer : in out Atom_Buffer) is
begin
Buffer.Ref.Reset;
Buffer.Available := 0;
Buffer.Used := 0;
end Hard_Reset;
procedure Soft_Reset (Buffer : in out Atom_Buffer) is
begin
Buffer.Used := 0;
end Soft_Reset;
end Natools.S_Expressions.Atom_Buffers;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Atom_Buffers is
procedure Preallocate (Buffer : in out Atom_Buffer; Length : in Count) is
Old_Size, New_Size : Count := 0;
begin
if Buffer.Used + Length <= Buffer.Available then
return;
end if;
Old_Size := Buffer.Available;
New_Size := Buffer.Used + Length;
if Buffer.Ref.Is_Empty then
declare
function Create return Atom;
function Create return Atom is
begin
return Atom'(1 .. New_Size => <>);
end Create;
begin
Buffer.Ref.Replace (Create'Access);
end;
else
declare
function Create return Atom;
Old_Accessor : constant Atom_Refs.Accessor := Buffer.Ref.Query;
function Create return Atom is
begin
return Result : Atom (1 .. New_Size) do
Result (1 .. Old_Size) := Old_Accessor.Data.all;
end return;
end Create;
begin
Buffer.Ref.Replace (Create'Access);
end;
end if;
Buffer.Available := New_Size;
end Preallocate;
procedure Append (Buffer : in out Atom_Buffer; Data : in Atom) is
begin
Preallocate (Buffer, Data'Length);
Buffer.Ref.Update.Data.all (Buffer.Used + 1 .. Buffer.Used + Data'Length)
:= Data;
Buffer.Used := Buffer.Used + Data'Length;
end Append;
procedure Append (Buffer : in out Atom_Buffer; Data : in Octet) is
begin
Preallocate (Buffer, 1);
Buffer.Ref.Update.Data.all (Buffer.Used + 1) := Data;
Buffer.Used := Buffer.Used + 1;
end Append;
function Length (Buffer : Atom_Buffer) return Count is
begin
return Buffer.Used;
end Length;
function Data (Buffer : Atom_Buffer) return Atom is
begin
if Buffer.Ref.Is_Empty then
pragma Assert (Buffer.Available = 0 and Buffer.Used = 0);
return Null_Atom;
else
return Buffer.Ref.Query.Data.all (1 .. Buffer.Used);
end if;
end Data;
function Raw_Query (Buffer : Atom_Buffer) return Atom_Refs.Accessor is
function Create return Atom;
function Create return Atom is
begin
return Null_Atom;
end Create;
begin
if Buffer.Ref.Is_Empty then
return Atom_Refs.Create (Create'Access).Query;
else
return Buffer.Ref.Query;
end if;
end Raw_Query;
procedure Query
(Buffer : in Atom_Buffer;
Process : not null access procedure (Data : in Atom)) is
begin
if Buffer.Ref.Is_Empty then
Process.all (Null_Atom);
else
Process.all (Buffer.Ref.Query.Data.all (1 .. Buffer.Used));
end if;
end Query;
procedure Read
(Buffer : in Atom_Buffer;
Data : out Atom;
Length : out Count)
is
Transmit : constant Count := Count'Min (Data'Length, Buffer.Used);
begin
Length := Buffer.Used;
if Buffer.Ref.Is_Empty then
pragma Assert (Length = 0);
null;
else
Data (Data'First .. Data'First + Transmit - 1)
:= Buffer.Ref.Query.Data.all (1 .. Transmit);
end if;
end Read;
function Element (Buffer : Atom_Buffer; Position : Count) return Octet is
begin
return Buffer.Ref.Query.Data.all (Position);
end Element;
procedure Hard_Reset (Buffer : in out Atom_Buffer) is
begin
Buffer.Ref.Reset;
Buffer.Available := 0;
Buffer.Used := 0;
end Hard_Reset;
procedure Soft_Reset (Buffer : in out Atom_Buffer) is
begin
Buffer.Used := 0;
end Soft_Reset;
end Natools.S_Expressions.Atom_Buffers;
|
fix accessors to return only used part of the buffer
|
s_expressions-atom_buffers: fix accessors to return only used part of the buffer
|
Ada
|
isc
|
faelys/natools
|
6d1202a3ac1513a16c3f72cb0e0167120b752b2a
|
mat/src/gtk/mat-callbacks.adb
|
mat/src/gtk/mat-callbacks.adb
|
-----------------------------------------------------------------------
-- mat-callbacks - Callbacks for Gtk
-- 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 Gtk.Main;
with Gtk.Widget;
package body MAT.Callbacks is
-- ------------------------------
-- Callback executed when the "quit" action is executed from the menu.
-- ------------------------------
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
begin
Gtk.Main.Main_Quit;
end On_Menu_Quit;
-- ------------------------------
-- Callback executed when the "about" action is executed from the menu.
-- ------------------------------
procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
About : constant Gtk.Widget.Gtk_Widget :=
Gtk.Widget.Gtk_Widget (Object.Get_Object ("about"));
begin
About.Show;
end On_Menu_About;
end MAT.Callbacks;
|
-----------------------------------------------------------------------
-- mat-callbacks - Callbacks for Gtk
-- 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 Gtk.Main;
with Gtk.Widget;
package body MAT.Callbacks is
-- ------------------------------
-- Callback executed when the "quit" action is executed from the menu.
-- ------------------------------
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
begin
Gtk.Main.Main_Quit;
end On_Menu_Quit;
-- ------------------------------
-- Callback executed when the "about" action is executed from the menu.
-- ------------------------------
procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
About : constant Gtk.Widget.Gtk_Widget :=
Gtk.Widget.Gtk_Widget (Object.Get_Object ("about"));
begin
About.Show;
end On_Menu_About;
-- ------------------------------
-- Callback executed when the "close-about" action is executed from the about box.
-- ------------------------------
procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is
About : constant Gtk.Widget.Gtk_Widget :=
Gtk.Widget.Gtk_Widget (Object.Get_Object ("about"));
begin
About.Hide;
end On_Close_About;
end MAT.Callbacks;
|
Implement the On_Close_About procedure
|
Implement the On_Close_About procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
85541b622853270c44477d909aa68720834d144b
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- 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;
with Util.Strings;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with Security.Contexts;
package body AWA.Blogs.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Blogs.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post",
Test_Update_Post'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)",
Test_Admin_List_Posts'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)",
Test_Admin_List_Comments'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the blog as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Post : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html");
ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html");
ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html");
ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist",
Reply, "Blog post missing page is invalid");
if Post = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html");
ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("create-blog", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after blog creation");
declare
Ident : constant String
:= Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id=");
begin
Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident,
"Invalid blog identifier in the response");
T.Blog_Ident := To_Unbounded_String (Ident);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "Post title");
Request.Set_Parameter ("text", "The blog post content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html");
T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident),
"Invalid post identifier in the response");
end;
-- Check public access to the post.
T.Post_Uri := To_Unbounded_String (Uuid);
T.Verify_Anonymous (Uuid);
end Test_Create_Blog;
-- ------------------------------
-- Test updating a post by simulating web requests.
-- ------------------------------
procedure Test_Update_Post (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
Ident : constant String := To_String (T.Blog_Ident);
Post_Ident : Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post-id", To_String (T.Post_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "New post title");
Request.Set_Parameter ("text", "The blog post new content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html");
Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident),
"Invalid post identifier returned after post update");
T.Verify_Anonymous (Uuid);
end Test_Update_Post;
-- ------------------------------
-- Test listing the blog posts.
-- ------------------------------
procedure Test_Admin_List_Posts (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html");
ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid");
end Test_Admin_List_Posts;
-- ------------------------------
-- Test listing the blog comments.
-- ------------------------------
procedure Test_Admin_List_Comments (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident,
"blog-list-comments.html");
ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply,
"Blog admin comments page is invalid");
end Test_Admin_List_Comments;
end AWA.Blogs.Tests;
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- 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;
with Util.Strings;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with Security.Contexts;
package body AWA.Blogs.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Blogs.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post",
Test_Update_Post'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)",
Test_Admin_List_Posts'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)",
Test_Admin_List_Comments'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)",
Test_Admin_Blog_Stats'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the blog as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Post : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html");
ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html");
ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html");
ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist",
Reply, "Blog post missing page is invalid");
if Post = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html");
ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("create-blog", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after blog creation");
declare
Ident : constant String
:= Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id=");
begin
Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident,
"Invalid blog identifier in the response");
T.Blog_Ident := To_Unbounded_String (Ident);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "Post title");
Request.Set_Parameter ("text", "The blog post content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html");
T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident),
"Invalid post identifier in the response");
end;
-- Check public access to the post.
T.Post_Uri := To_Unbounded_String (Uuid);
T.Verify_Anonymous (Uuid);
end Test_Create_Blog;
-- ------------------------------
-- Test updating a post by simulating web requests.
-- ------------------------------
procedure Test_Update_Post (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
Ident : constant String := To_String (T.Blog_Ident);
Post_Ident : Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post-id", To_String (T.Post_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "New post title");
Request.Set_Parameter ("text", "The blog post new content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html");
Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident),
"Invalid post identifier returned after post update");
T.Verify_Anonymous (Uuid);
end Test_Update_Post;
-- ------------------------------
-- Test listing the blog posts.
-- ------------------------------
procedure Test_Admin_List_Posts (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html");
ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid");
end Test_Admin_List_Posts;
-- ------------------------------
-- Test listing the blog comments.
-- ------------------------------
procedure Test_Admin_List_Comments (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident,
"blog-list-comments.html");
ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply,
"Blog admin comments page is invalid");
end Test_Admin_List_Comments;
-- ------------------------------
-- Test getting the JSON blog stats (for graphs).
-- ------------------------------
procedure Test_Admin_Blog_Stats (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats",
"blog-stats.html");
ASF.Tests.Assert_Contains (T, "data", Reply,
"Blog admin stats page is invalid");
end Test_Admin_Blog_Stats;
end AWA.Blogs.Tests;
|
Implement the Test_Admin_Blog_Stats procedure to test the blog stats
|
Implement the Test_Admin_Blog_Stats procedure to test the blog stats
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8c02ae7b956e4417e24f8c416378929c3bec699e
|
regtests/asf-views-facelets-tests.adb
|
regtests/asf-views-facelets-tests.adb
|
-----------------------------------------------------------------------
-- Facelet Tests - Unit tests for ASF.Views.Facelet
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ASF.Contexts.Facelets;
with ASF.Applications.Main;
package body ASF.Views.Facelets.Tests is
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
pragma Unreferenced (Context);
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 Util.Test_Caller (Test, "Views.Facelets");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Facelet'Access);
Caller.Add_Test (Suite, "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, 2011, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with EL.Objects;
with ASF.Converters;
with ASF.Validators;
with ASF.Contexts.Facelets;
package body ASF.Views.Facelets.Tests is
use ASF.Contexts.Facelets;
type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with null record;
-- Get a converter from a name.
-- Returns the converter object or null if there is no converter.
overriding
function Get_Converter (Context : in Facelet_Context;
Name : in EL.Objects.Object)
return ASF.Converters.Converter_Access;
-- Get a validator from a name.
-- Returns the validator object or null if there is no validator.
overriding
function Get_Validator (Context : in Facelet_Context;
Name : in EL.Objects.Object)
return ASF.Validators.Validator_Access;
-- ------------------------------
-- Get a converter from a name.
-- Returns the converter object or null if there is no converter.
-- ------------------------------
overriding
function Get_Converter (Context : in Facelet_Context;
Name : in EL.Objects.Object)
return ASF.Converters.Converter_Access is
pragma Unreferenced (Context, Name);
begin
return null;
end Get_Converter;
-- ------------------------------
-- Get a validator from a name.
-- Returns the validator object or null if there is no validator.
-- ------------------------------
overriding
function Get_Validator (Context : in Facelet_Context;
Name : in EL.Objects.Object)
return ASF.Validators.Validator_Access is
pragma Unreferenced (Context, Name);
begin
return null;
end Get_Validator;
-- ------------------------------
-- 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 Util.Test_Caller (Test, "Views.Facelets");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Facelet'Access);
Caller.Add_Test (Suite, "Test ASF.Views.Facelets.Find_Facelet",
Test_Load_Unknown_Facelet'Access);
end Add_Tests;
end ASF.Views.Facelets.Tests;
|
Fix the unit test to implement the Get_Converter and Get_Validator functions
|
Fix the unit test to implement the Get_Converter and Get_Validator functions
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
5726003013d6f3b07b942f389ed80a423df3ea81
|
orka_transforms/src/orka-transforms-simd_vectors.adb
|
orka_transforms/src/orka-transforms-simd_vectors.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_Vectors is
function "-" (Elements : Point) return Point is
begin
return Result : Point := Point (-Vector4 (Elements)) do
Result (W) := Elements (W);
end return;
end "-";
function "+" (Left, Right : Direction) return Direction is
(Direction (Vector4 (Left) + Vector4 (Right)));
function "+" (Left : Point; Right : Direction) return Point is
(Point (Vector4 (Left) + Vector4 (Right)));
function "+" (Left : Direction; Right : Point) return Point is
(Point (Vector4 (Left) + Vector4 (Right)));
function "-" (Left, Right : Point) return Direction is
(Direction (Vector4 (Left) - Vector4 (Right)));
----------------------------------------------------------------------------
package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type);
function Magnitude2 (Elements : Vector_Type) return Element_Type is
(Sum (Elements * Elements));
function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type is
begin
return (Factor, Factor, Factor, Factor) * Elements;
end "*";
function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type is
(Factor * Elements);
function "*" (Factor : Element_Type; Elements : Direction) return Direction is
(Direction (Factor * Vector4 (Elements)));
function "*" (Elements : Direction; Factor : Element_Type) return Direction is
(Factor * Elements);
function Magnitude (Elements : Vector_Type) return Element_Type is
begin
return EF.Sqrt (Magnitude2 (Elements));
end Magnitude;
function Normalize (Elements : Vector_Type) return Vector_Type is
Length : constant Element_Type := Magnitude (Elements);
begin
return Divide_Or_Zero (Elements, (Length, Length, Length, Length));
end Normalize;
function Normalized (Elements : Vector_Type) return Boolean is
function Is_Equivalent (Expected, Result : Element_Type) return Boolean is
-- Because the square root is not computed, the bounds need
-- to be increased to +/- 2 * Epsilon + Epsilon ** 2. Since
-- Epsilon < 1, we can simply take +/- 3 * Epsilon
Epsilon : constant Element_Type := 3.0 * Element_Type'Model_Epsilon;
begin
return Result in Expected - Epsilon .. Expected + Epsilon;
end Is_Equivalent;
begin
return Is_Equivalent (1.0, Magnitude2 (Elements));
end Normalized;
function Distance (Left, Right : Point) return Element_Type is
(Magnitude (Vector_Type (Left - Right)));
function Projection (Elements, Direction : Vector_Type) return Vector_Type is
Unit_Direction : constant Vector_Type := Normalize (Direction);
begin
-- The dot product gives the magnitude of the projected vector:
-- |A_b| = |A| * cos(theta) = A . U_b
return Dot (Elements, Unit_Direction) * Unit_Direction;
end Projection;
function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type is
(Elements - Projection (Elements, Direction));
function Angle (Left, Right : Vector_Type) return Element_Type is
begin
return EF.Arccos (Dot (Left, Right) / (Magnitude (Left) * Magnitude (Right)));
end Angle;
function Dot (Left, Right : Vector_Type) return Element_Type is
(Sum (Left * Right));
function Slerp
(Left, Right : Vector_Type;
Weight : Element_Type) return Vector_Type
is
Cos_Angle : constant Element_Type := Dot (Left, Right);
Angle : constant Element_Type := EF.Arccos (Cos_Angle);
SA : constant Element_Type := EF.Sin (Angle);
SL : constant Element_Type := EF.Sin ((1.0 - Weight) * Angle);
SR : constant Element_Type := EF.Sin (Weight * Angle);
begin
return (SL / SA) * Left + (SR / SA) * Right;
end Slerp;
end Orka.Transforms.SIMD_Vectors;
|
-- 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_Vectors is
function "-" (Elements : Point) return Point is
Result : Vector4 := -Vector4 (Elements);
begin
Result (W) := Elements (W);
return Point (Result);
end "-";
function "+" (Left, Right : Direction) return Direction is
(Direction (Vector4 (Left) + Vector4 (Right)));
function "+" (Left : Point; Right : Direction) return Point is
(Point (Vector4 (Left) + Vector4 (Right)));
function "+" (Left : Direction; Right : Point) return Point is
(Point (Vector4 (Left) + Vector4 (Right)));
function "-" (Left, Right : Point) return Direction is
(Direction (Vector4 (Left) - Vector4 (Right)));
----------------------------------------------------------------------------
package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type);
function Magnitude2 (Elements : Vector_Type) return Element_Type is
(Sum (Elements * Elements));
function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type is
begin
return (Factor, Factor, Factor, Factor) * Elements;
end "*";
function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type is
(Factor * Elements);
function "*" (Factor : Element_Type; Elements : Direction) return Direction is
(Direction (Factor * Vector4 (Elements)));
function "*" (Elements : Direction; Factor : Element_Type) return Direction is
(Factor * Elements);
function Magnitude (Elements : Vector_Type) return Element_Type is
begin
return EF.Sqrt (Magnitude2 (Elements));
end Magnitude;
function Normalize (Elements : Vector_Type) return Vector_Type is
Length : constant Element_Type := Magnitude (Elements);
begin
return Divide_Or_Zero (Elements, (Length, Length, Length, Length));
end Normalize;
function Normalized (Elements : Vector_Type) return Boolean is
function Is_Equivalent (Expected, Result : Element_Type) return Boolean is
-- Because the square root is not computed, the bounds need
-- to be increased to +/- 2 * Epsilon + Epsilon ** 2. Since
-- Epsilon < 1, we can simply take +/- 3 * Epsilon
Epsilon : constant Element_Type := 3.0 * Element_Type'Model_Epsilon;
begin
return Result in Expected - Epsilon .. Expected + Epsilon;
end Is_Equivalent;
begin
return Is_Equivalent (1.0, Magnitude2 (Elements));
end Normalized;
function Distance (Left, Right : Point) return Element_Type is
(Magnitude (Vector_Type (Left - Right)));
function Projection (Elements, Direction : Vector_Type) return Vector_Type is
Unit_Direction : constant Vector_Type := Normalize (Direction);
begin
-- The dot product gives the magnitude of the projected vector:
-- |A_b| = |A| * cos(theta) = A . U_b
return Dot (Elements, Unit_Direction) * Unit_Direction;
end Projection;
function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type is
(Elements - Projection (Elements, Direction));
function Angle (Left, Right : Vector_Type) return Element_Type is
begin
return EF.Arccos (Dot (Left, Right) / (Magnitude (Left) * Magnitude (Right)));
end Angle;
function Dot (Left, Right : Vector_Type) return Element_Type is
(Sum (Left * Right));
function Slerp
(Left, Right : Vector_Type;
Weight : Element_Type) return Vector_Type
is
Cos_Angle : constant Element_Type := Dot (Left, Right);
Angle : constant Element_Type := EF.Arccos (Cos_Angle);
SA : constant Element_Type := EF.Sin (Angle);
SL : constant Element_Type := EF.Sin ((1.0 - Weight) * Angle);
SR : constant Element_Type := EF.Sin (Weight * Angle);
begin
return (SL / SA) * Left + (SR / SA) * Right;
end Slerp;
end Orka.Transforms.SIMD_Vectors;
|
Fix failure of predicate of type Point in function "-"
|
transforms: Fix failure of predicate of type Point in function "-"
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
9de27e509654edea8a0b0a3fd6010aeccf76b5fc
|
awa/src/awa-converters-dates.adb
|
awa/src/awa-converters-dates.adb
|
-----------------------------------------------------------------------
-- awa-converters-dates -- Date Converters
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Exceptions;
with Ada.Strings.Unbounded;
with Util.Locales;
with Util.Dates.Formats;
with Util.Properties.Bundles;
with Util.Beans.Objects.Time;
with ASF.Locales;
with ASF.Utils;
with ASF.Applications.Main;
package body AWA.Converters.Dates is
ONE_HOUR : constant Duration := 3600.0;
ONE_DAY : constant Duration := 24 * ONE_HOUR;
-- ------------------------------
-- Convert the object value into a string. The object value is associated
-- with the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
overriding
function To_String (Convert : in Relative_Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in Util.Beans.Objects.Object) return String is
Bundle : ASF.Locales.Bundle;
Locale : constant Util.Locales.Locale := Context.Get_Locale;
begin
begin
ASF.Applications.Main.Load_Bundle (Context.Get_Application.all,
Name => "dates",
Locale => Util.Locales.To_String (Locale),
Bundle => Bundle);
exception
when E : Util.Properties.Bundles.NO_BUNDLE =>
Component.Log_Error ("Cannot localize dates: {0}",
Ada.Exceptions.Exception_Message (E));
end;
-- Convert the value as a date here so that we can raise an Invalid_Conversion exception.
declare
use Ada.Calendar;
Date : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value);
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Dt : constant Duration := Now - Date;
Values : ASF.Utils.Object_Array (1 .. 1);
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if Dt < 60.0 then
return Bundle.Get ("date_moment_ago");
elsif Dt < 120.0 then
return Bundle.Get ("date_minute_ago");
elsif Dt < ONE_HOUR then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / 60.0));
ASF.Utils.Formats.Format (Bundle.Get ("date_minutes_ago"),
Values, Result);
elsif Dt < 2 * ONE_HOUR then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / 60.0));
ASF.Utils.Formats.Format (Bundle.Get ("date_hour_ago"),
Values, Result);
elsif Dt < ONE_DAY then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_HOUR));
ASF.Utils.Formats.Format (Bundle.Get ("date_hours_ago"),
Values, Result);
elsif Dt < 2 * ONE_DAY then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_HOUR));
ASF.Utils.Formats.Format (Bundle.Get ("date_day_ago"),
Values, Result);
elsif Dt < 7 * ONE_DAY then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_DAY));
ASF.Utils.Formats.Format (Bundle.Get ("date_days_ago"),
Values, Result);
else
declare
use ASF.Converters.Dates;
Pattern : constant String
:= Date_Converter'Class (Convert).Get_Pattern (Context, Component);
begin
return Util.Dates.Formats.Format (Pattern, Date, Bundle);
end;
end if;
return Ada.Strings.Unbounded.To_String (Result);
end;
exception
when E : others =>
raise ASF.Converters.Invalid_Conversion with Ada.Exceptions.Exception_Message (E);
end To_String;
end AWA.Converters.Dates;
|
-----------------------------------------------------------------------
-- awa-converters-dates -- Date Converters
-- Copyright (C) 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Exceptions;
with Ada.Strings.Unbounded;
with Util.Locales;
with Util.Dates.Formats;
with Util.Properties.Bundles;
with Util.Beans.Objects.Time;
with ASF.Locales;
with ASF.Utils;
with ASF.Applications.Main;
package body AWA.Converters.Dates is
ONE_HOUR : constant Duration := 3600.0;
ONE_DAY : constant Duration := 24 * ONE_HOUR;
-- ------------------------------
-- Convert the object value into a string. The object value is associated
-- with the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
overriding
function To_String (Convert : in Relative_Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in Util.Beans.Objects.Object) return String is
Bundle : ASF.Locales.Bundle;
Locale : constant Util.Locales.Locale := Context.Get_Locale;
begin
begin
ASF.Applications.Main.Load_Bundle (Context.Get_Application.all,
Name => "dates",
Locale => Util.Locales.To_String (Locale),
Bundle => Bundle);
exception
when E : Util.Properties.Bundles.NO_BUNDLE =>
Component.Log_Error ("Cannot localize dates: {0}",
Ada.Exceptions.Exception_Message (E));
end;
-- Convert the value as a date here so that we can raise an Invalid_Conversion exception.
declare
use Ada.Calendar;
Date : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value);
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Dt : constant Duration := Now - Date;
Values : ASF.Utils.Object_Array (1 .. 1);
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if Dt < 60.0 then
return Bundle.Get ("date_moment_ago");
elsif Dt < 120.0 then
return Bundle.Get ("date_minute_ago");
elsif Dt < ONE_HOUR then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / 60.0));
ASF.Utils.Formats.Format (Bundle.Get ("date_minutes_ago"),
Values, Result);
elsif Dt < 2 * ONE_HOUR then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / 60.0));
ASF.Utils.Formats.Format (Bundle.Get ("date_hour_ago"),
Values, Result);
elsif Dt < ONE_DAY then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_HOUR));
ASF.Utils.Formats.Format (Bundle.Get ("date_hours_ago"),
Values, Result);
elsif Dt < 2 * ONE_DAY then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_HOUR));
ASF.Utils.Formats.Format (Bundle.Get ("date_day_ago"),
Values, Result);
elsif Dt < 7 * ONE_DAY then
Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_DAY));
ASF.Utils.Formats.Format (Bundle.Get ("date_days_ago"),
Values, Result);
else
declare
use ASF.Converters.Dates;
Pattern : constant String
:= Date_Converter'Class (Convert).Get_Pattern (Context, Bundle, Component);
begin
return Util.Dates.Formats.Format (Pattern, Date, Bundle);
end;
end if;
return Ada.Strings.Unbounded.To_String (Result);
end;
exception
when E : others =>
raise ASF.Converters.Invalid_Conversion with Ada.Exceptions.Exception_Message (E);
end To_String;
end AWA.Converters.Dates;
|
Add the bundle to the Get_Pattern function call
|
Add the bundle to the Get_Pattern function call
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
87d0b7f7e061720a611f913b6ce0601b1d2d37c3
|
src/asf-contexts-facelets.adb
|
src/asf-contexts-facelets.adb
|
-----------------------------------------------------------------------
-- contexts-facelets -- Contexts for facelets
-- 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 EL.Variables;
with ASF.Applications.Main;
with ASF.Views.Nodes.Facelets;
package body ASF.Contexts.Facelets is
-- ------------------------------
-- Get the EL context for evaluating expressions.
-- ------------------------------
function Get_ELContext (Context : in Facelet_Context)
return EL.Contexts.ELContext_Access is
begin
return Context.Context;
end Get_ELContext;
-- ------------------------------
-- Set the EL context for evaluating expressions.
-- ------------------------------
procedure Set_ELContext (Context : in out Facelet_Context;
ELContext : in EL.Contexts.ELContext_Access) is
begin
Context.Context := ELContext;
end Set_ELContext;
-- ------------------------------
-- Get the function mapper associated with the EL context.
-- ------------------------------
function Get_Function_Mapper (Context : in Facelet_Context)
return EL.Functions.Function_Mapper_Access is
use EL.Contexts;
begin
if Context.Context = null then
return null;
else
return Context.Context.Get_Function_Mapper;
end if;
end Get_Function_Mapper;
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Context : in out Facelet_Context;
Name : in String;
Value : in EL.Objects.Object) is
begin
null;
end Set_Attribute;
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Context : in out Facelet_Context;
Name : in Unbounded_String;
Value : in EL.Objects.Object) is
begin
null;
end Set_Attribute;
-- ------------------------------
-- Set the attribute having given name with the value expression.
-- ------------------------------
procedure Set_Variable (Context : in out Facelet_Context;
Name : in Unbounded_String;
Value : in EL.Expressions.Value_Expression) is
Mapper : constant access EL.Variables.VariableMapper'Class
:= Context.Context.Get_Variable_Mapper;
begin
if Mapper /= null then
Mapper.Set_Variable (Name, Value);
end if;
end Set_Variable;
-- ------------------------------
-- Include the facelet from the given source file.
-- The included views appended to the parent component tree.
-- ------------------------------
procedure Include_Facelet (Context : in out Facelet_Context;
Source : in String;
Parent : in Base.UIComponent_Access) is
begin
null;
end Include_Facelet;
-- ------------------------------
-- Include the definition having the given name.
-- ------------------------------
procedure Include_Definition (Context : in out Facelet_Context;
Name : in Unbounded_String;
Parent : in Base.UIComponent_Access;
Found : out Boolean) is
Node : Composition_Tag_Node;
Iter : Defines_Vector.Cursor := Context.Defines.Last;
The_Name : aliased constant String := To_String (Name);
begin
if Context.Inserts.Contains (The_Name'Unchecked_Access) then
Found := True;
return;
end if;
Context.Inserts.Insert (The_Name'Unchecked_Access);
while Defines_Vector.Has_Element (Iter) loop
Node := Defines_Vector.Element (Iter);
Node.Include_Definition (Parent => Parent,
Context => Context,
Name => Name,
Found => Found);
if Found then
Context.Inserts.Delete (The_Name'Unchecked_Access);
return;
end if;
Defines_Vector.Previous (Iter);
end loop;
Found := False;
Context.Inserts.Delete (The_Name'Unchecked_Access);
end Include_Definition;
-- ------------------------------
-- Push into the current facelet context the <ui:define> nodes contained in
-- the composition/decorate tag.
-- ------------------------------
procedure Push_Defines (Context : in out Facelet_Context;
Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node) is
begin
Context.Defines.Append (Node.all'Access);
end Push_Defines;
-- ------------------------------
-- Pop from the current facelet context the <ui:define> nodes.
-- ------------------------------
procedure Pop_Defines (Context : in out Facelet_Context) is
use Ada.Containers;
begin
if Context.Defines.Length > 0 then
Context.Defines.Delete_Last;
end if;
end Pop_Defines;
-- ------------------------------
-- Set the path to resolve relative facelet paths and get the previous path.
-- ------------------------------
procedure Set_Relative_Path (Context : in out Facelet_Context;
Path : in Unbounded_String;
Previous : out Unbounded_String) is
begin
Previous := Context.Path;
Context.Path := Path;
end Set_Relative_Path;
-- ------------------------------
-- Set the path to resolve relative facelet paths.
-- ------------------------------
procedure Set_Relative_Path (Context : in out Facelet_Context;
Path : in Unbounded_String) is
begin
Context.Path := Path;
end Set_Relative_Path;
-- ------------------------------
-- Resolve the facelet relative path
-- ------------------------------
function Resolve_Path (Context : Facelet_Context;
Path : String) return String is
begin
if Path (Path'First) = '/' then
return Path;
else
return To_String (Context.Path) & Path;
end if;
end Resolve_Path;
-- ------------------------------
-- Get a converter from a name.
-- Returns the converter object or null if there is no converter.
-- ------------------------------
function Get_Converter (Context : in Facelet_Context;
Name : in EL.Objects.Object)
return access ASF.Converters.Converter'Class is
begin
return Facelet_Context'Class (Context).Get_Application.Find (Name);
end Get_Converter;
end ASF.Contexts.Facelets;
|
-----------------------------------------------------------------------
-- contexts-facelets -- Contexts for facelets
-- 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.Directories;
with Util.Files;
with EL.Variables;
with ASF.Applications.Main;
with ASF.Views.Nodes.Facelets;
package body ASF.Contexts.Facelets is
-- ------------------------------
-- Get the EL context for evaluating expressions.
-- ------------------------------
function Get_ELContext (Context : in Facelet_Context)
return EL.Contexts.ELContext_Access is
begin
return Context.Context;
end Get_ELContext;
-- ------------------------------
-- Set the EL context for evaluating expressions.
-- ------------------------------
procedure Set_ELContext (Context : in out Facelet_Context;
ELContext : in EL.Contexts.ELContext_Access) is
begin
Context.Context := ELContext;
end Set_ELContext;
-- ------------------------------
-- Get the function mapper associated with the EL context.
-- ------------------------------
function Get_Function_Mapper (Context : in Facelet_Context)
return EL.Functions.Function_Mapper_Access is
use EL.Contexts;
begin
if Context.Context = null then
return null;
else
return Context.Context.Get_Function_Mapper;
end if;
end Get_Function_Mapper;
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Context : in out Facelet_Context;
Name : in String;
Value : in EL.Objects.Object) is
begin
null;
end Set_Attribute;
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Context : in out Facelet_Context;
Name : in Unbounded_String;
Value : in EL.Objects.Object) is
begin
null;
end Set_Attribute;
-- ------------------------------
-- Set the attribute having given name with the value expression.
-- ------------------------------
procedure Set_Variable (Context : in out Facelet_Context;
Name : in Unbounded_String;
Value : in EL.Expressions.Value_Expression) is
Mapper : constant access EL.Variables.VariableMapper'Class
:= Context.Context.Get_Variable_Mapper;
begin
if Mapper /= null then
Mapper.Set_Variable (Name, Value);
end if;
end Set_Variable;
-- ------------------------------
-- Include the facelet from the given source file.
-- The included views appended to the parent component tree.
-- ------------------------------
procedure Include_Facelet (Context : in out Facelet_Context;
Source : in String;
Parent : in Base.UIComponent_Access) is
begin
null;
end Include_Facelet;
-- ------------------------------
-- Include the definition having the given name.
-- ------------------------------
procedure Include_Definition (Context : in out Facelet_Context;
Name : in Unbounded_String;
Parent : in Base.UIComponent_Access;
Found : out Boolean) is
Node : Composition_Tag_Node;
Iter : Defines_Vector.Cursor := Context.Defines.Last;
The_Name : aliased constant String := To_String (Name);
begin
if Context.Inserts.Contains (The_Name'Unchecked_Access) then
Found := True;
return;
end if;
Context.Inserts.Insert (The_Name'Unchecked_Access);
while Defines_Vector.Has_Element (Iter) loop
Node := Defines_Vector.Element (Iter);
Node.Include_Definition (Parent => Parent,
Context => Context,
Name => Name,
Found => Found);
if Found then
Context.Inserts.Delete (The_Name'Unchecked_Access);
return;
end if;
Defines_Vector.Previous (Iter);
end loop;
Found := False;
Context.Inserts.Delete (The_Name'Unchecked_Access);
end Include_Definition;
-- ------------------------------
-- Push into the current facelet context the <ui:define> nodes contained in
-- the composition/decorate tag.
-- ------------------------------
procedure Push_Defines (Context : in out Facelet_Context;
Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node) is
begin
Context.Defines.Append (Node.all'Access);
end Push_Defines;
-- ------------------------------
-- Pop from the current facelet context the <ui:define> nodes.
-- ------------------------------
procedure Pop_Defines (Context : in out Facelet_Context) is
use Ada.Containers;
begin
if Context.Defines.Length > 0 then
Context.Defines.Delete_Last;
end if;
end Pop_Defines;
-- ------------------------------
-- Set the path to resolve relative facelet paths and get the previous path.
-- ------------------------------
procedure Set_Relative_Path (Context : in out Facelet_Context;
Path : in Unbounded_String;
Previous : out Unbounded_String) is
File : constant String := To_String (Path);
begin
Previous := Context.Path;
Context.Path := To_Unbounded_String (Ada.Directories.Containing_Directory (File));
end Set_Relative_Path;
-- ------------------------------
-- Set the path to resolve relative facelet paths.
-- ------------------------------
procedure Set_Relative_Path (Context : in out Facelet_Context;
Path : in Unbounded_String) is
begin
Context.Path := Path;
end Set_Relative_Path;
-- ------------------------------
-- Resolve the facelet relative path
-- ------------------------------
function Resolve_Path (Context : Facelet_Context;
Path : String) return String is
begin
if Path (Path'First) = '/' then
return Path;
else
return Util.Files.Compose (To_String (Context.Path), Path);
end if;
end Resolve_Path;
-- ------------------------------
-- Get a converter from a name.
-- Returns the converter object or null if there is no converter.
-- ------------------------------
function Get_Converter (Context : in Facelet_Context;
Name : in EL.Objects.Object)
return access ASF.Converters.Converter'Class is
begin
return Facelet_Context'Class (Context).Get_Application.Find (Name);
end Get_Converter;
end ASF.Contexts.Facelets;
|
Fix facelet inclusion when a path is relative
|
Fix facelet inclusion when a path is relative
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
af684c579675478a9dae52784dba84fd99a8625f
|
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
|
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- 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 ASF.Applications;
with ADO;
with ADO.Sessions;
with AWA.Events;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with AWA.Counters.Definition;
with Security.Permissions;
-- == Events ==
-- The <tt>wikis</tt> exposes a number of events which are posted when some action
-- are performed at the service level.
--
-- === wiki-create-page ===
-- This event is posted when a new wiki page is created.
--
-- === wiki-create-content ===
-- This event is posted when a new wiki page content is created. Each time a wiki page is
-- modified, a new wiki page content is created and this event is posted.
--
package AWA.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create");
package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete");
package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update");
package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view");
-- Define the permissions.
package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create");
package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete");
package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update");
-- Event posted when a new wiki page is created.
package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page");
-- Event posted when a new wiki content is created.
package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content");
-- Define the read wiki page counter.
package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count");
package Wiki_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class);
subtype Listener is Wiki_Lifecycle.Listener;
-- The configuration parameter that defines a list of wiki page ID to copy when a new
-- wiki space is created.
PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list";
-- Exception raised when a wiki page name is already used for the wiki space.
Name_Used : exception;
-- ------------------------------
-- Module wikis
-- ------------------------------
type Wiki_Module is new AWA.Modules.Module with private;
type Wiki_Module_Access is access all Wiki_Module'Class;
-- Initialize the wikis module.
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the wikis module.
function Get_Wiki_Module return Wiki_Module_Access;
-- Create the wiki space.
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Save the wiki space.
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Load the wiki space.
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier);
-- Create the wiki page into the wiki space.
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save the wiki page.
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Delete the wiki page as well as all its versions.
procedure Delete (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Load the wiki page and its content.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier);
-- Load the wiki page and its content from the wiki space Id and the page name.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String);
-- Create a new wiki content for the wiki page.
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
private
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier);
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
type Wiki_Module is new AWA.Modules.Module with null record;
end AWA.Wikis.Modules;
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with ADO.Sessions;
with AWA.Events;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with AWA.Counters.Definition;
with Security.Permissions;
-- == Events ==
-- The <tt>wikis</tt> exposes a number of events which are posted when some action
-- are performed at the service level.
--
-- === wiki-create-page ===
-- This event is posted when a new wiki page is created.
--
-- === wiki-create-content ===
-- This event is posted when a new wiki page content is created. Each time a wiki page is
-- modified, a new wiki page content is created and this event is posted.
--
package AWA.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create");
package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete");
package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update");
package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view");
-- Define the permissions.
package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create");
package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete");
package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update");
-- Event posted when a new wiki page is created.
package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page");
-- Event posted when a new wiki content is created.
package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content");
-- Define the read wiki page counter.
package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count");
package Wiki_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class);
subtype Listener is Wiki_Lifecycle.Listener;
-- The configuration parameter that defines a list of wiki page ID to copy when a new
-- wiki space is created.
PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list";
-- Exception raised when a wiki page name is already used for the wiki space.
Name_Used : exception;
-- ------------------------------
-- Module wikis
-- ------------------------------
type Wiki_Module is new AWA.Modules.Module with private;
type Wiki_Module_Access is access all Wiki_Module'Class;
-- Initialize the wikis module.
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the image prefix that was configured for the Wiki module.
function Get_Image_Prefix (Module : in Wiki_Module)
return Ada.Strings.Unbounded.Unbounded_String;
-- Get the wikis module.
function Get_Wiki_Module return Wiki_Module_Access;
-- Create the wiki space.
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Save the wiki space.
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Load the wiki space.
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier);
-- Create the wiki page into the wiki space.
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save the wiki page.
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Delete the wiki page as well as all its versions.
procedure Delete (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Load the wiki page and its content.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier);
-- Load the wiki page and its content from the wiki space Id and the page name.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String);
-- Create a new wiki content for the wiki page.
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
private
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier);
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
type Wiki_Module is new AWA.Modules.Module with record
Image_Prefix : Ada.Strings.Unbounded.Unbounded_String;
end record;
end AWA.Wikis.Modules;
|
Declare Get_Image_Prefix function and add an Image_Prefix member to the Wiki_Module
|
Declare Get_Image_Prefix function and add an Image_Prefix member to the Wiki_Module
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5cd4fa72b4882ec2be58c7f27fbf0c0e10e49557
|
src/asf-components-widgets-inputs.adb
|
src/asf-components-widgets-inputs.adb
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input 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 Ada.Strings.Unbounded;
with ASF.Components.Html.Messages;
with ASF.Applications.Messages.Vectors;
with Util.Beans.Objects;
package body ASF.Components.Widgets.Inputs is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Render the input field title.
-- ------------------------------
procedure Render_Title (UI : in UIInput;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class) is
Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title");
begin
Writer.Start_Element ("dt");
Writer.Write (Title);
Writer.End_Element ("dt");
end Render_Title;
-- ------------------------------
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
Style : constant String := UI.Get_Attribute ("styleClass", Context);
begin
Writer.Start_Element ("dl");
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Writer.Write_Attribute ("class", Style & " awa-error");
elsif Style'Length > 0 then
Writer.Write_Attribute ("class", Style);
end if;
UI.Render_Title (Writer, Context);
Writer.Start_Element ("dd");
UI.Render_Input (Context);
end;
end Encode_Begin;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the error message associated with the input field.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN_NO_STYLE, False, True, Context);
end if;
Writer.End_Element ("dd");
Writer.End_Element ("dl");
end;
end Encode_End;
end ASF.Components.Widgets.Inputs;
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input 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 Ada.Strings.Unbounded;
with Ada.Characters.Conversions;
with ASF.Models.Selects;
with ASF.Components.Base;
with ASF.Components.Utils;
with ASF.Components.Html.Messages;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Vectors;
with Util.Strings.Transforms;
with Util.Beans.Objects;
package body ASF.Components.Widgets.Inputs is
-- ------------------------------
-- Render the input field title.
-- ------------------------------
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class) is
Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title");
begin
Writer.Start_Element ("dt");
Writer.Start_Element ("label");
Writer.Write_Attribute ("for", Name);
Writer.Write_Text (Title);
Writer.End_Element ("label");
Writer.End_Element ("dt");
end Render_Title;
-- ------------------------------
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
Style : constant String := UI.Get_Attribute ("styleClass", Context);
begin
Writer.Start_Element ("dl");
Writer.Write_Attribute ("id", Id);
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Writer.Write_Attribute ("class", Style & " asf-error");
elsif Style'Length > 0 then
Writer.Write_Attribute ("class", Style);
end if;
UI.Render_Title (Id, Writer, Context);
Writer.Start_Element ("dd");
UI.Render_Input (Context, Write_Id => False);
end;
end Encode_Begin;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the error message associated with the input field.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN_NO_STYLE, False, True, Context);
end if;
Writer.End_Element ("dd");
Writer.End_Element ("dl");
end;
end Encode_End;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the autocomplete script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').complete({");
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Val : constant String := Context.Get_Parameter (Id & ".match");
begin
if Val'Length > 0 then
UI.Match_Value := Util.Beans.Objects.To_Object (Val);
else
ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context);
end if;
end;
end Process_Decodes;
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class) is
use type Util.Beans.Basic.List_Bean_Access;
List : constant Util.Beans.Basic.List_Bean_Access
:= ASF.Components.Utils.Get_List_Bean (UI, "autocomplete", Context);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Need_Comma : Boolean := False;
Count : Natural;
procedure Render_Item (Label : in String) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if Match'Length = 0 or else
(Match'Length <= Label'Length
and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then
if Need_Comma then
Writer.Write (",");
end if;
Writer.Write ('"');
Util.Strings.Transforms.Escape_Java (Content => Label,
Into => Result);
Writer.Write (Result);
Writer.Write ('"');
Need_Comma := True;
end if;
end Render_Item;
begin
Writer.Write ('[');
if List /= null then
Count := List.Get_Count;
if List.all in ASF.Models.Selects.Select_Item_List'Class then
declare
S : access ASF.Models.Selects.Select_Item_List'Class
:= ASF.Models.Selects.Select_Item_List'Class (List.all)'Access;
begin
for I in 1 .. Count loop
Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label));
end loop;
end;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
declare
Value : constant Util.Beans.Objects.Object := List.Get_Row;
Label : constant String := Util.Beans.Objects.To_String (Value);
begin
Render_Item (Label);
end;
end loop;
end if;
end if;
Writer.Write (']');
end Render_List;
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then
declare
Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match");
ME : EL.Expressions.Method_Expression;
begin
if Value /= null then
declare
VE : constant EL.Expressions.Value_Expression
:= ASF.Views.Nodes.Get_Value_Expression (Value.all);
begin
VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all);
end;
end if;
-- Post an event on this component to trigger the rendering of the completion
-- list as part of an application/json output. The rendering is made by Broadcast.
ASF.Events.Faces.Actions.Post_Event (UI => UI,
Method => ME);
end;
else
ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context);
end if;
-- exception
-- when E : others =>
-- UI.Is_Valid := False;
-- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context);
-- Log.Info (Utils.Get_Line_Info (UI)
-- & ": Exception raised when updating value {0} for component {1}: {2}",
-- EL.Objects.To_String (UI.Submitted_Value),
-- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E));
end Process_Updates;
-- ------------------------------
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
-- ------------------------------
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Event);
Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value);
begin
Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8");
UI.Render_List (Match, Context);
Context.Response_Completed;
end Broadcast;
end ASF.Components.Widgets.Inputs;
|
Implement the UIComplete component
|
Implement the UIComplete component
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
630d45b7541774c9495d886d875352a00436a362
|
src/base/files/util-files-rolling.ads
|
src/base/files/util-files-rolling.ads
|
-----------------------------------------------------------------------
-- util-files-rolling -- Rolling file manager
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Directories;
with Util.Strings.Vectors;
-- == Rolling file manager ==
-- The `Util.Files.Rolling` package provides a simple support to roll a file
-- based on some rolling policy. Such rolling is traditionally used for file
-- logs to move files to another place when they reach some size limit or when
-- some date conditions are met (such as a day change). The file manager uses
-- a file path and a pattern. The file path is used to define the default
-- or initial file. The pattern is used when rolling occurs to decide how
-- to reorganize files.
--
-- The file manager defines a triggering policy represented by `Policy_Type`.
-- It controls when the file rolling must be made.
--
-- * `No_Policy`: no policy, the rolling must be triggered manually.
-- * `Size_Policy`: size policy, the rolling is triggered when the file
-- reaches a given size.
-- * `Time_Policy`: time policy, the rolling is made when the date/time pattern
-- no longer applies to the active file.
--
-- To control how the rolling is made, the `Strategy_Type` defines the behavior
-- of the rolling.
--
-- * `Rollover_Strategy`:
-- * `Direct_Strategy`:
--
-- To use the file manager, the first step is to create an instance and configure
-- the default file, pattern, choose the triggering policy and strategy:
--
-- Manager : Util.Files.Rolling.File_Manager;
--
-- Manager.Initialize ("dynamo.log", "dynamo-%i.log",
-- Policy => (Size_Policy, 100_000),
-- Strategy => (Rollover_Strategy, 1, 10));
--
-- After the initialization, the current file is retrieved by using the
-- `Get_Current_Path` function and you should call `Is_Rollover_Necessary`
-- before writing content on the file. When it returns `True`, it means you
-- should call the `Rollover` procedure that will perform roll over according
-- to the rolling strategy.
--
package Util.Files.Rolling is
type Policy_Kind is (No_Policy, Size_Policy, Time_Policy);
type Policy_Type (Kind : Policy_Kind) is record
case Kind is
when No_Policy =>
null;
when Size_Policy =>
Size : Ada.Directories.File_Size := 100_000_000;
when Time_Policy =>
Interval : Natural := 1;
end case;
end record;
type Strategy_Kind is (Ascending_Strategy,
Descending_Strategy,
Direct_Strategy);
type Strategy_Type (Kind : Strategy_Kind) is record
case Kind is
when Ascending_Strategy | Descending_Strategy =>
Min_Index : Natural;
Max_Index : Natural;
when Direct_Strategy =>
Max_Files : Natural;
end case;
end record;
-- Format the file pattern with the date and index to produce a file path.
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Index : in Natural) return String;
type File_Manager is tagged limited private;
-- Initialize the file manager to roll the file referred by `Path` by using
-- the pattern defined in `Pattern`.
procedure Initialize (Manager : in out File_Manager;
Path : in String;
Pattern : in String;
Policy : in Policy_Type;
Strategy : in Strategy_Type);
-- Get the current path (it may or may not exist).
function Get_Current_Path (Manager : in File_Manager) return String;
-- Check if a rollover is necessary based on the rolling strategy.
function Is_Rollover_Necessary (Manager : in File_Manager) return Boolean;
-- Perform a rollover according to the strategy that was configured.
procedure Rollover (Manager : in out File_Manager);
procedure Rollover_Ascending (Manager : in out File_Manager);
procedure Rollover_Descending (Manager : in out File_Manager);
procedure Rollover_Direct (Manager : in out File_Manager);
-- Get the regex pattern to identify a file that must be purged.
-- The default is to extract the file pattern part of the file manager pattern.
function Get_Purge_Pattern (Manager : in File_Manager) return String;
private
-- Find the files that are eligible to purge in the given directory.
procedure Eligible_Files (Manager : in out File_Manager;
Path : in String;
Names : in out Util.Strings.Vectors.Vector;
First_Index : out Natural;
Last_Index : out Natural);
procedure Rename (Manager : in File_Manager;
Old : in String);
type File_Manager is tagged limited record
Policy : Policy_Kind := No_Policy;
Strategy : Strategy_Kind := Ascending_Strategy;
File_Path : Unbounded_String;
Pattern : Unbounded_String;
Interval : Natural;
Cur_Index : Natural := 1;
Min_Index : Natural;
Max_Index : Natural;
Max_Files : Natural := 1;
Deadline : Ada.Calendar.Time;
Max_Size : Ada.Directories.File_Size := Ada.Directories.File_Size'Last;
end record;
end Util.Files.Rolling;
|
-----------------------------------------------------------------------
-- util-files-rolling -- Rolling file manager
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Directories;
with Util.Strings.Vectors;
-- == Rolling file manager ==
-- The `Util.Files.Rolling` package provides a simple support to roll a file
-- based on some rolling policy. Such rolling is traditionally used for file
-- logs to move files to another place when they reach some size limit or when
-- some date conditions are met (such as a day change). The file manager uses
-- a file path and a pattern. The file path is used to define the default
-- or initial file. The pattern is used when rolling occurs to decide how
-- to reorganize files.
--
-- The file manager defines a triggering policy represented by `Policy_Type`.
-- It controls when the file rolling must be made.
--
-- * `No_Policy`: no policy, the rolling must be triggered manually.
-- * `Size_Policy`: size policy, the rolling is triggered when the file
-- reaches a given size.
-- * `Time_Policy`: time policy, the rolling is made when the date/time pattern
-- no longer applies to the active file; the `Interval` configuration
-- defines the period to check for time changes,
-- * `Size_Time_Policy`: combines the size and time policy, the rolling is
-- triggered when either the file reaches a given size or the date/time
-- pattern no longer applies to the active file.
--
-- To control how the rolling is made, the `Strategy_Type` defines the behavior
-- of the rolling.
--
-- * `Rollover_Strategy`:
-- * `Direct_Strategy`:
--
-- To use the file manager, the first step is to create an instance and configure
-- the default file, pattern, choose the triggering policy and strategy:
--
-- Manager : Util.Files.Rolling.File_Manager;
--
-- Manager.Initialize ("dynamo.log", "dynamo-%i.log",
-- Policy => (Size_Policy, 100_000),
-- Strategy => (Rollover_Strategy, 1, 10));
--
-- After the initialization, the current file is retrieved by using the
-- `Get_Current_Path` function and you should call `Is_Rollover_Necessary`
-- before writing content on the file. When it returns `True`, it means you
-- should call the `Rollover` procedure that will perform roll over according
-- to the rolling strategy.
--
package Util.Files.Rolling is
type Policy_Kind is (No_Policy, Size_Policy, Time_Policy, Size_Time_Policy);
type Policy_Type (Kind : Policy_Kind) is record
case Kind is
when No_Policy =>
null;
when Time_Policy | Size_Policy | Size_Time_Policy =>
Size : Ada.Directories.File_Size := 100_000_000;
Interval : Natural := 0;
end case;
end record;
type Strategy_Kind is (Ascending_Strategy,
Descending_Strategy,
Direct_Strategy);
type Strategy_Type (Kind : Strategy_Kind) is record
case Kind is
when Ascending_Strategy | Descending_Strategy =>
Min_Index : Natural;
Max_Index : Natural;
when Direct_Strategy =>
Max_Files : Natural;
end case;
end record;
-- Format the file pattern with the date and index to produce a file path.
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Index : in Natural) return String;
type File_Manager is tagged limited private;
-- Initialize the file manager to roll the file referred by `Path` by using
-- the pattern defined in `Pattern`.
procedure Initialize (Manager : in out File_Manager;
Path : in String;
Pattern : in String;
Policy : in Policy_Type;
Strategy : in Strategy_Type);
-- Get the current path (it may or may not exist).
function Get_Current_Path (Manager : in File_Manager) return String;
-- Check if a rollover is necessary based on the rolling strategy.
function Is_Rollover_Necessary (Manager : in out File_Manager) return Boolean;
-- Perform a rollover according to the strategy that was configured.
procedure Rollover (Manager : in out File_Manager);
procedure Rollover_Ascending (Manager : in out File_Manager);
procedure Rollover_Descending (Manager : in out File_Manager);
procedure Rollover_Direct (Manager : in out File_Manager);
-- Get the regex pattern to identify a file that must be purged.
-- The default is to extract the file pattern part of the file manager pattern.
function Get_Purge_Pattern (Manager : in File_Manager) return String;
private
-- Find the files that are eligible to purge in the given directory.
procedure Eligible_Files (Manager : in out File_Manager;
Path : in String;
Names : in out Util.Strings.Vectors.Vector;
First_Index : out Natural;
Last_Index : out Natural);
procedure Rename (Manager : in File_Manager;
Old : in String);
type File_Manager is tagged limited record
Policy : Policy_Kind := No_Policy;
Strategy : Strategy_Kind := Ascending_Strategy;
File_Path : Unbounded_String;
Pattern : Unbounded_String;
Interval : Natural;
Cur_Index : Natural := 1;
Min_Index : Natural;
Max_Index : Natural;
Max_Files : Natural := 1;
Deadline : Ada.Calendar.Time;
Max_Size : Ada.Directories.File_Size := Ada.Directories.File_Size'Last;
end record;
end Util.Files.Rolling;
|
Add the Size_Time_Policy to allow using the size and time policy at the same time
|
Add the Size_Time_Policy to allow using the size and time policy at the same time
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8cc51c95ac60c4eef17bca04f07c459dd7368f63
|
src/gen-artifacts-docs-googlecode.adb
|
src/gen-artifacts-docs-googlecode.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Artifacts.Docs.Googlecode is
-- ------------------------------
-- 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 is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
begin
Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- 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) is
begin
if Line.Kind = L_LIST then
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
elsif Line.Kind = L_LIST_ITEM then
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
elsif Line.Kind = L_START_CODE then
if Formatter.Need_NewLine then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, "{{{");
elsif Line.Kind = L_END_CODE then
if Formatter.Need_NewLine then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, "}}}");
else
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, Line.Content);
end if;
end Write_Line;
-- ------------------------------
-- 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) is
begin
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put_Line (File, "----");
Ada.Text_IO.Put_Line (File,
"[https://github.com/stcarrez/dynamo Generated by Dynamo] from _"
& Source & "_");
end Finish_Document;
end Gen.Artifacts.Docs.Googlecode;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Artifacts.Docs.Googlecode is
-- ------------------------------
-- 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 is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
begin
Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- Write a line in the document.
-- ------------------------------
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in String) is
begin
if Formatter.Need_NewLine then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, Line);
end Write_Line;
-- ------------------------------
-- 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) is
begin
case Line.Kind is
when L_LIST =>
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
when L_LIST_ITEM =>
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
when L_START_CODE =>
Formatter.Write_Line (File, "{{{");
when L_END_CODE =>
Formatter.Write_Line (File, "}}}");
when L_TEXT =>
Formatter.Write_Line (File, Line.Content);
when L_HEADER_1 =>
Formatter.Write_Line (File, "= " & Line.Content & " =");
when L_HEADER_2 =>
Formatter.Write_Line (File, "== " & Line.Content & " ==");
when L_HEADER_3 =>
Formatter.Write_Line (File, "=== " & Line.Content & " ===");
when L_HEADER_4 =>
Formatter.Write_Line (File, "==== " & Line.Content & " ====");
when others =>
null;
end case;
end Write_Line;
-- ------------------------------
-- 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) is
begin
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put_Line (File, "----");
Ada.Text_IO.Put_Line (File,
"[https://github.com/stcarrez/dynamo Generated by Dynamo] from _"
& Source & "_");
end Finish_Document;
end Gen.Artifacts.Docs.Googlecode;
|
Implement the Write_Line procedure Emit a header according to the L_HEADER_x codes
|
Implement the Write_Line procedure
Emit a header according to the L_HEADER_x codes
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
fdd4f2614ee8d39c3506efcc9281885de75b5b39
|
src/util-streams-buffered.adb
|
src/util-streams-buffered.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
package body Util.Streams.Buffered is
procedure Free_Buffer is
new Ada.Unchecked_Deallocation (Object => Stream_Element_Array,
Name => Buffer_Access);
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : in Output_Stream_Access;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Output := Output;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
Stream.No_Flush := False;
end Initialize;
-- ------------------------------
-- Initialize the stream to read from the string.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Content'Length);
Stream.Buffer := new Stream_Element_Array (1 .. Content'Length);
Stream.Input := null;
Stream.Write_Pos := Stream.Last + 1;
Stream.Read_Pos := 1;
for I in Content'Range loop
Stream.Buffer (Stream_Element_Offset (I - Content'First + 1))
:= Character'Pos (Content (I));
end loop;
end Initialize;
-- ------------------------------
-- Initialize the stream with a buffer of <b>Size</b> bytes.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive) is
begin
Stream.Initialize (Output => null, Size => Size);
Stream.No_Flush := True;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : in Input_Stream_Access;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Input := Input;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Close the sink.
-- ------------------------------
overriding
procedure Close (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Output /= null then
Output_Buffer_Stream'Class (Stream).Flush;
Stream.Output.Close;
end if;
end Close;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is
begin
return Stream.Buffer;
end Get_Buffer;
-- ------------------------------
-- Get the number of element in the stream.
-- ------------------------------
function Get_Size (Stream : in Output_Buffer_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Start : Stream_Element_Offset := Buffer'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
begin
while Start <= Buffer'Last loop
Size := Buffer'Last - Start + 1;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Pos := 1;
Avail := Stream.Last - Pos + 1;
end if;
if Avail < Size then
Size := Avail;
end if;
Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Stream.Write_Pos := Pos;
-- If we have still more data than the buffer size, flush and write
-- the buffer directly.
if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
overriding
procedure Flush (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Write_Pos > 1 and not Stream.No_Flush then
if Stream.Output /= null then
Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1));
Stream.Output.Flush;
end if;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
-- ------------------------------
procedure Fill (Stream : in out Input_Buffer_Stream) is
begin
if Stream.Input = null then
Stream.Eof := True;
else
Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos);
Stream.Eof := Stream.Write_Pos < 1;
if not Stream.Eof then
Stream.Write_Pos := Stream.Write_Pos + 1;
end if;
Stream.Read_Pos := 1;
end if;
end Fill;
-- ------------------------------
-- Read one character from the input stream.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character) is
begin
if Stream.Read_Pos >= Stream.Write_Pos then
Stream.Fill;
if Stream.Eof then
raise Ada.IO_Exceptions.Data_Error with "End of buffer";
end if;
end if;
Char := Character'Val (Stream.Buffer (Stream.Read_Pos));
Stream.Read_Pos := Stream.Read_Pos + 1;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Start : Stream_Element_Offset := Into'First;
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
Total : Stream_Element_Offset := 0;
begin
while Start <= Into'Last loop
Size := Into'Last - Start + 1;
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
exit when Avail <= 0;
end if;
if Avail < Size then
Size := Avail;
end if;
Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Total := Total + Size;
Stream.Read_Pos := Pos;
end loop;
Last := Total;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String) is
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
begin
loop
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
if Stream.Eof then
return;
end if;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
end if;
for I in 1 .. Avail loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos)));
Pos := Pos + 1;
end loop;
Stream.Read_Pos := Pos;
end loop;
end Read;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Output_Buffer_Stream) is
begin
if Object.Buffer /= null then
if Object.Output /= null then
Object.Flush;
end if;
Free_Buffer (Object.Buffer);
end if;
end Finalize;
-- ------------------------------
-- Returns True if the end of the stream is reached.
-- ------------------------------
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is
begin
return Stream.Eof;
end Is_Eof;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Input_Buffer_Stream) is
begin
if Object.Buffer /= null then
Free_Buffer (Object.Buffer);
end if;
end Finalize;
end Util.Streams.Buffered;
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
package body Util.Streams.Buffered is
procedure Free_Buffer is
new Ada.Unchecked_Deallocation (Object => Stream_Element_Array,
Name => Buffer_Access);
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : in Output_Stream_Access;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Output := Output;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
Stream.No_Flush := False;
end Initialize;
-- ------------------------------
-- Initialize the stream to read from the string.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Content'Length);
Stream.Buffer := new Stream_Element_Array (1 .. Content'Length);
Stream.Input := null;
Stream.Write_Pos := Stream.Last + 1;
Stream.Read_Pos := 1;
for I in Content'Range loop
Stream.Buffer (Stream_Element_Offset (I - Content'First + 1))
:= Character'Pos (Content (I));
end loop;
end Initialize;
-- ------------------------------
-- Initialize the stream with a buffer of <b>Size</b> bytes.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive) is
begin
Stream.Initialize (Output => null, Size => Size);
Stream.No_Flush := True;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : in Input_Stream_Access;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Input := Input;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Close the sink.
-- ------------------------------
overriding
procedure Close (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Output /= null then
Output_Buffer_Stream'Class (Stream).Flush;
Stream.Output.Close;
end if;
end Close;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is
begin
return Stream.Buffer;
end Get_Buffer;
-- ------------------------------
-- Get the number of element in the stream.
-- ------------------------------
function Get_Size (Stream : in Output_Buffer_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Start : Stream_Element_Offset := Buffer'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
begin
while Start <= Buffer'Last loop
Size := Buffer'Last - Start + 1;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Pos := 1;
Avail := Stream.Last - Pos + 1;
end if;
if Avail < Size then
Size := Avail;
end if;
Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Stream.Write_Pos := Pos;
-- If we have still more data than the buffer size, flush and write
-- the buffer directly.
if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
overriding
procedure Flush (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Write_Pos > 1 and not Stream.No_Flush then
if Stream.Output /= null then
Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1));
Stream.Output.Flush;
end if;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
-- ------------------------------
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
if Stream.Write_Pos > 1 then
Into (Into'First .. Into'First + Stream.Write_Pos - 1) :=
Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos);
Last := Into'First + Stream.Write_Pos - 1;
else
Last := Into'First - 1;
end if;
end Flush;
-- ------------------------------
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
-- ------------------------------
procedure Fill (Stream : in out Input_Buffer_Stream) is
begin
if Stream.Input = null then
Stream.Eof := True;
else
Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos);
Stream.Eof := Stream.Write_Pos < 1;
if not Stream.Eof then
Stream.Write_Pos := Stream.Write_Pos + 1;
end if;
Stream.Read_Pos := 1;
end if;
end Fill;
-- ------------------------------
-- Read one character from the input stream.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character) is
begin
if Stream.Read_Pos >= Stream.Write_Pos then
Stream.Fill;
if Stream.Eof then
raise Ada.IO_Exceptions.Data_Error with "End of buffer";
end if;
end if;
Char := Character'Val (Stream.Buffer (Stream.Read_Pos));
Stream.Read_Pos := Stream.Read_Pos + 1;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Start : Stream_Element_Offset := Into'First;
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
Total : Stream_Element_Offset := 0;
begin
while Start <= Into'Last loop
Size := Into'Last - Start + 1;
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
exit when Avail <= 0;
end if;
if Avail < Size then
Size := Avail;
end if;
Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Total := Total + Size;
Stream.Read_Pos := Pos;
end loop;
Last := Total;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String) is
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
begin
loop
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
if Stream.Eof then
return;
end if;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
end if;
for I in 1 .. Avail loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos)));
Pos := Pos + 1;
end loop;
Stream.Read_Pos := Pos;
end loop;
end Read;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Output_Buffer_Stream) is
begin
if Object.Buffer /= null then
if Object.Output /= null then
Object.Flush;
end if;
Free_Buffer (Object.Buffer);
end if;
end Finalize;
-- ------------------------------
-- Returns True if the end of the stream is reached.
-- ------------------------------
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is
begin
return Stream.Eof;
end Is_Eof;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Input_Buffer_Stream) is
begin
if Object.Buffer /= null then
Free_Buffer (Object.Buffer);
end if;
end Finalize;
end Util.Streams.Buffered;
|
Implement the Flush procedure in an array passed as parameter
|
Implement the Flush procedure in an array passed as parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d30616db3b997d871b12eadced5313ca871ca4f9
|
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);
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 = "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);
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 From.Database.Get_Property ("user") /= "" then
Append (Result, "?user=");
Append (Result, From.Database.Get_Property ("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
Append (Result, "synchronous=OFF&encoding=UTF-8");
end if;
return To_String (Result);
end Get_Database_URL;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Database : constant String := From.Get_Database_URL;
Command : constant String := "dynamo create-database db '" & Database & "'";
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
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));
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.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);
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 From.Database.Get_Property ("user") /= "" then
Append (Result, "?user=");
Append (Result, From.Database.Get_Property ("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
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));
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;
|
Implement the Get_Configure_Command and use it for the database configuration Add the database root user and root password configuration
|
Implement the Get_Configure_Command and use it for the database configuration
Add the database root user and root password configuration
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7d15b7fbae59e462a62dfb6748e2fe67656f9c8a
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- 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;
with Util.Strings;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with Security.Contexts;
package body AWA.Blogs.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Blogs.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post",
Test_Update_Post'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the blog as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Post : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html");
ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html");
ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html");
ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist",
Reply, "Blog post missing page is invalid");
if Post = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html");
ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("create-blog", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after blog creation");
declare
Ident : constant String
:= Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id=");
begin
Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident,
"Invalid blog identifier in the response");
T.Blog_Ident := To_Unbounded_String (Ident);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "Post title");
Request.Set_Parameter ("text", "The blog post content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html");
T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident),
"Invalid post identifier in the response");
end;
-- Check public access to the post.
T.Post_Uri := To_Unbounded_String (Uuid);
T.Verify_Anonymous (Uuid);
end Test_Create_Blog;
-- Test updating a post by simulating web requests.
procedure Test_Update_Post (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
Ident : constant String := To_String (T.Blog_Ident);
Post_Ident : Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post-id", To_String (T.Post_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "New post title");
Request.Set_Parameter ("text", "The blog post new content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html");
Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident),
"Invalid post identifier returned after post update");
T.Verify_Anonymous (Uuid);
end Test_Update_Post;
end AWA.Blogs.Tests;
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- 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;
with Util.Strings;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with Security.Contexts;
package body AWA.Blogs.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Blogs.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post",
Test_Update_Post'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)",
Test_Admin_List_Posts'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the blog as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Post : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html");
ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html");
ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html");
ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist",
Reply, "Blog post missing page is invalid");
if Post = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html");
ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("create-blog", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after blog creation");
declare
Ident : constant String
:= Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id=");
begin
Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident,
"Invalid blog identifier in the response");
T.Blog_Ident := To_Unbounded_String (Ident);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "Post title");
Request.Set_Parameter ("text", "The blog post content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html");
T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident),
"Invalid post identifier in the response");
end;
-- Check public access to the post.
T.Post_Uri := To_Unbounded_String (Uuid);
T.Verify_Anonymous (Uuid);
end Test_Create_Blog;
-- ------------------------------
-- Test updating a post by simulating web requests.
-- ------------------------------
procedure Test_Update_Post (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
Ident : constant String := To_String (T.Blog_Ident);
Post_Ident : Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("post-blog-id", Ident);
Request.Set_Parameter ("post-id", To_String (T.Post_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("post-title", "New post title");
Request.Set_Parameter ("text", "The blog post new content.");
Request.Set_Parameter ("uri", Uuid);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post-status", "1");
Request.Set_Parameter ("allow-comment", "0");
ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html");
Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/"
& Ident & "/preview/");
Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident),
"Invalid post identifier returned after post update");
T.Verify_Anonymous (Uuid);
end Test_Update_Post;
-- ------------------------------
-- Test listing the blog posts.
-- ------------------------------
procedure Test_Admin_List_Posts (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := To_String (T.Blog_Ident);
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html");
ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid");
end Test_Admin_List_Posts;
end AWA.Blogs.Tests;
|
Implement Test_Admin_List_Posts procedure to test the blog admin list post page
|
Implement Test_Admin_List_Posts procedure to test the blog admin list post page
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6147cb03663c1978ee76832c0014e1d7c949fc17
|
1-base/lace/source/environ/lace-environ-os_commands.adb
|
1-base/lace/source/environ/lace-environ-os_commands.adb
|
with
shell.Commands,
gnat.OS_Lib,
ada.Strings.fixed,
ada.Strings.Maps,
ada.Characters.latin_1,
ada.Exceptions;
package body lace.Environ.OS_Commands
is
use ada.Exceptions;
function Path_to (Command : in String) return Paths.Folder
is
use Paths;
begin
return to_Folder (run_OS ("which " & Command));
end Path_to;
procedure run_OS (command_Line : in String;
Input : in String := "")
is
use Shell;
begin
Commands.run (command_Line, +Input);
exception
when E : Commands.command_Error =>
raise Error with Exception_Message (E);
end run_OS;
function run_OS (command_Line : in String;
Input : in String := "";
add_Errors : in Boolean := True) return String
is
use Shell,
Shell.Commands;
function trim_LF (Source : in String) return String
is
use ada.Strings.fixed,
ada.Strings.Maps,
ada.Characters;
LF_Set : constant Character_Set := to_Set (Latin_1.LF);
begin
return trim (Source, LF_Set, LF_Set);
end trim_LF;
Results : constant Command_Results := run (command_Line, +Input);
Output : constant String := +Output_of (Results);
begin
if add_Errors
then
return trim_LF (Output & (+Errors_of (Results)));
else
return trim_LF (Output);
end if;
exception
when E : command_Error =>
raise Error with Exception_Message (E);
end run_OS;
function run_OS (command_Line : in String;
Input : in String := "") return Data
is
use Shell,
Shell.Commands;
the_Command : Command := Forge.to_Command (command_Line);
begin
return Output_of (run (The_Command, +Input));
exception
when E : command_Error =>
raise Error with Exception_Message (E);
end run_OS;
function Executable_on_Path (Executable : Paths.File) return Boolean
is
use Paths,
gnat.OS_Lib;
File_Path : String_Access := Locate_Exec_On_Path (+Executable);
Found : constant Boolean := File_Path /= null;
begin
free (File_Path);
return Found;
end Executable_on_Path;
end lace.Environ.OS_Commands;
|
with
shell.Commands.unsafe,
gnat.OS_Lib,
ada.Strings.fixed,
ada.Strings.Maps,
ada.Characters.latin_1,
ada.Exceptions;
package body lace.Environ.OS_Commands
is
use ada.Exceptions;
function Path_to (Command : in String) return Paths.Folder
is
use Paths;
begin
return to_Folder (run_OS ("which " & Command));
end Path_to;
procedure run_OS (command_Line : in String;
Input : in String := "")
is
use Shell;
begin
Commands.unsafe.run (command_Line, +Input);
exception
when E : Commands.command_Error =>
raise Error with Exception_Message (E);
end run_OS;
function run_OS (command_Line : in String;
Input : in String := "";
add_Errors : in Boolean := True) return String
is
use Shell,
Shell.Commands,
Shell.Commands.unsafe;
function trim_LF (Source : in String) return String
is
use ada.Strings.fixed,
ada.Strings.Maps,
ada.Characters;
LF_Set : constant Character_Set := to_Set (Latin_1.LF);
begin
return trim (Source, LF_Set, LF_Set);
end trim_LF;
Results : constant Command_Results := run (command_Line, +Input);
Output : constant String := +Output_of (Results);
begin
if add_Errors
then
return trim_LF (Output & (+Errors_of (Results)));
else
return trim_LF (Output);
end if;
exception
when E : command_Error =>
raise Error with Exception_Message (E);
end run_OS;
function run_OS (command_Line : in String;
Input : in String := "") return Data
is
use Shell,
Shell.Commands,
Shell.Commands.unsafe;
the_Command : unsafe.Command := Forge.to_Command (command_Line);
begin
return Output_of (run (The_Command, +Input));
exception
when E : command_Error =>
raise Error with Exception_Message (E);
end run_OS;
function Executable_on_Path (Executable : Paths.File) return Boolean
is
use Paths,
gnat.OS_Lib;
File_Path : String_Access := Locate_Exec_On_Path (+Executable);
Found : constant Boolean := File_Path /= null;
begin
free (File_Path);
return Found;
end Executable_on_Path;
end lace.Environ.OS_Commands;
|
Use 'unsafe' aShell commands.
|
lace.environ.os_commands: Use 'unsafe' aShell commands.
|
Ada
|
isc
|
charlie5/lace,charlie5/lace,charlie5/lace
|
9d1d7e92f333e985b883b2076a9927f8d45bed54
|
awa/plugins/awa-comments/src/awa-comments-modules.adb
|
awa/plugins/awa-comments/src/awa-comments-modules.adb
|
-----------------------------------------------------------------------
-- awa-comments-module -- Comments module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Sessions.Entities;
with Security.Permissions;
with AWA.Users.Models;
with AWA.Permissions;
with AWA.Modules.Beans;
with AWA.Services.Contexts;
with AWA.Comments.Beans;
package body AWA.Comments.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module");
package Register is new AWA.Modules.Beans (Module => Comment_Module,
Module_Access => Comment_Module_Access);
-- ------------------------------
-- Initialize the comments module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Comment_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the comments module");
-- Register the comment list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Comments.Beans.Comment_List_Bean",
Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access);
-- Register the comment bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Comments.Beans.Comment_Bean",
Handler => AWA.Comments.Beans.Create_Comment_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Load the comment identified by the given identifier.
-- ------------------------------
procedure Load_Comment (Model : in Comment_Module;
Comment : in out AWA.Comments.Models.Comment_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Comment.Load (DB, Id, Found);
end Load_Comment;
-- ------------------------------
-- Create a new comment for the associated database entity.
-- ------------------------------
procedure Create_Comment (Model : in Comment_Module;
Permission : in String;
Entity_Type : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id));
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment.Get_Entity_Id);
Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type));
Comment.Set_Author (User);
Comment.Set_Create_Date (Ada.Calendar.Clock);
Comment.Save (DB);
Ctx.Commit;
end Create_Comment;
end AWA.Comments.Modules;
|
-----------------------------------------------------------------------
-- awa-comments-module -- Comments module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Sessions.Entities;
with Security.Permissions;
with AWA.Users.Models;
with AWA.Permissions;
with AWA.Modules.Beans;
with AWA.Services.Contexts;
with AWA.Comments.Beans;
package body AWA.Comments.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module");
package Register is new AWA.Modules.Beans (Module => Comment_Module,
Module_Access => Comment_Module_Access);
-- ------------------------------
-- Initialize the comments module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Comment_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the comments module");
-- Register the comment list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Comments.Beans.Comment_List_Bean",
Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access);
-- Register the comment bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Comments.Beans.Comment_Bean",
Handler => AWA.Comments.Beans.Create_Comment_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Load the comment identified by the given identifier.
-- ------------------------------
procedure Load_Comment (Model : in Comment_Module;
Comment : in out AWA.Comments.Models.Comment_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Comment.Load (DB, Id, Found);
end Load_Comment;
-- ------------------------------
-- Create a new comment for the associated database entity.
-- ------------------------------
procedure Create_Comment (Model : in Comment_Module;
Permission : in String;
Entity_Type : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id));
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment.Get_Entity_Id);
Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type));
Comment.Set_Author (User);
Comment.Set_Create_Date (Ada.Calendar.Clock);
Comment.Save (DB);
Ctx.Commit;
end Create_Comment;
-- ------------------------------
-- Update the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
-- ------------------------------
procedure Update_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
if not Comment.Is_Inserted then
Log.Error ("The comment was not created");
raise Not_Found with "The comment was not inserted";
end if;
Ctx.Start;
Log.Info ("Updating the comment {0}", ADO.Identifier'Image (Comment.Get_Id));
-- Check that the user has the update permission on the given comment.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment);
Comment.Save (DB);
Ctx.Commit;
end Update_Comment;
-- ------------------------------
-- Delete the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
-- ------------------------------
procedure Delete_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given answer.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment);
Comment.Delete (DB);
Ctx.Commit;
end Delete_Comment;
end AWA.Comments.Modules;
|
Implement the new operation Delete_Comment and Update_Comment
|
Implement the new operation Delete_Comment and Update_Comment
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
bbc809d0934c50363b9a85d7f388bec4bdfb5512
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.ANSWER_TABLE,
Session => Session);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From, From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.ANSWER_TABLE,
Session => Session);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
Load the question associated with the answer
|
Load the question associated with the answer
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
54ebaf7282c20d03e70431f0f70186231f9e445f
|
src/natools-s_expressions.ads
|
src/natools-s_expressions.ads
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.S_Expression declare basic types used in all children packages --
-- dealing with S-expressions. --
-- --
-- S-expressions here are defined as a half serialization mechanism, using --
-- standard syntax from http://people.csail.mit.edu/rivest/Sexp.txt --
-- --
-- Briefly, "atoms" are defined as a sequence of octets of any length, and --
-- "lists" are defined as a sequence of items, each of which being either --
-- an atom or another list. A S-expression is a sequence of octets that --
-- represents such a list. --
-- --
-- So atoms are unstructured blob of data, supposed to be the serialization --
-- of some lower-level object (e.g. a string), and they are structured as --
-- leaves in a tree. --
-- --
-- All S-expression code here assume that Stream_Element is actually an --
-- 8-bit byte. So Octet, Atom and related types are derived from --
-- Ada.Streams entries. --
------------------------------------------------------------------------------
with Ada.Streams;
package Natools.S_Expressions is
pragma Pure (Natools.S_Expressions);
-----------------
-- Basic Types --
-----------------
subtype Octet is Ada.Streams.Stream_Element;
subtype Offset is Ada.Streams.Stream_Element_Offset;
subtype Count is Ada.Streams.Stream_Element_Count;
subtype Atom is Ada.Streams.Stream_Element_Array;
Null_Atom : constant Atom (1 .. 0) := (others => <>);
function To_String (Data : in Atom) return String;
function To_Atom (Data : in String) return Atom;
function Less_Than (Left, Right : Atom) return Boolean;
-----------------------------
-- S-expression Descriptor --
-----------------------------
package Events is
type Event is
(Error,
Open_List,
Close_List,
Add_Atom,
End_Of_Input);
end Events;
type Descriptor is limited interface;
-- Descriptor interface can be implemented by objects that can
-- describe a S-expression to its holder, using an event-driven
-- interface. The current event reports error conditions, or whether
-- a beginning or end of list encountered, or whether a new atom is
-- available.
function Current_Event (Object : in Descriptor) return Events.Event
is abstract;
-- Return the current event in Object
function Current_Atom (Object : in Descriptor) return Atom is abstract;
-- Return the current atom in an Object whose state is Add_Atom
function Current_Level (Object : in Descriptor) return Natural is abstract;
-- Return the number of nested lists currently opened
procedure Query_Atom
(Object : in Descriptor;
Process : not null access procedure (Data : in Atom)) is abstract;
-- Read-in-place callback for the current atom in Object.
-- Must only be called when current event in Object is Add_Event.
procedure Read_Atom
(Object : in Descriptor;
Data : out Atom;
Length : out Count) is abstract;
-- Copy the current atom in Object to Data.
-- Must only be called when current event in Object is Add_Event.
procedure Next
(Object : in out Descriptor;
Event : out Events.Event) is abstract;
-- Update Object to reflect the next event in the S-expression
procedure Next (Object : in out Descriptor'Class);
-- Call Next discarding current event
private
use type Ada.Streams.Stream_Element;
use type Ada.Streams.Stream_Element_Offset;
use type Ada.Streams.Stream_Element_Array;
use type Events.Event;
end Natools.S_Expressions;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.S_Expression declare basic types used in all children packages --
-- dealing with S-expressions. --
-- --
-- S-expressions here are defined as a half serialization mechanism, using --
-- standard syntax from http://people.csail.mit.edu/rivest/Sexp.txt --
-- --
-- Briefly, "atoms" are defined as a sequence of octets of any length, and --
-- "lists" are defined as a sequence of items, each of which being either --
-- an atom or another list. A S-expression is a sequence of octets that --
-- represents such a list. --
-- --
-- So atoms are unstructured blob of data, supposed to be the serialization --
-- of some lower-level object (e.g. a string), and they are structured as --
-- leaves in a tree. --
-- --
-- All S-expression code here assume that Stream_Element is actually an --
-- 8-bit byte. So Octet, Atom and related types are derived from --
-- Ada.Streams entries. --
------------------------------------------------------------------------------
with Ada.Streams;
package Natools.S_Expressions is
pragma Pure (Natools.S_Expressions);
-----------------
-- Basic Types --
-----------------
subtype Octet is Ada.Streams.Stream_Element;
subtype Offset is Ada.Streams.Stream_Element_Offset;
subtype Count is Ada.Streams.Stream_Element_Count;
subtype Atom is Ada.Streams.Stream_Element_Array;
Null_Atom : constant Atom (1 .. 0) := (others => <>);
function To_String (Data : in Atom) return String;
function To_Atom (Data : in String) return Atom;
function "<" (Left, Right : Atom) return Boolean
renames Ada.Streams."<";
function Less_Than (Left, Right : Atom) return Boolean;
-----------------------------
-- S-expression Descriptor --
-----------------------------
package Events is
type Event is
(Error,
Open_List,
Close_List,
Add_Atom,
End_Of_Input);
end Events;
type Descriptor is limited interface;
-- Descriptor interface can be implemented by objects that can
-- describe a S-expression to its holder, using an event-driven
-- interface. The current event reports error conditions, or whether
-- a beginning or end of list encountered, or whether a new atom is
-- available.
function Current_Event (Object : in Descriptor) return Events.Event
is abstract;
-- Return the current event in Object
function Current_Atom (Object : in Descriptor) return Atom is abstract;
-- Return the current atom in an Object whose state is Add_Atom
function Current_Level (Object : in Descriptor) return Natural is abstract;
-- Return the number of nested lists currently opened
procedure Query_Atom
(Object : in Descriptor;
Process : not null access procedure (Data : in Atom)) is abstract;
-- Read-in-place callback for the current atom in Object.
-- Must only be called when current event in Object is Add_Event.
procedure Read_Atom
(Object : in Descriptor;
Data : out Atom;
Length : out Count) is abstract;
-- Copy the current atom in Object to Data.
-- Must only be called when current event in Object is Add_Event.
procedure Next
(Object : in out Descriptor;
Event : out Events.Event) is abstract;
-- Update Object to reflect the next event in the S-expression
procedure Next (Object : in out Descriptor'Class);
-- Call Next discarding current event
private
use type Ada.Streams.Stream_Element;
use type Ada.Streams.Stream_Element_Offset;
use type Ada.Streams.Stream_Element_Array;
use type Events.Event;
end Natools.S_Expressions;
|
add usual lexicographical comparison operator on Atoms, so that clients don't have to explicitly use Ada.Streams."<"
|
s_expressions: add usual lexicographical comparison operator on Atoms, so that clients don't have to explicitly use Ada.Streams."<"
|
Ada
|
isc
|
faelys/natools
|
387b4ba8598d3e4a75c1cbe32d25ddb456e783b7
|
src/util-commands-drivers.ads
|
src/util-commands-drivers.ads
|
-----------------------------------------------------------------------
-- 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;
private with Ada.Containers.Indefinite_Ordered_Maps;
-- == Command line driver ==
-- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line
-- tools that have different commands identified by a name.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
-- A simple command handler executed when the command with the given name is executed.
type Command_Handler is not null access procedure (Name : in String;
Args : in out Argument_List;
Context : in out Context_Type);
-- A more complex command handler that has a command instance as context.
type Command_Type is abstract tagged limited private;
type Command_Access is access all Command_Type'Class;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type) is abstract;
-- Write the help associated with the command.
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in Command_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
type Help_Command_Type is new Command_Type with private;
-- Execute the help command with the arguments.
-- Print the help for every registered command.
overriding
procedure Execute (Command : in Help_Command_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type);
-- Write the help associated with the command.
procedure Help (Command : in Help_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Handler : in Command_Handler);
-- Find the command having the given name.
-- Returns null if the command was not found.
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access;
-- Execute the command registered under the given name.
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
private
package Command_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => Command_Access,
"<" => "<");
type Command_Type is abstract tagged limited record
Driver : access Driver_Type'Class;
end record;
type Help_Command_Type is new Command_Type with null record;
type Handler_Command_Type is new Command_Type with record
Handler : Command_Handler;
end record;
-- Execute the command with the arguments.
overriding
procedure Execute (Command : in Handler_Command_Type;
Name : in String;
Args : in out Argument_List;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Handler_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Maps.Map;
end record;
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;
private with Ada.Containers.Indefinite_Ordered_Maps;
-- == Command line driver ==
-- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line
-- tools that have different commands identified by a name.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
-- A simple command handler executed when the command with the given name is executed.
type Command_Handler is not null access procedure (Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- A more complex command handler that has a command instance as context.
type Command_Type is abstract tagged limited private;
type Command_Access is access all Command_Type'Class;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is abstract;
-- Write the help associated with the command.
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in Command_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
type Help_Command_Type is new Command_Type with private;
-- Execute the help command with the arguments.
-- Print the help for every registered command.
overriding
procedure Execute (Command : in Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
procedure Help (Command : in Help_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Handler : in Command_Handler);
-- Find the command having the given name.
-- Returns null if the command was not found.
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access;
-- Execute the command registered under the given name.
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
private
package Command_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => Command_Access,
"<" => "<");
type Command_Type is abstract tagged limited record
Driver : access Driver_Type'Class;
end record;
type Help_Command_Type is new Command_Type with null record;
type Handler_Command_Type is new Command_Type with record
Handler : Command_Handler;
end record;
-- Execute the command with the arguments.
overriding
procedure Execute (Command : in Handler_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Handler_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Maps.Map;
end record;
end Util.Commands.Drivers;
|
Update the Execute and command handlers to use the Argument_List'Class since this is now an interface
|
Update the Execute and command handlers to use the Argument_List'Class since this is now an interface
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8f80ec2963b30b403ab27ae7423720ecb9c015cc
|
samples/import.adb
|
samples/import.adb
|
-----------------------------------------------------------------------
-- import -- Import some HTML content and generate Wiki text
-- 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.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Characters.Conversions;
with GNAT.Command_Line;
with Util.Files;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Strings.Transforms;
with Wiki.Parsers;
with Wiki.Filters.Html;
with Wiki.Writers.Builders;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Render.Wiki;
procedure Import is
use GNAT.Command_Line;
use Ada.Strings.Unbounded;
use Ada.Characters.Conversions;
procedure Usage;
function Is_Url (Name : in String) return Boolean;
procedure Parse_Url (Url : in String);
procedure Parse (Content : in String);
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Count : Natural := 0;
Html_Mode : Boolean := True;
Wiki_Mode : Boolean := False;
Syntax : Wiki.Parsers.Wiki_Syntax_Type := Wiki.Parsers.SYNTAX_MARKDOWN;
procedure Usage is
begin
Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format");
Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-d] [-c] {URL | file}");
Ada.Text_IO.Put_Line (" -t Convert to text only");
Ada.Text_IO.Put_Line (" -m Convert to Markdown");
Ada.Text_IO.Put_Line (" -M Convert to Mediawiki");
Ada.Text_IO.Put_Line (" -d Convert to Dotclear");
Ada.Text_IO.Put_Line (" -c Convert to Creole");
end Usage;
procedure Parse (Content : in String) is
begin
if Wiki_Mode then
declare
Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type;
Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access, Syntax);
Html_Filter.Set_Document (Renderer'Unchecked_Access);
Wiki.Parsers.Parse (Html_Filter'Unchecked_Access,
To_Wide_Wide_String (Content), Wiki.Parsers.SYNTAX_HTML);
Ada.Text_IO.Put_Line (Writer.To_String);
end;
elsif Html_Mode then
declare
Writer : aliased Wiki.Writers.Builders.Html_Writer_Type;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access);
Html_Filter.Set_Document (Renderer'Unchecked_Access);
Wiki.Parsers.Parse (Html_Filter'Unchecked_Access,
To_Wide_Wide_String (Content), Syntax);
Ada.Text_IO.Put_Line (Writer.To_String);
end;
else
declare
Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access);
Html_Filter.Set_Document (Renderer'Unchecked_Access);
Wiki.Parsers.Parse (Html_Filter'Unchecked_Access,
To_Wide_Wide_String (Content), Syntax);
Ada.Text_IO.Put_Line (Writer.To_String);
end;
end if;
end Parse;
procedure Parse_Url (Url : in String) is
Command : constant String := "wget -q -O - " & Url;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Pipe.Open (Command);
Buffer.Initialize (null, Pipe'Unchecked_Access, 1024 * 1024);
Buffer.Read (Content);
Pipe.Close;
if Pipe.Get_Exit_Status /= 0 then
Ada.Text_IO.Put_Line (Command & " exited with status "
& Integer'Image (Pipe.Get_Exit_Status));
else
Parse (To_String (Content));
end if;
end Parse_Url;
function Is_Url (Name : in String) return Boolean is
begin
if Name'Length <= 9 then
return False;
else
return Name (Name'First .. Name'First + 6) = "http://"
or Name (Name'First .. Name'First + 7) = "https://";
end if;
end Is_Url;
begin
loop
case Getopt ("m M d c t f:") is
when 'm' =>
Syntax := Wiki.Parsers.SYNTAX_MARKDOWN;
Wiki_Mode := True;
when 'M' =>
Syntax := Wiki.Parsers.SYNTAX_MEDIA_WIKI;
Wiki_Mode := True;
when 'c' =>
Syntax := Wiki.Parsers.SYNTAX_CREOLE;
Wiki_Mode := True;
when 'd' =>
Syntax := Wiki.Parsers.SYNTAX_DOTCLEAR;
Wiki_Mode := True;
when 't' =>
Html_Mode := False;
when 'f' =>
declare
Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter);
begin
Html_Filter.Hide (Wiki.Filters.Html.Html_Tag_Type'Value (Value & "_TAG"));
exception
when Constraint_Error =>
Ada.Text_IO.Put_Line ("Invalid tag " & Value);
end;
when others =>
exit;
end case;
end loop;
loop
declare
Name : constant String := GNAT.Command_Line.Get_Argument;
Data : Unbounded_String;
begin
if Name = "" then
if Count = 0 then
Usage;
end if;
return;
end if;
Count := Count + 1;
if Is_Url (Name) then
Parse_Url (Name);
else
Util.Files.Read_File (Name, Data);
Parse (To_String (Data));
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'");
end;
end loop;
exception
when Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid option.");
Usage;
end Import;
|
-----------------------------------------------------------------------
-- import -- Import some HTML content and generate Wiki text
-- 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.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Characters.Conversions;
with GNAT.Command_Line;
with Util.Files;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Strings.Transforms;
with Wiki.Parsers;
with Wiki.Filters.Html;
with Wiki.Streams.Builders;
with Wiki.Streams.Html.Builders;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Render.Wiki;
with Wiki.Nodes;
procedure Import is
use GNAT.Command_Line;
use Ada.Strings.Unbounded;
use Ada.Characters.Conversions;
procedure Usage;
function Is_Url (Name : in String) return Boolean;
procedure Parse_Url (Url : in String);
procedure Parse (Content : in String);
Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Count : Natural := 0;
Html_Mode : Boolean := True;
Wiki_Mode : Boolean := False;
Syntax : Wiki.Parsers.Wiki_Syntax_Type := Wiki.Parsers.SYNTAX_MARKDOWN;
procedure Usage is
begin
Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format");
Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-d] [-c] {URL | file}");
Ada.Text_IO.Put_Line (" -t Convert to text only");
Ada.Text_IO.Put_Line (" -m Convert to Markdown");
Ada.Text_IO.Put_Line (" -M Convert to Mediawiki");
Ada.Text_IO.Put_Line (" -d Convert to Dotclear");
Ada.Text_IO.Put_Line (" -c Convert to Creole");
end Usage;
procedure Parse (Content : in String) is
Doc : Wiki.Nodes.Document;
Engine : Wiki.Parsers.Parser;
begin
Engine.Add_Filter (Html_Filter'Unchecked_Access);
if Wiki_Mode then
declare
Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream;
Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer;
begin
Engine.Set_Syntax (Wiki.Parsers.SYNTAX_HTML);
Engine.Parse (To_Wide_Wide_String (Content), Doc);
Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax);
Renderer.Render (Doc);
Ada.Text_IO.Put_Line (Stream.To_String);
end;
elsif Html_Mode then
declare
Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
Engine.Set_Syntax (Syntax);
Engine.Parse (To_Wide_Wide_String (Content), Doc);
Renderer.Set_Output_Stream (Stream'Unchecked_Access);
Renderer.Render (Doc);
Ada.Text_IO.Put_Line (Stream.To_String);
end;
else
declare
Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Engine.Set_Syntax (Syntax);
Engine.Parse (To_Wide_Wide_String (Content), Doc);
Renderer.Set_Output_Stream (Stream'Unchecked_Access);
Renderer.Render (Doc);
Ada.Text_IO.Put_Line (Stream.To_String);
end;
end if;
end Parse;
procedure Parse_Url (Url : in String) is
Command : constant String := "wget -q -O - " & Url;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Pipe.Open (Command);
Buffer.Initialize (null, Pipe'Unchecked_Access, 1024 * 1024);
Buffer.Read (Content);
Pipe.Close;
if Pipe.Get_Exit_Status /= 0 then
Ada.Text_IO.Put_Line (Command & " exited with status "
& Integer'Image (Pipe.Get_Exit_Status));
else
Parse (To_String (Content));
end if;
end Parse_Url;
function Is_Url (Name : in String) return Boolean is
begin
if Name'Length <= 9 then
return False;
else
return Name (Name'First .. Name'First + 6) = "http://"
or Name (Name'First .. Name'First + 7) = "https://";
end if;
end Is_Url;
begin
loop
case Getopt ("m M d c t f:") is
when 'm' =>
Syntax := Wiki.Parsers.SYNTAX_MARKDOWN;
Wiki_Mode := True;
when 'M' =>
Syntax := Wiki.Parsers.SYNTAX_MEDIA_WIKI;
Wiki_Mode := True;
when 'c' =>
Syntax := Wiki.Parsers.SYNTAX_CREOLE;
Wiki_Mode := True;
when 'd' =>
Syntax := Wiki.Parsers.SYNTAX_DOTCLEAR;
Wiki_Mode := True;
when 't' =>
Html_Mode := False;
when 'f' =>
declare
Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter);
begin
Html_Filter.Hide (Wiki.Nodes.Html_Tag_Type'Value (Value & "_TAG"));
exception
when Constraint_Error =>
Ada.Text_IO.Put_Line ("Invalid tag " & Value);
end;
when others =>
exit;
end case;
end loop;
loop
declare
Name : constant String := GNAT.Command_Line.Get_Argument;
Data : Unbounded_String;
begin
if Name = "" then
if Count = 0 then
Usage;
end if;
return;
end if;
Count := Count + 1;
if Is_Url (Name) then
Parse_Url (Name);
else
Util.Files.Read_File (Name, Data);
Parse (To_String (Data));
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'");
end;
end loop;
exception
when Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid option.");
Usage;
end Import;
|
Update the import example to use the new Wiki implementation
|
Update the import example to use the new Wiki implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
194422de10ad854a6f94dab053f5e737ec420547
|
samples/render.adb
|
samples/render.adb
|
-----------------------------------------------------------------------
-- render -- Wiki rendering example
-- Copyright (C) 2015, 2016, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Directories;
with GNAT.Command_Line;
with Wiki.Documents;
with Wiki.Parsers;
with Wiki.Filters.TOC;
with Wiki.Filters.Html;
with Wiki.Filters.Autolink;
with Wiki.Plugins.Templates;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Unbounded;
procedure Usage;
procedure Render_Html (Doc : in out Wiki.Documents.Document;
Style : in Unbounded_String);
procedure Render_Text (Doc : in out Wiki.Documents.Document);
procedure Usage is
begin
Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text");
Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-H] [-d] [-c] [-s style] {wiki-file}");
Ada.Text_IO.Put_Line (" -t Render to text only");
Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content");
Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content");
Ada.Text_IO.Put_Line (" -H Render a HTML wiki content");
Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content");
Ada.Text_IO.Put_Line (" -g Render a Google wiki content");
Ada.Text_IO.Put_Line (" -c Render a Creole wiki content");
Ada.Text_IO.Put_Line (" -s style Use the CSS style file");
end Usage;
procedure Render_Html (Doc : in out Wiki.Documents.Document;
Style : in Unbounded_String) is
Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
if Length (Style) > 0 then
Output.Start_Element ("html");
Output.Start_Element ("head");
Output.Start_Element ("link");
Output.Write_Attribute ("type", "text/css");
Output.Write_Attribute ("rel", "stylesheet");
Output.Write_Attribute ("href", To_String (Style));
Output.End_Element ("link");
Output.End_Element ("head");
Output.Start_Element ("body");
end if;
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Set_Render_TOC (True);
Renderer.Render (Doc);
if Length (Style) > 0 then
Output.End_Element ("body");
Output.End_Element ("html");
end if;
end Render_Html;
procedure Render_Text (Doc : in out Wiki.Documents.Document) is
Output : aliased Wiki.Streams.Text_IO.File_Output_Stream;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
end Render_Text;
Count : Natural := 0;
Html_Mode : Boolean := True;
Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN;
Style : Unbounded_String;
begin
loop
case Getopt ("m M d c g t H s:") is
when 'm' =>
Syntax := Wiki.SYNTAX_MARKDOWN;
when 'M' =>
Syntax := Wiki.SYNTAX_MEDIA_WIKI;
when 'c' =>
Syntax := Wiki.SYNTAX_CREOLE;
when 'd' =>
Syntax := Wiki.SYNTAX_DOTCLEAR;
when 'H' =>
Syntax := Wiki.SYNTAX_HTML;
when 'g' =>
Syntax := Wiki.SYNTAX_GOOGLE;
when 't' =>
Html_Mode := False;
when 's' =>
Style := To_Unbounded_String (Parameter);
when others =>
exit;
end case;
end loop;
loop
declare
Name : constant String := GNAT.Command_Line.Get_Argument;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
TOC : aliased Wiki.Filters.TOC.TOC_Filter;
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
begin
if Name = "" then
if Count = 0 then
Usage;
end if;
return;
end if;
Count := Count + 1;
Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name));
-- Open the file and parse it (assume UTF-8).
Input.Open (Name, "WCEM=8");
Engine.Set_Plugin_Factory (Template'Unchecked_Access);
Engine.Add_Filter (TOC'Unchecked_Access);
Engine.Add_Filter (Autolink'Unchecked_Access);
Engine.Add_Filter (Filter'Unchecked_Access);
Engine.Set_Syntax (Syntax);
Engine.Parse (Input'Unchecked_Access, Doc);
-- Render the document in text or HTML.
if Html_Mode then
Render_Html (Doc, Style);
else
Render_Text (Doc);
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'");
end;
end loop;
exception
when Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid option.");
Usage;
end Render;
|
-----------------------------------------------------------------------
-- render -- Wiki rendering example
-- Copyright (C) 2015, 2016, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Directories;
with GNAT.Command_Line;
with Wiki.Documents;
with Wiki.Parsers;
with Wiki.Filters.TOC;
with Wiki.Filters.Html;
with Wiki.Filters.Autolink;
with Wiki.Plugins.Templates;
with Wiki.Render.Html;
with Wiki.Render.Text;
with Wiki.Streams.Text_IO;
with Wiki.Streams.Html.Text_IO;
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Unbounded;
procedure Usage;
procedure Render_Html (Doc : in out Wiki.Documents.Document;
Style : in Unbounded_String);
procedure Render_Text (Doc : in out Wiki.Documents.Document);
procedure Usage is
begin
Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text");
Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-H] [-d] [-c] [-s style] {wiki-file}");
Ada.Text_IO.Put_Line (" -t Render to text only");
Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content");
Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content");
Ada.Text_IO.Put_Line (" -T Render a Textile wiki content");
Ada.Text_IO.Put_Line (" -H Render a HTML wiki content");
Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content");
Ada.Text_IO.Put_Line (" -g Render a Google wiki content");
Ada.Text_IO.Put_Line (" -c Render a Creole wiki content");
Ada.Text_IO.Put_Line (" -s style Use the CSS style file");
end Usage;
procedure Render_Html (Doc : in out Wiki.Documents.Document;
Style : in Unbounded_String) is
Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
if Length (Style) > 0 then
Output.Start_Element ("html");
Output.Start_Element ("head");
Output.Start_Element ("link");
Output.Write_Attribute ("type", "text/css");
Output.Write_Attribute ("rel", "stylesheet");
Output.Write_Attribute ("href", To_String (Style));
Output.End_Element ("link");
Output.End_Element ("head");
Output.Start_Element ("body");
end if;
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Set_Render_TOC (True);
Renderer.Render (Doc);
if Length (Style) > 0 then
Output.End_Element ("body");
Output.End_Element ("html");
end if;
end Render_Html;
procedure Render_Text (Doc : in out Wiki.Documents.Document) is
Output : aliased Wiki.Streams.Text_IO.File_Output_Stream;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Output_Stream (Output'Unchecked_Access);
Renderer.Render (Doc);
end Render_Text;
Count : Natural := 0;
Html_Mode : Boolean := True;
Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN;
Style : Unbounded_String;
begin
loop
case Getopt ("m M d c g t T H s:") is
when 'm' =>
Syntax := Wiki.SYNTAX_MARKDOWN;
when 'M' =>
Syntax := Wiki.SYNTAX_MEDIA_WIKI;
when 'c' =>
Syntax := Wiki.SYNTAX_CREOLE;
when 'd' =>
Syntax := Wiki.SYNTAX_DOTCLEAR;
when 'H' =>
Syntax := Wiki.SYNTAX_HTML;
when 'T' =>
Syntax := Wiki.SYNTAX_TEXTILE;
when 'g' =>
Syntax := Wiki.SYNTAX_GOOGLE;
when 't' =>
Html_Mode := False;
when 's' =>
Style := To_Unbounded_String (Parameter);
when others =>
exit;
end case;
end loop;
loop
declare
Name : constant String := GNAT.Command_Line.Get_Argument;
Input : aliased Wiki.Streams.Text_IO.File_Input_Stream;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter;
Template : aliased Wiki.Plugins.Templates.File_Template_Plugin;
TOC : aliased Wiki.Filters.TOC.TOC_Filter;
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
begin
if Name = "" then
if Count = 0 then
Usage;
end if;
return;
end if;
Count := Count + 1;
Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name));
-- Open the file and parse it (assume UTF-8).
Input.Open (Name, "WCEM=8");
Engine.Set_Plugin_Factory (Template'Unchecked_Access);
Engine.Add_Filter (TOC'Unchecked_Access);
Engine.Add_Filter (Autolink'Unchecked_Access);
Engine.Add_Filter (Filter'Unchecked_Access);
Engine.Set_Syntax (Syntax);
Engine.Parse (Input'Unchecked_Access, Doc);
-- Render the document in text or HTML.
if Html_Mode then
Render_Html (Doc, Style);
else
Render_Text (Doc);
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'");
end;
end loop;
exception
when Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid option.");
Usage;
end Render;
|
Add -T option to choose the Textile syntax
|
Add -T option to choose the Textile syntax
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
aff7be3f3f173bc5b705edbd6e8131a1e4665c8b
|
src/asf-views-nodes-core.adb
|
src/asf-views-nodes-core.adb
|
-----------------------------------------------------------------------
-- nodes-core -- Core nodes
-- 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 Util.Strings.Transforms;
package body ASF.Views.Nodes.Core is
-- ------------------------------
-- Set Tag
-- ------------------------------
-- ------------------------------
-- Create the Set Tag
-- ------------------------------
function Create_Set_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Set_Tag_Node_Access := new Set_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Value := Find_Attribute (Attributes, "value");
Node.Var := Find_Attribute (Attributes, "var");
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
if Node.Var = null then
Node.Error ("Missing 'var' attribute");
end if;
return Node.all'Access;
end Create_Set_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Set_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
pragma Unreferenced (Parent);
Value : constant EL.Expressions.Expression
:= Get_Expression (Node.Value.all);
begin
Context.Set_Variable (Node.Var.Value, Value);
end Build_Components;
-- ------------------------------
-- If Tag
-- ------------------------------
-- ------------------------------
-- Create the If Tag
-- ------------------------------
function Create_If_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant If_Tag_Node_Access := new If_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Condition := Find_Attribute (Attributes, "test");
Node.Var := Find_Attribute (Attributes, "var");
if Node.Condition = null then
Node.Error ("Missing 'test' attribute");
end if;
return Node.all'Access;
end Create_If_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access If_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
Value : constant EL.Objects.Object := Get_Value (Node.Condition.all, Context);
begin
if Node.Var /= null then
Context.Set_Attribute (Node.Var.Value, Value);
end if;
if EL.Objects.To_Boolean (Value) then
Tag_Node (Node.all).Build_Children (Parent, Context);
end if;
end Build_Components;
-- ------------------------------
-- Choose Tag
-- ------------------------------
-- ------------------------------
-- Create the Choose Tag
-- ------------------------------
function Create_Choose_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Choose_Tag_Node_Access := new Choose_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Choose_Tag_Node;
-- ------------------------------
-- Freeze the tag node tree and perform any initialization steps
-- necessary to build the components efficiently.
-- Prepare the evaluation of choices by identifying the <c:when> and
-- <c:otherwise> conditions.
-- ------------------------------
overriding
procedure Freeze (Node : access Choose_Tag_Node) is
Child : Tag_Node_Access := Node.First_Child;
Choice : When_Tag_Node_Access := null;
begin
while Child /= null loop
if Child.all in Otherwise_Tag_Node'Class then
Node.Otherwise := Child;
elsif Child.all in When_Tag_Node'Class then
if Choice = null then
Node.Choices := When_Tag_Node (Child.all)'Access;
else
Choice.Next_Choice := When_Tag_Node (Child.all)'Access;
end if;
Choice := When_Tag_Node (Child.all)'Access;
else
null;
-- @todo: report a warning in a log
-- @todo: clean the sub-tree and remove what is not necessary
end if;
Child := Child.Next;
end loop;
end Freeze;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Choose_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
Choice : When_Tag_Node_Access := Node.Choices;
begin
-- Evaluate the choices and stop at the first which succeeds
while Choice /= null loop
if Choice.Is_Selected (Context) then
Choice.Build_Children (Parent, Context);
return;
end if;
Choice := Choice.Next_Choice;
end loop;
-- No choice matched, build the otherwise clause.
if Node.Otherwise /= null then
Node.Otherwise.Build_Children (Parent, Context);
end if;
end Build_Components;
-- ------------------------------
-- Create the When Tag
-- ------------------------------
function Create_When_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant When_Tag_Node_Access := new When_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Condition := Find_Attribute (Attributes, "test");
if Node.Condition = null then
Node.Error ("Missing 'test' attribute");
end if;
-- Node.Var := Find_Attribute (Attributes, "var");
return Node.all'Access;
end Create_When_Tag_Node;
-- ------------------------------
-- Check whether the node condition is selected.
-- ------------------------------
function Is_Selected (Node : When_Tag_Node;
Context : Facelet_Context'Class) return Boolean is
begin
return EL.Objects.To_Boolean (Get_Value (Node.Condition.all, Context));
end Is_Selected;
-- ------------------------------
-- Create the Otherwise Tag
-- ------------------------------
function Create_Otherwise_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Otherwise_Tag_Node_Access := new Otherwise_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Otherwise_Tag_Node;
-- Tag names
CHOOSE_TAG : aliased constant String := "choose";
IF_TAG : aliased constant String := "if";
OTHERWISE_TAG : aliased constant String := "otherwise";
SET_TAG : aliased constant String := "set";
WHEN_TAG : aliased constant String := "when";
-- Name-space URI. Use the JSTL name-space to make the XHTML views compatible
-- the JSF.
URI : aliased constant String := "http://java.sun.com/jstl/core";
-- Tag library definition. Names must be sorted.
Tag_Bindings : aliased constant ASF.Factory.Binding_Array
:= ((Name => CHOOSE_TAG'Access,
Component => null,
Tag => Create_Choose_Tag_Node'Access),
(Name => IF_TAG'Access,
Component => null,
Tag => Create_If_Tag_Node'Access),
(Name => OTHERWISE_TAG'Access,
Component => null,
Tag => Create_Otherwise_Tag_Node'Access),
(Name => SET_TAG'Access,
Component => null,
Tag => Create_Set_Tag_Node'Access),
(Name => WHEN_TAG'Access,
Component => null,
Tag => Create_When_Tag_Node'Access));
Tag_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Tag_Bindings'Access);
-- ------------------------------
-- Tag factory for nodes defined in this package.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Tag_Factory'Access;
end Definition;
-- Function names
CAPITALIZE_FN : aliased constant String := "capitalize";
TO_UPPER_CASE_FN : aliased constant String := "toUpperCase";
TO_LOWER_CASE_FN : aliased constant String := "toLowerCase";
function Capitalize (Value : EL.Objects.Object) return EL.Objects.Object;
function To_Upper_Case (Value : EL.Objects.Object) return EL.Objects.Object;
function To_Lower_Case (Value : EL.Objects.Object) return EL.Objects.Object;
function Capitalize (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.Capitalize (S));
end Capitalize;
function To_Upper_Case (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.To_Upper_Case (S));
end To_Upper_Case;
function To_Lower_Case (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.To_Lower_Case (S));
end To_Lower_Case;
-- ------------------------------
-- Register a set of functions in the namespace
-- xmlns:fn="http://java.sun.com/jsp/jstl/functions"
-- Functions:
-- capitalize, toUpperCase, toLowerCase
-- ------------------------------
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
URI : constant String := "http://java.sun.com/jsp/jstl/functions";
begin
Mapper.Set_Function (Name => CAPITALIZE_FN,
Namespace => URI,
Func => Capitalize'Access);
Mapper.Set_Function (Name => TO_LOWER_CASE_FN,
Namespace => URI,
Func => To_Lower_Case'Access);
Mapper.Set_Function (Name => TO_UPPER_CASE_FN,
Namespace => URI,
Func => To_Upper_Case'Access);
end Set_Functions;
end ASF.Views.Nodes.Core;
|
-----------------------------------------------------------------------
-- nodes-core -- Core nodes
-- 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 Util.Strings.Transforms;
with Ada.Strings.Fixed;
package body ASF.Views.Nodes.Core is
-- ------------------------------
-- Set Tag
-- ------------------------------
-- ------------------------------
-- Create the Set Tag
-- ------------------------------
function Create_Set_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Set_Tag_Node_Access := new Set_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Value := Find_Attribute (Attributes, "value");
Node.Var := Find_Attribute (Attributes, "var");
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
if Node.Var = null then
Node.Error ("Missing 'var' attribute");
end if;
return Node.all'Access;
end Create_Set_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Set_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
pragma Unreferenced (Parent);
Value : constant EL.Expressions.Expression
:= Get_Expression (Node.Value.all);
begin
Context.Set_Variable (Node.Var.Value, Value);
end Build_Components;
-- ------------------------------
-- If Tag
-- ------------------------------
-- ------------------------------
-- Create the If Tag
-- ------------------------------
function Create_If_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant If_Tag_Node_Access := new If_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Condition := Find_Attribute (Attributes, "test");
Node.Var := Find_Attribute (Attributes, "var");
if Node.Condition = null then
Node.Error ("Missing 'test' attribute");
end if;
return Node.all'Access;
end Create_If_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access If_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
Value : constant EL.Objects.Object := Get_Value (Node.Condition.all, Context);
begin
if Node.Var /= null then
Context.Set_Attribute (Node.Var.Value, Value);
end if;
if EL.Objects.To_Boolean (Value) then
Tag_Node (Node.all).Build_Children (Parent, Context);
end if;
end Build_Components;
-- ------------------------------
-- Choose Tag
-- ------------------------------
-- ------------------------------
-- Create the Choose Tag
-- ------------------------------
function Create_Choose_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Choose_Tag_Node_Access := new Choose_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Choose_Tag_Node;
-- ------------------------------
-- Freeze the tag node tree and perform any initialization steps
-- necessary to build the components efficiently.
-- Prepare the evaluation of choices by identifying the <c:when> and
-- <c:otherwise> conditions.
-- ------------------------------
overriding
procedure Freeze (Node : access Choose_Tag_Node) is
Child : Tag_Node_Access := Node.First_Child;
Choice : When_Tag_Node_Access := null;
begin
while Child /= null loop
if Child.all in Otherwise_Tag_Node'Class then
Node.Otherwise := Child;
elsif Child.all in When_Tag_Node'Class then
if Choice = null then
Node.Choices := When_Tag_Node (Child.all)'Access;
else
Choice.Next_Choice := When_Tag_Node (Child.all)'Access;
end if;
Choice := When_Tag_Node (Child.all)'Access;
else
null;
-- @todo: report a warning in a log
-- @todo: clean the sub-tree and remove what is not necessary
end if;
Child := Child.Next;
end loop;
end Freeze;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Choose_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
Choice : When_Tag_Node_Access := Node.Choices;
begin
-- Evaluate the choices and stop at the first which succeeds
while Choice /= null loop
if Choice.Is_Selected (Context) then
Choice.Build_Children (Parent, Context);
return;
end if;
Choice := Choice.Next_Choice;
end loop;
-- No choice matched, build the otherwise clause.
if Node.Otherwise /= null then
Node.Otherwise.Build_Children (Parent, Context);
end if;
end Build_Components;
-- ------------------------------
-- Create the When Tag
-- ------------------------------
function Create_When_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant When_Tag_Node_Access := new When_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Condition := Find_Attribute (Attributes, "test");
if Node.Condition = null then
Node.Error ("Missing 'test' attribute");
end if;
-- Node.Var := Find_Attribute (Attributes, "var");
return Node.all'Access;
end Create_When_Tag_Node;
-- ------------------------------
-- Check whether the node condition is selected.
-- ------------------------------
function Is_Selected (Node : When_Tag_Node;
Context : Facelet_Context'Class) return Boolean is
begin
return EL.Objects.To_Boolean (Get_Value (Node.Condition.all, Context));
end Is_Selected;
-- ------------------------------
-- Create the Otherwise Tag
-- ------------------------------
function Create_Otherwise_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Otherwise_Tag_Node_Access := new Otherwise_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Otherwise_Tag_Node;
-- Tag names
CHOOSE_TAG : aliased constant String := "choose";
IF_TAG : aliased constant String := "if";
OTHERWISE_TAG : aliased constant String := "otherwise";
SET_TAG : aliased constant String := "set";
WHEN_TAG : aliased constant String := "when";
-- Name-space URI. Use the JSTL name-space to make the XHTML views compatible
-- the JSF.
URI : aliased constant String := "http://java.sun.com/jstl/core";
-- Tag library definition. Names must be sorted.
Tag_Bindings : aliased constant ASF.Factory.Binding_Array
:= ((Name => CHOOSE_TAG'Access,
Component => null,
Tag => Create_Choose_Tag_Node'Access),
(Name => IF_TAG'Access,
Component => null,
Tag => Create_If_Tag_Node'Access),
(Name => OTHERWISE_TAG'Access,
Component => null,
Tag => Create_Otherwise_Tag_Node'Access),
(Name => SET_TAG'Access,
Component => null,
Tag => Create_Set_Tag_Node'Access),
(Name => WHEN_TAG'Access,
Component => null,
Tag => Create_When_Tag_Node'Access));
Tag_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Tag_Bindings'Access);
-- ------------------------------
-- Tag factory for nodes defined in this package.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Tag_Factory'Access;
end Definition;
-- Function names
CAPITALIZE_FN : aliased constant String := "capitalize";
TO_UPPER_CASE_FN : aliased constant String := "toUpperCase";
TO_LOWER_CASE_FN : aliased constant String := "toLowerCase";
SUBSTRING_AFTER_FN : aliased constant String := "substringAfter";
SUBSTRING_BEFORE_FN : aliased constant String := "substringBefore";
function Capitalize (Value : EL.Objects.Object) return EL.Objects.Object;
function To_Upper_Case (Value : EL.Objects.Object) return EL.Objects.Object;
function To_Lower_Case (Value : EL.Objects.Object) return EL.Objects.Object;
function Substring_Before (Value : in EL.Objects.Object;
Token : in EL.Objects.Object) return EL.Objects.Object;
function Substring_After (Value : in EL.Objects.Object;
Token : in EL.Objects.Object) return EL.Objects.Object;
function Capitalize (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.Capitalize (S));
end Capitalize;
function To_Upper_Case (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.To_Upper_Case (S));
end To_Upper_Case;
function To_Lower_Case (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.To_Lower_Case (S));
end To_Lower_Case;
-- ------------------------------
-- Return the substring before the token string
-- ------------------------------
function Substring_Before (Value : in EL.Objects.Object;
Token : in EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
T : constant String := EL.Objects.To_String (Token);
Pos : constant Natural := Ada.Strings.Fixed.Index (S, T);
begin
if Pos = 0 then
return EL.Objects.Null_Object;
else
return EL.Objects.To_Object (S (S'First .. Pos - 1));
end if;
end Substring_Before;
-- ------------------------------
-- Return the substring after the token string
-- ------------------------------
function Substring_After (Value : in EL.Objects.Object;
Token : in EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
T : constant String := EL.Objects.To_String (Token);
Pos : constant Natural := Ada.Strings.Fixed.Index (S, T);
begin
if Pos = 0 then
return EL.Objects.Null_Object;
else
return EL.Objects.To_Object (S (Pos + T'Length .. S'Last));
end if;
end Substring_After;
-- ------------------------------
-- Register a set of functions in the namespace
-- xmlns:fn="http://java.sun.com/jsp/jstl/functions"
-- Functions:
-- capitalize, toUpperCase, toLowerCase
-- ------------------------------
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
URI : constant String := "http://java.sun.com/jsp/jstl/functions";
begin
Mapper.Set_Function (Name => CAPITALIZE_FN,
Namespace => URI,
Func => Capitalize'Access);
Mapper.Set_Function (Name => TO_LOWER_CASE_FN,
Namespace => URI,
Func => To_Lower_Case'Access);
Mapper.Set_Function (Name => TO_UPPER_CASE_FN,
Namespace => URI,
Func => To_Upper_Case'Access);
Mapper.Set_Function (Name => SUBSTRING_BEFORE_FN,
Namespace => URI,
Func => Substring_Before'Access);
Mapper.Set_Function (Name => SUBSTRING_AFTER_FN,
Namespace => URI,
Func => Substring_After'Access);
end Set_Functions;
end ASF.Views.Nodes.Core;
|
Add substring before and substring after EL functions
|
Add substring before and substring after EL functions
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
d9e988b8b217c688c0dd35b42cbcecfd7fc2706f
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
|
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- 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.Tests;
with Ada.Strings.Unbounded;
package AWA.Blogs.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with record
Blog_Ident : Ada.Strings.Unbounded.Unbounded_String;
Post_Ident : Ada.Strings.Unbounded.Unbounded_String;
Post_Uri : Ada.Strings.Unbounded.Unbounded_String;
end record;
-- Get some access on the blog as anonymous users.
procedure Verify_Anonymous (T : in out Test;
Post : in String);
-- Test access to the blog as anonymous user.
procedure Test_Anonymous_Access (T : in out Test);
-- Test creation of blog by simulating web requests.
procedure Test_Create_Blog (T : in out Test);
-- Test updating a post by simulating web requests.
procedure Test_Update_Post (T : in out Test);
-- Test listing the blog posts.
procedure Test_Admin_List_Posts (T : in out Test);
-- Test listing the blog comments.
procedure Test_Admin_List_Comments (T : in out Test);
-- Test getting the JSON blog stats (for graphs).
procedure Test_Admin_Blog_Stats (T : in out Test);
end AWA.Blogs.Tests;
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- 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.Tests;
with AWA.Tests;
with Ada.Strings.Unbounded;
package AWA.Blogs.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Blog_Ident : Ada.Strings.Unbounded.Unbounded_String;
Post_Ident : Ada.Strings.Unbounded.Unbounded_String;
Post_Uri : Ada.Strings.Unbounded.Unbounded_String;
end record;
-- Get some access on the blog as anonymous users.
procedure Verify_Anonymous (T : in out Test;
Post : in String);
-- Test access to the blog as anonymous user.
procedure Test_Anonymous_Access (T : in out Test);
-- Test creation of blog by simulating web requests.
procedure Test_Create_Blog (T : in out Test);
-- Test updating a post by simulating web requests.
procedure Test_Update_Post (T : in out Test);
-- Test listing the blog posts.
procedure Test_Admin_List_Posts (T : in out Test);
-- Test listing the blog comments.
procedure Test_Admin_List_Comments (T : in out Test);
-- Test getting the JSON blog stats (for graphs).
procedure Test_Admin_Blog_Stats (T : in out Test);
end AWA.Blogs.Tests;
|
Update the test declaration to use AWA.Tests.Test type
|
Update the test declaration to use AWA.Tests.Test type
|
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.