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
|
---|---|---|---|---|---|---|---|---|---|
5f4b7dc824578d155e5112dba4a4173e5d08e6a7
|
src/gen-model-tables.adb
|
src/gen-model-tables.adb
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Util.Strings;
with Util.Log.Loggers;
package body Gen.Model.Tables is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables");
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if Name = "type" then
declare
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T = null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC);
end;
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "index" then
return Util.Beans.Objects.To_Object (From.Number);
elsif Name = "isUnique" then
return Util.Beans.Objects.To_Object (From.Unique);
elsif Name = "isNull" then
return Util.Beans.Objects.To_Object (not From.Not_Null);
elsif Name = "isInserted" then
return Util.Beans.Objects.To_Object (From.Is_Inserted);
elsif Name = "isUpdated" then
return Util.Beans.Objects.To_Object (From.Is_Updated);
elsif Name = "sqlType" then
if Length (From.Sql_Type) > 0 then
return Util.Beans.Objects.To_Object (From.Sql_Type);
end if;
declare
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T = null then
return Util.Beans.Objects.Null_Object;
end if;
return T.Get_Value ("name");
end;
elsif Name = "sqlName" then
return Util.Beans.Objects.To_Object (From.Sql_Name);
elsif Name = "isVersion" then
return Util.Beans.Objects.To_Object (From.Is_Version);
elsif Name = "isReadable" then
return Util.Beans.Objects.To_Object (From.Is_Readable);
elsif Name = "isPrimaryKey" then
return Util.Beans.Objects.To_Object (From.Is_Key);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Is_Basic_Type);
elsif Name = "generator" then
return From.Generator;
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Returns true if the column type is a basic type.
-- ------------------------------
function Is_Basic_Type (From : in Column_Definition) return Boolean is
use type Gen.Model.Mappings.Mapping_Definition_Access;
use type Gen.Model.Mappings.Basic_Type;
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
Name : constant String := To_String (From.Type_Name);
begin
if T /= null then
return T.Kind /= Gen.Model.Mappings.T_BLOB;
end if;
return Name = "int" or Name = "String"
or Name = "ADO.Identifier" or Name = "Timestamp"
or Name = "Integer"
or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time";
end Is_Basic_Type;
-- ------------------------------
-- Returns the column type.
-- ------------------------------
function Get_Type (From : in Column_Definition) return String is
use type Gen.Model.Mappings.Mapping_Definition_Access;
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T /= null then
return To_String (T.Target);
else
return To_String (From.Type_Name);
end if;
end Get_Type;
-- ------------------------------
-- Returns the column type mapping.
-- ------------------------------
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access is
use type Mappings.Mapping_Definition_Access;
Result : Gen.Model.Mappings.Mapping_Definition_Access := null;
Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, ".");
begin
if Pos = 0 then
Result := Gen.Model.Mappings.Find_Type (From.Type_Name);
end if;
if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then
Log.Debug ("Found enum");
end if;
if Result = null then
Result := From.Table.Package_Def.Find_Type (From.Type_Name);
end if;
return Result;
end Get_Type_Mapping;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Column_Definition) is
use type Mappings.Mapping_Definition_Access;
begin
-- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name);
-- if O.Type_Mapping = null then
-- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name);
-- end if;
null;
end Prepare;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
return Column_Definition (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Table_Definition) is
begin
O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access,
Util.Beans.Objects.STATIC);
O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Create a table with the given name.
-- ------------------------------
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is
Table : constant Table_Definition_Access := new Table_Definition;
begin
Table.Name := Name;
declare
Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1);
Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
Table.Table_Name := Table.Type_Name;
end;
return Table;
end Create_Table;
-- ------------------------------
-- Create a table column with the given name and add it to the table.
-- ------------------------------
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access) is
begin
Column := new Column_Definition;
Column.Name := Name;
Column.Sql_Name := Name;
Column.Number := Table.Members.Get_Count;
Column.Table := Table'Unchecked_Access;
Table.Members.Append (Column);
if Name = "version" then
Table.Version_Column := Column;
Column.Is_Version := True;
Column.Is_Updated := False;
Column.Is_Inserted := False;
elsif Name = "id" then
Table.Id_Column := Column;
Column.Is_Key := True;
end if;
end Add_Column;
-- ------------------------------
-- Create a table association with the given name and add it to the table.
-- ------------------------------
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access) is
begin
Assoc := new Association_Definition;
Assoc.Name := Name;
Assoc.Number := Table.Members.Get_Count;
Assoc.Table := Table'Unchecked_Access;
Table.Members.Append (Assoc.all'Access);
Table.Has_Associations := True;
end Add_Association;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Table_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" or Name = "columns" then
return From.Members_Bean;
elsif Name = "operations" then
return From.Operations_Bean;
elsif Name = "id" and From.Id_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "version" and From.Version_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= From.Version_Column.all'Unchecked_Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "hasAssociations" then
return Util.Beans.Objects.To_Object (From.Has_Associations);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "table" then
return Util.Beans.Objects.To_Object (From.Table_Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Table_Definition) is
Iter : Column_List.Cursor := O.Members.First;
begin
while Column_List.Has_Element (Iter) loop
Column_List.Element (Iter).Prepare;
Column_List.Next (Iter);
end loop;
end Prepare;
-- ------------------------------
-- Set the table name and determines the package name.
-- ------------------------------
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
Table.Name := To_Unbounded_String (Name);
if Pos > 0 then
Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1));
Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end Set_Table_Name;
end Gen.Model.Tables;
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Util.Strings;
with Util.Log.Loggers;
package body Gen.Model.Tables is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables");
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if Name = "type" then
declare
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T = null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC);
end;
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "index" then
return Util.Beans.Objects.To_Object (From.Number);
elsif Name = "isUnique" then
return Util.Beans.Objects.To_Object (From.Unique);
elsif Name = "isNull" then
return Util.Beans.Objects.To_Object (not From.Not_Null);
elsif Name = "isInserted" then
return Util.Beans.Objects.To_Object (From.Is_Inserted);
elsif Name = "isUpdated" then
return Util.Beans.Objects.To_Object (From.Is_Updated);
elsif Name = "sqlType" then
if Length (From.Sql_Type) > 0 then
return Util.Beans.Objects.To_Object (From.Sql_Type);
end if;
declare
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T = null then
return Util.Beans.Objects.Null_Object;
end if;
return T.Get_Value ("name");
end;
elsif Name = "sqlName" then
return Util.Beans.Objects.To_Object (From.Sql_Name);
elsif Name = "isVersion" then
return Util.Beans.Objects.To_Object (From.Is_Version);
elsif Name = "isReadable" then
return Util.Beans.Objects.To_Object (From.Is_Readable);
elsif Name = "isPrimaryKey" then
return Util.Beans.Objects.To_Object (From.Is_Key);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Is_Basic_Type);
elsif Name = "generator" then
return From.Generator;
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Returns true if the column type is a basic type.
-- ------------------------------
function Is_Basic_Type (From : in Column_Definition) return Boolean is
use type Gen.Model.Mappings.Mapping_Definition_Access;
use type Gen.Model.Mappings.Basic_Type;
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
Name : constant String := To_String (From.Type_Name);
begin
if T /= null then
return T.Kind /= Gen.Model.Mappings.T_BLOB;
end if;
return Name = "int" or Name = "String"
or Name = "ADO.Identifier" or Name = "Timestamp"
or Name = "Integer"
or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time";
end Is_Basic_Type;
-- ------------------------------
-- Returns the column type.
-- ------------------------------
function Get_Type (From : in Column_Definition) return String is
use type Gen.Model.Mappings.Mapping_Definition_Access;
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T /= null then
return To_String (T.Target);
else
return To_String (From.Type_Name);
end if;
end Get_Type;
-- ------------------------------
-- Returns the column type mapping.
-- ------------------------------
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access is
use type Mappings.Mapping_Definition_Access;
Result : Gen.Model.Mappings.Mapping_Definition_Access := null;
Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, ".");
begin
if Pos = 0 then
Result := Gen.Model.Mappings.Find_Type (From.Type_Name);
end if;
if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then
Log.Debug ("Found enum");
end if;
if Result = null then
Result := From.Table.Package_Def.Find_Type (From.Type_Name);
end if;
return Result;
end Get_Type_Mapping;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Column_Definition) is
use type Mappings.Mapping_Definition_Access;
begin
-- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name);
-- if O.Type_Mapping = null then
-- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name);
-- end if;
null;
end Prepare;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
return Column_Definition (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Table_Definition) is
begin
O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access,
Util.Beans.Objects.STATIC);
O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Create a table with the given name.
-- ------------------------------
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is
Table : constant Table_Definition_Access := new Table_Definition;
begin
Table.Name := Name;
declare
Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1);
Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
Table.Table_Name := Table.Type_Name;
end;
return Table;
end Create_Table;
-- ------------------------------
-- Create a table column with the given name and add it to the table.
-- ------------------------------
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access) is
begin
Column := new Column_Definition;
Column.Name := Name;
Column.Sql_Name := Name;
Column.Number := Table.Members.Get_Count;
Column.Table := Table'Unchecked_Access;
Table.Members.Append (Column);
if Name = "version" then
Table.Version_Column := Column;
Column.Is_Version := True;
Column.Is_Updated := False;
Column.Is_Inserted := False;
elsif Name = "id" then
Table.Id_Column := Column;
Column.Is_Key := True;
end if;
end Add_Column;
-- ------------------------------
-- Create a table association with the given name and add it to the table.
-- ------------------------------
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access) is
begin
Assoc := new Association_Definition;
Assoc.Name := Name;
Assoc.Number := Table.Members.Get_Count;
Assoc.Table := Table'Unchecked_Access;
Assoc.Sql_Name := Name;
Table.Members.Append (Assoc.all'Access);
Table.Has_Associations := True;
end Add_Association;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Table_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" or Name = "columns" then
return From.Members_Bean;
elsif Name = "operations" then
return From.Operations_Bean;
elsif Name = "id" and From.Id_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "version" and From.Version_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= From.Version_Column.all'Unchecked_Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "hasAssociations" then
return Util.Beans.Objects.To_Object (From.Has_Associations);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "table" then
return Util.Beans.Objects.To_Object (From.Table_Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Table_Definition) is
Iter : Column_List.Cursor := O.Members.First;
begin
while Column_List.Has_Element (Iter) loop
Column_List.Element (Iter).Prepare;
Column_List.Next (Iter);
end loop;
end Prepare;
-- ------------------------------
-- Set the table name and determines the package name.
-- ------------------------------
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
Table.Name := To_Unbounded_String (Name);
if Pos > 0 then
Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1));
Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end Set_Table_Name;
end Gen.Model.Tables;
|
Set the association sql name from the association name
|
Set the association sql name from the association name
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
69490df2a9bf4e0560b9b41229d5bc65b677383d
|
src/wiki-attributes.adb
|
src/wiki-attributes.adb
|
-----------------------------------------------------------------------
-- wiki-attributes -- Wiki document attributes
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Attributes is
-- ------------------------------
-- Get the attribute name.
-- ------------------------------
function Get_Name (Position : in Cursor) return String is
Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos);
begin
return Attr.Value.Name;
end Get_Name;
-- ------------------------------
-- Get the attribute value.
-- ------------------------------
function Get_Value (Position : in Cursor) return String is
Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos);
begin
return Wiki.Strings.To_String (Attr.Value.Value);
end Get_Value;
-- ------------------------------
-- Get the attribute wide value.
-- ------------------------------
function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString is
Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos);
begin
return Attr.Value.Value;
end Get_Wide_Value;
-- ------------------------------
-- Returns True if the cursor has a valid attribute.
-- ------------------------------
function Has_Element (Position : in Cursor) return Boolean is
begin
return Attribute_Vectors.Has_Element (Position.Pos);
end Has_Element;
-- ------------------------------
-- Move the cursor to the next attribute.
-- ------------------------------
procedure Next (Position : in out Cursor) is
begin
Attribute_Vectors.Next (Position.Pos);
end Next;
-- ------------------------------
-- Find the attribute with the given name.
-- ------------------------------
function Find (List : in Attribute_List;
Name : in String) return Cursor is
Iter : Attribute_Vectors.Cursor := List.List.First;
begin
while Attribute_Vectors.Has_Element (Iter) loop
declare
Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter);
begin
if Attr.Value.Name = Name then
return Cursor '(Pos => Iter);
end if;
end;
Attribute_Vectors.Next (Iter);
end loop;
return Cursor '(Pos => Iter);
end Find;
-- ------------------------------
-- Find the attribute with the given name and return its value.
-- ------------------------------
function Get_Attribute (List : in Attribute_List;
Name : in String) return Wiki.Strings.WString is
Attr : constant Cursor := Find (List, Name);
begin
if Has_Element (Attr) then
return Get_Wide_Value (Attr);
else
return "";
end if;
end Get_Attribute;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
Attr : constant Attribute_Access
:= new Attribute '(Util.Refs.Ref_Entity with
Name_Length => Name'Length,
Value_Length => Value'Length,
Name => Wiki.Strings.To_String (Name),
Value => Value);
begin
List.List.Append (Attribute_Refs.Create (Attr));
end Append;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List;
Name : in String;
Value : in Wiki.Strings.WString) is
Attr : constant Attribute_Access
:= new Attribute '(Util.Refs.Ref_Entity with
Name_Length => Name'Length,
Value_Length => Value'Length,
Name => Name,
Value => Value);
begin
List.List.Append (Attribute_Refs.Create (Attr));
end Append;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List;
Name : in String;
Value : in Wiki.Strings.UString) is
Val : constant Wiki.Strings.WString := Wiki.Strings.To_WString (Value);
Attr : constant Attribute_Access
:= new Attribute '(Util.Refs.Ref_Entity with
Name_Length => Name'Length,
Value_Length => Val'Length,
Name => Name,
Value => Val);
begin
List.List.Append (Attribute_Refs.Create (Attr));
end Append;
-- ------------------------------
-- Get the cursor to get access to the first attribute.
-- ------------------------------
function First (List : in Attribute_List) return Cursor is
begin
return Cursor '(Pos => List.List.First);
end First;
-- ------------------------------
-- Get the number of attributes in the list.
-- ------------------------------
function Length (List : in Attribute_List) return Natural is
begin
return Natural (List.List.Length);
end Length;
-- ------------------------------
-- Clear the list and remove all existing attributes.
-- ------------------------------
procedure Clear (List : in out Attribute_List) is
begin
List.List.Clear;
end Clear;
-- ------------------------------
-- Iterate over the list attributes and call the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterate (List : in Attribute_List;
Process : not null access procedure (Name : in String;
Value : in Wiki.Strings.WString)) is
Iter : Attribute_Vectors.Cursor := List.List.First;
Item : Attribute_Ref;
begin
while Attribute_Vectors.Has_Element (Iter) loop
Item := Attribute_Vectors.Element (Iter);
Process (Item.Value.Name, Item.Value.Value);
Attribute_Vectors.Next (Iter);
end loop;
end Iterate;
-- ------------------------------
-- Finalize the attribute list releasing any storage.
-- ------------------------------
overriding
procedure Finalize (List : in out Attribute_List) is
begin
List.Clear;
end Finalize;
end Wiki.Attributes;
|
-----------------------------------------------------------------------
-- wiki-attributes -- Wiki document attributes
-- Copyright (C) 2015, 2016, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Attributes is
-- ------------------------------
-- Get the attribute name.
-- ------------------------------
function Get_Name (Position : in Cursor) return String is
Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos);
begin
return Attr.Value.Name;
end Get_Name;
-- ------------------------------
-- Get the attribute value.
-- ------------------------------
function Get_Value (Position : in Cursor) return String is
Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos);
begin
return Wiki.Strings.To_String (Attr.Value.Value);
end Get_Value;
-- ------------------------------
-- Get the attribute wide value.
-- ------------------------------
function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString is
Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos);
begin
return Attr.Value.Value;
end Get_Wide_Value;
-- ------------------------------
-- Returns True if the cursor has a valid attribute.
-- ------------------------------
function Has_Element (Position : in Cursor) return Boolean is
begin
return Attribute_Vectors.Has_Element (Position.Pos);
end Has_Element;
-- ------------------------------
-- Move the cursor to the next attribute.
-- ------------------------------
procedure Next (Position : in out Cursor) is
begin
Attribute_Vectors.Next (Position.Pos);
end Next;
-- ------------------------------
-- Find the attribute with the given name.
-- ------------------------------
function Find (List : in Attribute_List;
Name : in String) return Cursor is
Iter : Attribute_Vectors.Cursor := List.List.First;
begin
while Attribute_Vectors.Has_Element (Iter) loop
declare
Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter);
begin
if Attr.Value.Name = Name then
return Cursor '(Pos => Iter);
end if;
end;
Attribute_Vectors.Next (Iter);
end loop;
return Cursor '(Pos => Iter);
end Find;
-- ------------------------------
-- Find the attribute with the given name and return its value.
-- ------------------------------
function Get_Attribute (List : in Attribute_List;
Name : in String) return Wiki.Strings.WString is
Attr : constant Cursor := Find (List, Name);
begin
if Has_Element (Attr) then
return Get_Wide_Value (Attr);
else
return "";
end if;
end Get_Attribute;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List;
Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
Attr : constant Attribute_Access
:= new Attribute '(Util.Refs.Ref_Entity with
Name_Length => Name'Length,
Value_Length => Value'Length,
Name => Wiki.Strings.To_String (Name),
Value => Value);
begin
List.List.Append (Attribute_Refs.Create (Attr));
end Append;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List;
Name : in String;
Value : in Wiki.Strings.WString) is
Attr : constant Attribute_Access
:= new Attribute '(Util.Refs.Ref_Entity with
Name_Length => Name'Length,
Value_Length => Value'Length,
Name => Name,
Value => Value);
begin
List.List.Append (Attribute_Refs.Create (Attr));
end Append;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List;
Name : in String;
Value : in Wiki.Strings.UString) is
Val : constant Wiki.Strings.WString := Wiki.Strings.To_WString (Value);
begin
Append (List, Name, Val);
end Append;
procedure Append (List : in out Attribute_List;
Name : in String;
Value : in Wiki.Strings.BString) is
procedure Append (Content : in Wiki.Strings.WString) is
begin
Append (List, Name, Content);
end Append;
procedure Append_Attribute is
new Wiki.Strings.Wide_Wide_Builders.Get (Append);
begin
Append_Attribute (Value);
end Append;
-- ------------------------------
-- Get the cursor to get access to the first attribute.
-- ------------------------------
function First (List : in Attribute_List) return Cursor is
begin
return Cursor '(Pos => List.List.First);
end First;
-- ------------------------------
-- Get the number of attributes in the list.
-- ------------------------------
function Length (List : in Attribute_List) return Natural is
begin
return Natural (List.List.Length);
end Length;
-- ------------------------------
-- Clear the list and remove all existing attributes.
-- ------------------------------
procedure Clear (List : in out Attribute_List) is
begin
List.List.Clear;
end Clear;
-- ------------------------------
-- Iterate over the list attributes and call the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterate (List : in Attribute_List;
Process : not null access procedure (Name : in String;
Value : in Wiki.Strings.WString)) is
Iter : Attribute_Vectors.Cursor := List.List.First;
Item : Attribute_Ref;
begin
while Attribute_Vectors.Has_Element (Iter) loop
Item := Attribute_Vectors.Element (Iter);
Process (Item.Value.Name, Item.Value.Value);
Attribute_Vectors.Next (Iter);
end loop;
end Iterate;
-- ------------------------------
-- Finalize the attribute list releasing any storage.
-- ------------------------------
overriding
procedure Finalize (List : in out Attribute_List) is
begin
List.Clear;
end Finalize;
end Wiki.Attributes;
|
Add the Append procedure with a Builder string (optimized to avoid string copies!)
|
Add the Append procedure with a Builder string (optimized to avoid string copies!)
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
9708bde22e784836d20312293db87dad84ce7ad2
|
awa/src/awa-events.ads
|
awa/src/awa-events.ads
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Objects.Maps;
with ADO;
with AWA.Index_Arrays;
-- == Introduction ==
-- The <b>AWA.Events</b> package defines an event framework for modules to post events
-- and have Ada bean methods be invoked when these events are dispatched. Subscription to
-- events is done through configuration files. This allows to configure the modules and
-- integrate them together easily at configuration time.
--
-- === Declaration ===
-- Modules define the events that they can generate by instantiating the <b>Definition</b>
-- package. This is a static definition of the event. Each event is given a unique name.
--
-- with AWA.Events.Definition;
-- ...
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- === Posting an event ===
-- The module can post an event to inform other modules or the system that a particular
-- action occurred. The module creates the event instance of type <b>Module_Event</b> and
-- populates that event with useful properties for event receivers.
--
-- with AWA.Events;
-- ...
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- === Receiving an event ===
-- Modules or applications interested by a particular event will configure the event manager
-- to dispatch the event to an Ada bean event action. The Ada bean is an object that must
-- implement a procedure that matches the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- The configuration file indicates how to bind the Ada bean action and the event together.
-- The action is specified using an EL Method Expression (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
-- === Event queues and dispatchers ===
-- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them.
-- There are two kinds of dispatchers:
--
-- * Synchronous dispatcher process the event when it is posted. The task which posts
-- the event invokes the Ada bean action. In this dispatching mode, there is no event queue.
-- If the action method raises an exception, it will however be blocked.
--
-- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event
-- queue. A dispatcher task processes the event and invokes the action method at a later
-- time.
--
-- When the event is queued, there are two types of event queues:
--
-- * A Fifo memory queue manages the event and dispatches them in FIFO order.
-- If the application is stopped, the events present in the Fifo queue are lost.
--
-- * A persistent event queue manages the event in a similar way as the FIFO queue but
-- saves them in the database. If the application is stopped, events that have not yet
-- been processed will be dispatched when the application is started again.
--
-- == Data Model ==
-- [images/awa_events_model.png]
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
package Event_Arrays is new AWA.Index_Arrays (Event_Index, String);
use type Event_Arrays.Element_Type_Access;
subtype Name_Access is Event_Arrays.Element_Type_Access;
generic
package Definition renames Event_Arrays.Definition;
-- Exception raised if an event name is not found.
Not_Found : exception renames Event_Arrays.Not_Found;
-- Identifies an invalid event.
-- Invalid_Event : constant Event_Index := 0;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String) return Event_Index renames Event_Arrays.Find;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
-- Get the entity identifier associated with the event.
function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier;
-- Set the entity identifier associated with the event.
procedure Set_Entity_Identifier (Event : in out Module_Event;
Id : in ADO.Identifier);
-- Copy the event properties to the map passed in <tt>Into</tt>.
procedure Copy (Event : in Module_Event;
Into : in out Util.Beans.Objects.Maps.Map);
private
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Event_Arrays.Invalid_Index;
Props : Util.Beans.Objects.Maps.Map;
Entity : ADO.Identifier := ADO.NO_IDENTIFIER;
Entity_Type : ADO.Entity_Type := ADO.NO_ENTITY_TYPE;
end record;
-- The index of the last event definition.
-- Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Name_Access
renames Event_Arrays.Get_Element;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Objects.Maps;
with ADO;
with AWA.Index_Arrays;
-- == Introduction ==
-- The <b>AWA.Events</b> package defines an event framework for modules to post events
-- and have Ada bean methods be invoked when these events are dispatched. Subscription to
-- events is done through configuration files. This allows to configure the modules and
-- integrate them together easily at configuration time.
--
-- === Declaration ===
-- Modules define the events that they can generate by instantiating the <b>Definition</b>
-- package. This is a static definition of the event. Each event is given a unique name.
--
-- with AWA.Events.Definition;
-- ...
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- === Posting an event ===
-- The module can post an event to inform other modules or the system that a particular
-- action occurred. The module creates the event instance of type <b>Module_Event</b> and
-- populates that event with useful properties for event receivers.
--
-- with AWA.Events;
-- ...
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- === Receiving an event ===
-- Modules or applications interested by a particular event will configure the event manager
-- to dispatch the event to an Ada bean event action. The Ada bean is an object that must
-- implement a procedure that matches the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- The configuration file indicates how to bind the Ada bean action and the event together.
-- The action is specified using an EL Method Expression (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
-- === Event queues and dispatchers ===
-- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them.
-- There are two kinds of dispatchers:
--
-- * Synchronous dispatcher process the event when it is posted. The task which posts
-- the event invokes the Ada bean action. In this dispatching mode, there is no event queue.
-- If the action method raises an exception, it will however be blocked.
--
-- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event
-- queue. A dispatcher task processes the event and invokes the action method at a later
-- time.
--
-- When the event is queued, there are two types of event queues:
--
-- * A Fifo memory queue manages the event and dispatches them in FIFO order.
-- If the application is stopped, the events present in the Fifo queue are lost.
--
-- * A persistent event queue manages the event in a similar way as the FIFO queue but
-- saves them in the database. If the application is stopped, events that have not yet
-- been processed will be dispatched when the application is started again.
--
-- == Data Model ==
-- [images/awa_events_model.png]
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
package Event_Arrays is new AWA.Index_Arrays (Event_Index, String);
use type Event_Arrays.Element_Type_Access;
subtype Name_Access is Event_Arrays.Element_Type_Access;
generic
package Definition renames Event_Arrays.Definition;
-- Exception raised if an event name is not found.
Not_Found : exception renames Event_Arrays.Not_Found;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String) return Event_Index renames Event_Arrays.Find;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
-- Get the entity identifier associated with the event.
function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier;
-- Set the entity identifier associated with the event.
procedure Set_Entity_Identifier (Event : in out Module_Event;
Id : in ADO.Identifier);
-- Copy the event properties to the map passed in <tt>Into</tt>.
procedure Copy (Event : in Module_Event;
Into : in out Util.Beans.Objects.Maps.Map);
private
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Event_Arrays.Invalid_Index;
Props : Util.Beans.Objects.Maps.Map;
Entity : ADO.Identifier := ADO.NO_IDENTIFIER;
Entity_Type : ADO.Entity_Type := ADO.NO_ENTITY_TYPE;
end record;
-- The index of the last event definition.
-- Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Name_Access
renames Event_Arrays.Get_Element;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
c7dc9b0d4d1a3aec4d268c8ca2a324ef23e42f09
|
src/bbox-api.adb
|
src/bbox-api.adb
|
-----------------------------------------------------------------------
-- bbox -- Bbox API
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties.JSON;
with Util.Log.Loggers;
with Util.Strings;
package body Bbox.API is
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API");
function Strip_Unecessary_Array (Content : in String) return String;
-- ------------------------------
-- Set the server IP address.
-- ------------------------------
procedure Set_Server (Client : in out Client_Type;
Server : in String) is
begin
Log.Debug ("Using bbox server {0}", Server);
Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server);
end Set_Server;
-- ------------------------------
-- Internal operation to get the URI based on the operation being called.
-- ------------------------------
function Get_URI (Client : in Client_Type;
Operation : in String) return String is
begin
return "http://" & To_String (Client.Server) & "/api/v1/" & Operation;
end Get_URI;
-- ------------------------------
-- Login to the server Bbox API with the password.
-- ------------------------------
procedure Login (Client : in out Client_Type;
Password : in String) is
procedure Process (Name, Value : in String);
URI : constant String := Client.Get_URI ("login");
Response : Util.Http.Clients.Response;
procedure Process (Name, Value : in String) is
Pos, Last : Natural;
begin
if Name = "Set-Cookie" then
Pos := Util.Strings.Index (Value, '=');
if Pos = 0 then
return;
end if;
Last := Util.Strings.Index (Value, ';');
if Last = 0 or else Last < Pos then
return;
end if;
Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1));
end if;
end Process;
begin
Log.Debug ("Login to {0}", URI);
Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api");
Client.Http.Post (URI, "password=" & Password, Response);
if Response.Get_Status = Util.Http.SC_OK then
Response.Iterate_Headers (Process'Access);
else
Log.Error ("Connection and login to {0} failed", URI);
end if;
end Login;
-- ------------------------------
-- Strip [] for some Json content.
-- We did a mistake when we designed the Bbox API and used '[' ... ']' arrays
-- for most of the JSON result. Strip that unecessary array.
-- ------------------------------
function Strip_Unecessary_Array (Content : in String) return String is
Last : Natural := Content'Last;
begin
while Last > Content'First and Content (Last) = ASCII.LF loop
Last := Last - 1;
end loop;
if Content (Content'First) = '[' and Content (Last) = ']' then
return Content (Content'First + 1 .. Last - 1);
else
return Content;
end if;
end Strip_Unecessary_Array;
-- ------------------------------
-- Execute a GET operation on the Bbox API to retrieve the result into the property list.
-- ------------------------------
procedure Get (Client : in out Client_Type;
Operation : in String;
Result : in out Util.Properties.Manager) is
URI : constant String := Client.Get_URI (Operation);
Response : Util.Http.Clients.Response;
begin
Log.Debug ("Get {0}", URI);
Client.Http.Get (URI, Response);
Util.Properties.JSON.Parse_JSON (Result, Strip_Unecessary_Array (Response.Get_Body));
end Get;
-- ------------------------------
-- Execute a GET operation on the Bbox API to retrieve the JSON result and return it.
-- ------------------------------
function Get (Client : in out Client_Type;
Operation : in String) return String is
URI : constant String := Client.Get_URI (Operation);
Response : Util.Http.Clients.Response;
begin
Log.Debug ("Get {0}", URI);
Client.Http.Get (URI, Response);
return Response.Get_Body;
end Get;
-- ------------------------------
-- Execute a PUT operation on the Bbox API to change some parameter.
-- ------------------------------
procedure Put (Client : in out Client_Type;
Operation : in String;
Params : in String) is
URI : constant String := Client.Get_URI (Operation);
Response : Util.Http.Clients.Response;
begin
Log.Debug ("Put {0}", URI);
Client.Http.Put (URI, Params, Response);
end Put;
end Bbox.API;
|
-----------------------------------------------------------------------
-- bbox -- Bbox API
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties.JSON;
with Util.Log.Loggers;
with Util.Strings;
with Util.Properties.Basic;
package body Bbox.API is
use Ada.Strings.Unbounded;
package Int_Property renames Util.Properties.Basic.Integer_Property;
package Bool_Property renames Util.Properties.Basic.Boolean_Property;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API");
function Strip_Unecessary_Array (Content : in String) return String;
-- ------------------------------
-- Set the server IP address.
-- ------------------------------
procedure Set_Server (Client : in out Client_Type;
Server : in String) is
begin
Log.Debug ("Using bbox server {0}", Server);
Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server);
end Set_Server;
-- ------------------------------
-- Internal operation to get the URI based on the operation being called.
-- ------------------------------
function Get_URI (Client : in Client_Type;
Operation : in String) return String is
begin
return "http://" & To_String (Client.Server) & "/api/v1/" & Operation;
end Get_URI;
-- ------------------------------
-- Login to the server Bbox API with the password.
-- ------------------------------
procedure Login (Client : in out Client_Type;
Password : in String) is
procedure Process (Name, Value : in String);
URI : constant String := Client.Get_URI ("login");
Response : Util.Http.Clients.Response;
procedure Process (Name, Value : in String) is
Pos, Last : Natural;
begin
if Name = "Set-Cookie" then
Pos := Util.Strings.Index (Value, '=');
if Pos = 0 then
return;
end if;
Last := Util.Strings.Index (Value, ';');
if Last = 0 or else Last < Pos then
return;
end if;
Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1));
Client.Is_Logged := True;
end if;
end Process;
begin
Log.Debug ("Login to {0}", URI);
Client.Is_Logged := False;
Client.Http.Set_Header ("Cookie", "");
Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api");
Client.Http.Set_Timeout (10.0);
Client.Http.Post (URI, "password=" & Password, Response);
if Response.Get_Status = Util.Http.SC_OK then
Response.Iterate_Headers (Process'Access);
else
Log.Error ("Connection and login to {0} failed", URI);
end if;
end Login;
-- ------------------------------
-- Strip [] for some Json content.
-- We did a mistake when we designed the Bbox API and used '[' ... ']' arrays
-- for most of the JSON result. Strip that unecessary array.
-- ------------------------------
function Strip_Unecessary_Array (Content : in String) return String is
Last : Natural := Content'Last;
begin
while Last > Content'First and Content (Last) = ASCII.LF loop
Last := Last - 1;
end loop;
if Content (Content'First) = '[' and Content (Last) = ']' then
return Content (Content'First + 1 .. Last - 1);
else
return Content;
end if;
end Strip_Unecessary_Array;
-- ------------------------------
-- Execute a GET operation on the Bbox API to retrieve the result into the property list.
-- ------------------------------
procedure Get (Client : in out Client_Type;
Operation : in String;
Result : in out Util.Properties.Manager) is
URI : constant String := Client.Get_URI (Operation);
Response : Util.Http.Clients.Response;
begin
Log.Debug ("Get {0}", URI);
Client.Http.Set_Timeout (10.0);
Client.Http.Get (URI, Response);
Util.Properties.JSON.Parse_JSON (Result, Strip_Unecessary_Array (Response.Get_Body));
end Get;
-- ------------------------------
-- Execute a GET operation on the Bbox API to retrieve the JSON result and return it.
-- ------------------------------
function Get (Client : in out Client_Type;
Operation : in String) return String is
URI : constant String := Client.Get_URI (Operation);
Response : Util.Http.Clients.Response;
begin
Log.Debug ("Get {0}", URI);
Client.Http.Set_Timeout (10.0);
Client.Http.Get (URI, Response);
return Response.Get_Body;
end Get;
-- ------------------------------
-- Execute a PUT operation on the Bbox API to change some parameter.
-- ------------------------------
procedure Put (Client : in out Client_Type;
Operation : in String;
Params : in String) is
URI : constant String := Client.Get_URI (Operation);
Response : Util.Http.Clients.Response;
begin
Log.Debug ("Put {0}", URI);
Client.Http.Set_Timeout (10.0);
Client.Http.Put (URI, Params, Response);
end Put;
procedure Refresh_Token (Client : in out Client_Type) is
use type Ada.Calendar.Time;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Response : Util.Http.Clients.Response;
Tokens : Util.Properties.Manager;
begin
if Length (Client.Token) /= 0 and then Client.Expires > Now then
return;
end if;
Log.Debug ("Get bbox token");
Client.Http.Set_Timeout (10.0);
Client.Http.Get (Client.Get_URI ("device/token"), Response);
Util.Properties.JSON.Parse_JSON (Tokens, Strip_Unecessary_Array (Response.Get_Body));
Client.Token := To_Unbounded_String (Tokens.Get ("device.token", ""));
Client.Expires := Ada.Calendar.Clock + 60.0;
end Refresh_Token;
-- Execute a POST operation on the Bbox API to change some parameter.
procedure Post (Client : in out Client_Type;
Operation : in String;
Params : in String) is
URI : constant String := Client.Get_URI (Operation);
Response : Util.Http.Clients.Response;
begin
Log.Debug ("Post {0}", URI);
Client.Refresh_Token;
Client.Http.Set_Timeout (10.0);
Client.Http.Post (URI & "?btoken=" & To_String (Client.Token), Params, Response);
end Post;
-- Iterate over a JSON array flattened in the properties.
procedure Iterate (Props : in Util.Properties.Manager;
Name : in String;
Process : access procedure (P : in Util.Properties.Manager;
Base : in String)) is
Count : constant Integer := Int_Property.Get (Props, Name & ".length", 0);
begin
for I in 0 .. Count loop
declare
Base : constant String := Name & "." & Util.Strings.Image (I);
begin
Process (Props, Base);
end;
end loop;
end Iterate;
end Bbox.API;
|
Implement the Iterate, Refresh_Token, Iterate operations
|
Implement the Iterate, Refresh_Token, Iterate operations
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
d80aa795509c6d5fb422e5920cc4a22970a112cb
|
src/display.adb
|
src/display.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with HelperText;
package body Display is
package HT renames HelperText;
--------------------------------------------------------------------------------------------
-- insert_history
--------------------------------------------------------------------------------------------
procedure insert_history (HR : history_rec) is
begin
if history_arrow = cyclic_range'Last then
history_arrow := cyclic_range'First;
else
history_arrow := history_arrow + 1;
end if;
history (history_arrow) := HR;
end insert_history;
------------------------------------------------------------------------
-- fmtpc
------------------------------------------------------------------------
function fmtpc (f : Float; percent : Boolean) return fivelong
is
type loadtype is delta 0.01 digits 4;
result : fivelong := (others => ' ');
raw1 : constant loadtype := loadtype (f);
raw2 : constant String := raw1'Img;
raw3 : constant String := raw2 (2 .. raw2'Last);
rlen : constant Natural := raw3'Length;
start : constant Natural := 6 - rlen;
begin
result (start .. 5) := raw3;
if percent then
result (5) := '%';
end if;
return result;
end fmtpc;
------------------------------------------------------------------------
-- fmtload
------------------------------------------------------------------------
function fmtload (f : Float) return fivelong
is
type loadtype is delta 0.01 digits 4;
result : fivelong := (others => ' ');
begin
if f < 100.0 then
return fmtpc (f, False);
elsif f < 1000.0 then
declare
type loadtype is delta 0.1 digits 4;
raw1 : constant loadtype := loadtype (f);
begin
return HT.trim (raw1'Img);
end;
elsif f < 10000.0 then
declare
raw1 : constant Integer := Integer (f);
begin
-- preceded by space, 1000.0 .. 9999.99, should be 5 chars
return raw1'Image;
end;
elsif f < 100000.0 then
declare
raw1 : constant Integer := Integer (f);
begin
-- 100000.0 .. 99999.9
return HT.trim (raw1'Img);
end;
else
return "100k+";
end if;
exception
when others =>
return "ERROR";
end fmtload;
end Display;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with HelperText;
package body Display is
package HT renames HelperText;
--------------------------------------------------------------------------------------------
-- insert_history
--------------------------------------------------------------------------------------------
procedure insert_history (HR : history_rec) is
begin
if history_arrow = cyclic_range'Last then
history_arrow := cyclic_range'First;
else
history_arrow := history_arrow + 1;
end if;
history (history_arrow) := HR;
end insert_history;
------------------------------------------------------------------------
-- fmtpc
------------------------------------------------------------------------
function fmtpc (f : Float; percent : Boolean) return fivelong
is
type loadtype is delta 0.01 digits 4;
result : fivelong := (others => ' ');
raw1 : constant loadtype := loadtype (f);
raw2 : constant String := raw1'Img;
raw3 : constant String := raw2 (2 .. raw2'Last);
rlen : constant Natural := raw3'Length;
start : constant Natural := 6 - rlen;
begin
result (start .. 5) := raw3;
if percent then
result (5) := '%';
end if;
return result;
end fmtpc;
------------------------------------------------------------------------
-- fmtload
------------------------------------------------------------------------
function fmtload (f : Float) return fivelong
is
type loadtype is delta 0.01 digits 4;
result : fivelong := (others => ' ');
begin
if f < 100.0 then
return fmtpc (f, False);
elsif f < 1000.0 then
declare
type loadtype is delta 0.1 digits 4;
raw1 : constant loadtype := loadtype (f);
begin
return HT.trim (raw1'Img);
end;
elsif f < 10000.0 then
declare
raw1 : constant Integer := Integer (f);
begin
-- preceded by space, 1000.0 .. 9999.99, should be 5 chars
return raw1'Img;
end;
elsif f < 100000.0 then
declare
raw1 : constant Integer := Integer (f);
begin
-- 100000.0 .. 99999.9
return HT.trim (raw1'Img);
end;
else
return "100k+";
end if;
exception
when others =>
return "ERROR";
end fmtload;
end Display;
|
Fix typo (caught by gcc6!)
|
Fix typo (caught by gcc6!)
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
b0ba5f57325042af1675f21432a8f8bbad685255
|
src/wiki-render-html.adb
|
src/wiki-render-html.adb
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Util.Strings;
package body Wiki.Render.Html is
package ACC renames Ada.Characters.Conversions;
-- ------------------------------
-- Set the output stream.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the link renderer.
-- ------------------------------
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Link_Renderer_Access) is
begin
Engine.Links := Links;
end Set_Link_Renderer;
-- ------------------------------
-- Render the node instance from the document.
-- ------------------------------
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Render_Header (Header => Node.Header,
Level => Node.Level);
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Output.Start_Element ("br");
Engine.Output.End_Element ("br");
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
Engine.Output.Start_Element ("hr");
Engine.Output.End_Element ("hr");
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
when Wiki.Nodes.N_PREFORMAT =>
Engine.Render_Preformatted (Node.Preformatted, "");
when Wiki.Nodes.N_INDENT =>
-- Engine.Indent_Level := Node.Level;
null;
when Wiki.Nodes.N_LIST =>
Engine.Render_List_Item (Node.Level, False);
when Wiki.Nodes.N_NUM_LIST =>
Engine.Render_List_Item (Node.Level, True);
when Wiki.Nodes.N_TEXT =>
Engine.Add_Text (Text => Node.Text,
Format => Node.Format);
when Wiki.Nodes.N_QUOTE =>
Engine.Render_Quote (Doc, Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_LINK =>
Engine.Render_Link (Doc, Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_IMAGE =>
Engine.Render_Image (Doc, Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_BLOCKQUOTE =>
Engine.Add_Blockquote (Node.Level);
when Wiki.Nodes.N_TAG_START =>
Engine.Render_Tag (Doc, Node);
end case;
end Render;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start);
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes);
begin
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := True;
Engine.Need_Paragraph := False;
end if;
Engine.Output.Start_Element (Name.all);
while Wiki.Attributes.Has_Element (Iter) loop
Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := False;
Engine.Need_Paragraph := True;
end if;
Engine.Output.End_Element (Name.all);
end Render_Tag;
-- ------------------------------
-- Render a section header in the document.
-- ------------------------------
procedure Render_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
case Level is
when 1 =>
Engine.Output.Write_Wide_Element ("h1", Header);
when 2 =>
Engine.Output.Write_Wide_Element ("h2", Header);
when 3 =>
Engine.Output.Write_Wide_Element ("h3", Header);
when 4 =>
Engine.Output.Write_Wide_Element ("h4", Header);
when 5 =>
Engine.Output.Write_Wide_Element ("h5", Header);
when 6 =>
Engine.Output.Write_Wide_Element ("h6", Header);
when others =>
Engine.Output.Write_Wide_Element ("h3", Header);
end case;
end Render_Header;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural) is
begin
if Engine.Quote_Level /= Level then
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
end if;
while Engine.Quote_Level < Level loop
Engine.Output.Start_Element ("blockquote");
Engine.Quote_Level := Engine.Quote_Level + 1;
end loop;
while Engine.Quote_Level > Level loop
Engine.Output.End_Element ("blockquote");
Engine.Quote_Level := Engine.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Engine.Has_Paragraph then
Engine.Output.End_Element ("p");
Engine.Has_Paragraph := False;
end if;
if Engine.Has_Item then
Engine.Output.End_Element ("li");
Engine.Has_Item := False;
end if;
Engine.Need_Paragraph := False;
Engine.Open_Paragraph;
while Engine.Current_Level < Level loop
if Ordered then
Engine.Output.Start_Element ("ol");
else
Engine.Output.Start_Element ("ul");
end if;
Engine.Current_Level := Engine.Current_Level + 1;
Engine.List_Styles (Engine.Current_Level) := Ordered;
end loop;
end Render_List_Item;
procedure Close_Paragraph (Engine : in out Html_Renderer) is
begin
if Engine.Html_Level > 0 then
return;
end if;
if Engine.Has_Paragraph then
Engine.Output.End_Element ("p");
end if;
if Engine.Has_Item then
Engine.Output.End_Element ("li");
end if;
while Engine.Current_Level > 0 loop
if Engine.List_Styles (Engine.Current_Level) then
Engine.Output.End_Element ("ol");
else
Engine.Output.End_Element ("ul");
end if;
Engine.Current_Level := Engine.Current_Level - 1;
end loop;
Engine.Has_Paragraph := False;
Engine.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Engine : in out Html_Renderer) is
begin
if Engine.Html_Level > 0 then
return;
end if;
if Engine.Need_Paragraph then
Engine.Output.Start_Element ("p");
Engine.Has_Paragraph := True;
Engine.Need_Paragraph := False;
end if;
if Engine.Current_Level > 0 and not Engine.Has_Item then
Engine.Output.Start_Element ("li");
Engine.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Render a link.
-- ------------------------------
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type) is
procedure Render_Attribute (Name : in String;
Value : in Wide_Wide_String) is
begin
if Name = "href" then
declare
URI : Unbounded_Wide_Wide_String;
Exists : Boolean;
begin
Engine.Links.Make_Page_Link (Value, URI, Exists);
Engine.Output.Write_Wide_Attribute ("href", URI);
end;
elsif Value'Length = 0 then
return;
elsif Name = "lang" or Name = "title" or Name = "rel" or Name = "target"
or Name = "style" or Name = "class" then
Engine.Output.Write_Wide_Attribute (Name, Value);
end if;
end Render_Attribute;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("a");
Wiki.Attributes.Iterate (Attr, Render_Attribute'Access);
Engine.Output.Write_Wide_Text (Title);
Engine.Output.End_Element ("a");
end Render_Link;
-- ------------------------------
-- Render an image.
-- ------------------------------
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type) is
procedure Render_Attribute (Name : in String;
Value : in Wide_Wide_String) is
begin
if Name = "src" then
declare
URI : Unbounded_Wide_Wide_String;
Width : Natural;
Height : Natural;
begin
Engine.Links.Make_Image_Link (Value, URI, Width, Height);
Engine.Output.Write_Wide_Attribute ("src", URI);
if Width > 0 then
Engine.Output.Write_Attribute ("width", Natural'Image (Width));
end if;
if Height > 0 then
Engine.Output.Write_Attribute ("height", Natural'Image (Height));
end if;
end;
elsif Value'Length = 0 then
return;
elsif Name = "alt" or Name = "longdesc"
or Name = "style" or Name = "class" then
Engine.Output.Write_Wide_Attribute (Name, Value);
end if;
end Render_Attribute;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("img");
Engine.Output.Write_Wide_Attribute ("alt", Title);
Wiki.Attributes.Iterate (Attr, Render_Attribute'Access);
Engine.Output.End_Element ("img");
end Render_Image;
-- ------------------------------
-- Render a quote.
-- ------------------------------
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type) is
procedure Render_Attribute (Name : in String;
Value : in Wide_Wide_String) is
begin
if Value'Length = 0 then
return;
elsif Name = "cite" or Name = "title" or Name = "lang" or Name = "style" or Name = "class" then
Engine.Output.Write_Wide_Attribute (Name, Value);
end if;
end Render_Attribute;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("q");
Wiki.Attributes.Iterate (Attr, Render_Attribute'Access);
Engine.Output.Write_Wide_Text (Title);
Engine.Output.End_Element ("q");
end Render_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(BOLD => HTML_BOLD'Access,
ITALIC => HTML_ITALIC'Access,
CODE => HTML_CODE'Access,
SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
SUBSCRIPT => HTML_SUBSCRIPT'Access,
STRIKEOUT => HTML_STRIKEOUT'Access,
PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
Engine.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Engine.Output.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Engine.Output.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Engine.Output.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Render a text block that is pre-formatted.
-- ------------------------------
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Engine.Close_Paragraph;
if Format = "html" then
Engine.Output.Write (Text);
else
Engine.Output.Start_Element ("pre");
Engine.Output.Write_Wide_Text (Text);
Engine.Output.End_Element ("pre");
end if;
end Render_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Engine : in out Html_Renderer) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
end Finish;
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Util.Strings;
package body Wiki.Render.Html is
package ACC renames Ada.Characters.Conversions;
-- ------------------------------
-- Set the output stream.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the link renderer.
-- ------------------------------
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Link_Renderer_Access) is
begin
Engine.Links := Links;
end Set_Link_Renderer;
-- ------------------------------
-- Render the node instance from the document.
-- ------------------------------
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Render_Header (Header => Node.Header,
Level => Node.Level);
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Output.Start_Element ("br");
Engine.Output.End_Element ("br");
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
Engine.Output.Start_Element ("hr");
Engine.Output.End_Element ("hr");
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
when Wiki.Nodes.N_PREFORMAT =>
Engine.Render_Preformatted (Node.Preformatted, "");
when Wiki.Nodes.N_INDENT =>
-- Engine.Indent_Level := Node.Level;
null;
when Wiki.Nodes.N_LIST =>
Engine.Render_List_Item (Node.Level, False);
when Wiki.Nodes.N_NUM_LIST =>
Engine.Render_List_Item (Node.Level, True);
when Wiki.Nodes.N_TEXT =>
Engine.Add_Text (Text => Node.Text,
Format => Node.Format);
when Wiki.Nodes.N_QUOTE =>
Engine.Render_Quote (Doc, Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_LINK =>
Engine.Render_Link (Doc, Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_IMAGE =>
Engine.Render_Image (Doc, Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_BLOCKQUOTE =>
Engine.Add_Blockquote (Node.Level);
when Wiki.Nodes.N_TAG_START =>
Engine.Render_Tag (Doc, Node);
end case;
end Render;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start);
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes);
begin
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := True;
Engine.Need_Paragraph := False;
elsif Node.Tag_Start = Wiki.Nodes.UL_TAG
or Node.Tag_Start = Wiki.Nodes.OL_TAG
or Node.Tag_Start = Wiki.Nodes.DL_Tag
or Node.Tag_Start = Wiki.Nodes.DT_TAG
or Node.Tag_Start = Wiki.Nodes.DD_TAG
or Node.Tag_Start = Wiki.Nodes.LI_TAG
or Node.Tag_Start = Wiki.Nodes.TABLE_TAG then
Engine.Close_Paragraph;
Engine.Need_Paragraph := False;
end if;
Engine.Output.Start_Element (Name.all);
while Wiki.Attributes.Has_Element (Iter) loop
Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := False;
Engine.Need_Paragraph := True;
end if;
Engine.Output.End_Element (Name.all);
end Render_Tag;
-- ------------------------------
-- Render a section header in the document.
-- ------------------------------
procedure Render_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
case Level is
when 1 =>
Engine.Output.Write_Wide_Element ("h1", Header);
when 2 =>
Engine.Output.Write_Wide_Element ("h2", Header);
when 3 =>
Engine.Output.Write_Wide_Element ("h3", Header);
when 4 =>
Engine.Output.Write_Wide_Element ("h4", Header);
when 5 =>
Engine.Output.Write_Wide_Element ("h5", Header);
when 6 =>
Engine.Output.Write_Wide_Element ("h6", Header);
when others =>
Engine.Output.Write_Wide_Element ("h3", Header);
end case;
end Render_Header;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural) is
begin
if Engine.Quote_Level /= Level then
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
end if;
while Engine.Quote_Level < Level loop
Engine.Output.Start_Element ("blockquote");
Engine.Quote_Level := Engine.Quote_Level + 1;
end loop;
while Engine.Quote_Level > Level loop
Engine.Output.End_Element ("blockquote");
Engine.Quote_Level := Engine.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Engine.Has_Paragraph then
Engine.Output.End_Element ("p");
Engine.Has_Paragraph := False;
end if;
if Engine.Has_Item then
Engine.Output.End_Element ("li");
Engine.Has_Item := False;
end if;
Engine.Need_Paragraph := False;
Engine.Open_Paragraph;
while Engine.Current_Level < Level loop
if Ordered then
Engine.Output.Start_Element ("ol");
else
Engine.Output.Start_Element ("ul");
end if;
Engine.Current_Level := Engine.Current_Level + 1;
Engine.List_Styles (Engine.Current_Level) := Ordered;
end loop;
end Render_List_Item;
procedure Close_Paragraph (Engine : in out Html_Renderer) is
begin
if Engine.Html_Level > 0 then
return;
end if;
if Engine.Has_Paragraph then
Engine.Output.End_Element ("p");
end if;
if Engine.Has_Item then
Engine.Output.End_Element ("li");
end if;
while Engine.Current_Level > 0 loop
if Engine.List_Styles (Engine.Current_Level) then
Engine.Output.End_Element ("ol");
else
Engine.Output.End_Element ("ul");
end if;
Engine.Current_Level := Engine.Current_Level - 1;
end loop;
Engine.Has_Paragraph := False;
Engine.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Engine : in out Html_Renderer) is
begin
if Engine.Html_Level > 0 then
return;
end if;
if Engine.Need_Paragraph then
Engine.Output.Start_Element ("p");
Engine.Has_Paragraph := True;
Engine.Need_Paragraph := False;
end if;
if Engine.Current_Level > 0 and not Engine.Has_Item then
Engine.Output.Start_Element ("li");
Engine.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Render a link.
-- ------------------------------
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type) is
procedure Render_Attribute (Name : in String;
Value : in Wide_Wide_String) is
begin
if Name = "href" then
declare
URI : Unbounded_Wide_Wide_String;
Exists : Boolean;
begin
Engine.Links.Make_Page_Link (Value, URI, Exists);
Engine.Output.Write_Wide_Attribute ("href", URI);
end;
elsif Value'Length = 0 then
return;
elsif Name = "lang" or Name = "title" or Name = "rel" or Name = "target"
or Name = "style" or Name = "class" then
Engine.Output.Write_Wide_Attribute (Name, Value);
end if;
end Render_Attribute;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("a");
Wiki.Attributes.Iterate (Attr, Render_Attribute'Access);
Engine.Output.Write_Wide_Text (Title);
Engine.Output.End_Element ("a");
end Render_Link;
-- ------------------------------
-- Render an image.
-- ------------------------------
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type) is
procedure Render_Attribute (Name : in String;
Value : in Wide_Wide_String) is
begin
if Name = "src" then
declare
URI : Unbounded_Wide_Wide_String;
Width : Natural;
Height : Natural;
begin
Engine.Links.Make_Image_Link (Value, URI, Width, Height);
Engine.Output.Write_Wide_Attribute ("src", URI);
if Width > 0 then
Engine.Output.Write_Attribute ("width", Natural'Image (Width));
end if;
if Height > 0 then
Engine.Output.Write_Attribute ("height", Natural'Image (Height));
end if;
end;
elsif Value'Length = 0 then
return;
elsif Name = "alt" or Name = "longdesc"
or Name = "style" or Name = "class" then
Engine.Output.Write_Wide_Attribute (Name, Value);
end if;
end Render_Attribute;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("img");
if Title'Length > 0 then
Engine.Output.Write_Wide_Attribute ("alt", Title);
end if;
Wiki.Attributes.Iterate (Attr, Render_Attribute'Access);
Engine.Output.End_Element ("img");
end Render_Image;
-- ------------------------------
-- Render a quote.
-- ------------------------------
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type) is
procedure Render_Attribute (Name : in String;
Value : in Wide_Wide_String) is
begin
if Value'Length = 0 then
return;
elsif Name = "cite" or Name = "title" or Name = "lang" or Name = "style" or Name = "class" then
Engine.Output.Write_Wide_Attribute (Name, Value);
end if;
end Render_Attribute;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("q");
Wiki.Attributes.Iterate (Attr, Render_Attribute'Access);
Engine.Output.Write_Wide_Text (Title);
Engine.Output.End_Element ("q");
end Render_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(BOLD => HTML_BOLD'Access,
ITALIC => HTML_ITALIC'Access,
CODE => HTML_CODE'Access,
SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
SUBSCRIPT => HTML_SUBSCRIPT'Access,
STRIKEOUT => HTML_STRIKEOUT'Access,
PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
Engine.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Engine.Output.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Engine.Output.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Engine.Output.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Render a text block that is pre-formatted.
-- ------------------------------
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Engine.Close_Paragraph;
if Format = "html" then
Engine.Output.Write (Text);
else
Engine.Output.Start_Element ("pre");
Engine.Output.Write_Wide_Text (Text);
Engine.Output.End_Element ("pre");
end if;
end Render_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Engine : in out Html_Renderer) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
end Finish;
end Wiki.Render.Html;
|
Fix HTML generation with ul/dl/ol lists
|
Fix HTML generation with ul/dl/ol lists
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
e968b4f3d27d68c9fa7bd1a9e916159088956c1b
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies. The framework defines a simple role based security policy and an URL security
-- policy intended to provide security in web applications. The security policy manager reads
-- some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components (yellow) are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance. Additional security policy context can be added depending on
-- the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies. The framework defines a simple role based security policy and an URL security
-- policy intended to provide security in web applications. The security policy manager reads
-- some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components (yellow) are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance. Additional security policy context can be added depending on
-- the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
-- @include security-contexts.ads
--
-- [Security_Policies Security Policies]
--
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
Add some links in the documentation
|
Add some links in the documentation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
908c52a2168d2482cc8a6ca5ff0c9af27b71c856
|
regtests/security-policies-tests.adb
|
regtests/security-policies-tests.adb
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Returns true if the given permission is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Test_Principal;
Role : in Security.Policies.Roles.Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
Map : Role_Map;
begin
M.Create_Role (Name => "manager",
Role => Role);
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
M.Set_Roles ("admin", Map);
end Test_Set_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
M.Add_Policy (R.all'Access);
M.Read_Policy (Util.Files.Compose (Path, "empty.xml"));
R.Add_Role_Type (Name => "admin",
Result => Admin_Perm);
R.Add_Role_Type (Name => "manager",
Result => Manager_Perm);
M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml"));
User.Roles (Admin_Perm) := True;
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
-- end;
--
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/list.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
-- end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (1);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
begin
M.Read_Policy (Util.Files.Compose (Path, File));
--
-- Admin_Perm := M.Find_Role (Role);
--
-- Context.Set_Context (Manager => M'Unchecked_Access,
-- Principal => User'Unchecked_Access);
--
-- declare
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- -- A user without the role should not have the permission.
-- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was granted for user without role. URI=" & URI);
--
-- -- Set the role.
-- User.Roles (Admin_Perm) := True;
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was not granted for user with role. URI=" & URI);
-- end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Returns true if the given permission is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Test_Principal;
Role : in Security.Policies.Roles.Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Role);
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
T.Assert (not Map (Role), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Role), "The admin role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
M.Add_Policy (R.all'Access);
M.Read_Policy (Util.Files.Compose (Path, "empty.xml"));
R.Add_Role_Type (Name => "admin",
Result => Admin_Perm);
R.Add_Role_Type (Name => "manager",
Result => Manager_Perm);
M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml"));
User.Roles (Admin_Perm) := True;
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
-- end;
--
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/list.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
-- end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (1);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
begin
M.Read_Policy (Util.Files.Compose (Path, File));
--
-- Admin_Perm := M.Find_Role (Role);
--
-- Context.Set_Context (Manager => M'Unchecked_Access,
-- Principal => User'Unchecked_Access);
--
-- declare
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- -- A user without the role should not have the permission.
-- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was granted for user without role. URI=" & URI);
--
-- -- Set the role.
-- User.Roles (Admin_Perm) := True;
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was not granted for user with role. URI=" & URI);
-- end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
Check that the given role is set after Set_Roles
|
Check that the given role is set after Set_Roles
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
68276ee85c70543290243cb723899dce891468cb
|
src/asf-components-core.adb
|
src/asf-components-core.adb
|
-----------------------------------------------------------------------
-- components-core -- ASF Core Components
-- 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.Unchecked_Deallocation;
package body ASF.Components.Core is
use ASF;
use EL.Objects;
-- ------------------------------
-- Return a client-side identifier for this component, generating
-- one if necessary.
-- ------------------------------
function Get_Client_Id (UI : UIComponentBase) return Unbounded_String is
Id : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("id");
begin
if Id /= null then
return To_Unbounded_String (Views.Nodes.Get_Value (Id.all, UI.Get_Context.all));
end if;
-- return UI.Id;
return Base.UIComponent (UI).Get_Client_Id;
end Get_Client_Id;
-- ------------------------------
-- Renders the UIText evaluating the EL expressions it may contain.
-- ------------------------------
procedure Encode_Begin (UI : in UIText;
Context : in out Faces_Context'Class) is
begin
UI.Text.Encode_All (UI.Expr_Table, Context);
end Encode_Begin;
-- ------------------------------
-- Set the expression array that contains reduced expressions.
-- ------------------------------
procedure Set_Expression_Table (UI : in out UIText;
Expr_Table : in Views.Nodes.Expression_Access_Array_Access) is
use type ASF.Views.Nodes.Expression_Access_Array_Access;
begin
if UI.Expr_Table /= null then
raise Program_Error with "Expression table already initialized";
end if;
UI.Expr_Table := Expr_Table;
end Set_Expression_Table;
-- ------------------------------
-- Finalize the object.
-- ------------------------------
overriding
procedure Finalize (UI : in out UIText) is
use type ASF.Views.Nodes.Expression_Access_Array_Access;
procedure Free is
new Ada.Unchecked_Deallocation (EL.Expressions.Expression'Class,
EL.Expressions.Expression_Access);
procedure Free is
new Ada.Unchecked_Deallocation (ASF.Views.Nodes.Expression_Access_Array,
ASF.Views.Nodes.Expression_Access_Array_Access);
begin
if UI.Expr_Table /= null then
for I in UI.Expr_Table'Range loop
Free (UI.Expr_Table (I));
end loop;
Free (UI.Expr_Table);
end if;
end Finalize;
function Create_UIText (Tag : ASF.Views.Nodes.Text_Tag_Node_Access)
return UIText_Access is
Result : constant UIText_Access := new UIText;
begin
Result.Text := Tag;
return Result;
end Create_UIText;
-- ------------------------------
-- Abstract Leaf component
-- ------------------------------
overriding
procedure Encode_Children (UI : in UILeaf;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_Children;
overriding
procedure Encode_Begin (UI : in UILeaf;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_Begin;
overriding
procedure Encode_End (UI : in UILeaf;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_End;
-- ------------------------------
-- Component Parameter
-- ------------------------------
-- ------------------------------
-- Get the parameter name
-- ------------------------------
function Get_Name (UI : UIParameter;
Context : Faces_Context'Class) return String is
Name : constant EL.Objects.Object := UI.Get_Attribute (Name => "name",
Context => Context);
begin
return EL.Objects.To_String (Name);
end Get_Name;
-- ------------------------------
-- Get the parameter value
-- ------------------------------
function Get_Value (UI : UIParameter;
Context : Faces_Context'Class) return EL.Objects.Object is
begin
return UI.Get_Attribute (Name => "value", Context => Context);
end Get_Value;
-- ------------------------------
-- Get the list of parameters associated with a component.
-- ------------------------------
function Get_Parameters (UI : Base.UIComponent'Class) return UIParameter_Access_Array is
Result : UIParameter_Access_Array (1 .. UI.Get_Children_Count);
Last : Natural := 0;
procedure Collect (Child : in Base.UIComponent_Access);
pragma Inline (Collect);
procedure Collect (Child : in Base.UIComponent_Access) is
begin
if Child.all in UIParameter'Class then
Last := Last + 1;
Result (Last) := UIParameter (Child.all)'Access;
end if;
end Collect;
procedure Iter is new ASF.Components.Base.Iterate (Process => Collect);
pragma Inline (Iter);
begin
Iter (UI);
return Result (1 .. Last);
end Get_Parameters;
end ASF.Components.Core;
|
-----------------------------------------------------------------------
-- components-core -- ASF Core Components
-- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body ASF.Components.Core is
use EL.Objects;
-- ------------------------------
-- Return a client-side identifier for this component, generating
-- one if necessary.
-- ------------------------------
function Get_Client_Id (UI : UIComponentBase) return Unbounded_String is
Id : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("id");
begin
if Id /= null then
return To_Unbounded_String (Views.Nodes.Get_Value (Id.all, UI.Get_Context.all));
end if;
-- return UI.Id;
return Base.UIComponent (UI).Get_Client_Id;
end Get_Client_Id;
-- ------------------------------
-- Renders the UIText evaluating the EL expressions it may contain.
-- ------------------------------
procedure Encode_Begin (UI : in UIText;
Context : in out Faces_Context'Class) is
begin
UI.Text.Encode_All (UI.Expr_Table, Context);
end Encode_Begin;
-- ------------------------------
-- Set the expression array that contains reduced expressions.
-- ------------------------------
procedure Set_Expression_Table (UI : in out UIText;
Expr_Table : in Views.Nodes.Expression_Access_Array_Access) is
use type ASF.Views.Nodes.Expression_Access_Array_Access;
begin
if UI.Expr_Table /= null then
UI.Log_Error ("Expression table already initialized");
raise Program_Error with "Expression table already initialized";
end if;
UI.Expr_Table := Expr_Table;
end Set_Expression_Table;
-- ------------------------------
-- Finalize the object.
-- ------------------------------
overriding
procedure Finalize (UI : in out UIText) is
use type ASF.Views.Nodes.Expression_Access_Array_Access;
procedure Free is
new Ada.Unchecked_Deallocation (EL.Expressions.Expression'Class,
EL.Expressions.Expression_Access);
procedure Free is
new Ada.Unchecked_Deallocation (ASF.Views.Nodes.Expression_Access_Array,
ASF.Views.Nodes.Expression_Access_Array_Access);
begin
if UI.Expr_Table /= null then
for I in UI.Expr_Table'Range loop
Free (UI.Expr_Table (I));
end loop;
Free (UI.Expr_Table);
end if;
Base.UIComponent (UI).Finalize;
end Finalize;
function Create_UIText (Tag : ASF.Views.Nodes.Text_Tag_Node_Access)
return UIText_Access is
Result : constant UIText_Access := new UIText;
begin
Result.Text := Tag;
return Result;
end Create_UIText;
-- ------------------------------
-- Get the parameter name
-- ------------------------------
function Get_Name (UI : UIParameter;
Context : Faces_Context'Class) return String is
Name : constant EL.Objects.Object := UI.Get_Attribute (Name => "name",
Context => Context);
begin
return EL.Objects.To_String (Name);
end Get_Name;
-- ------------------------------
-- Get the parameter value
-- ------------------------------
function Get_Value (UI : UIParameter;
Context : Faces_Context'Class) return EL.Objects.Object is
begin
return UI.Get_Attribute (Name => "value", Context => Context);
end Get_Value;
-- ------------------------------
-- Get the list of parameters associated with a component.
-- ------------------------------
function Get_Parameters (UI : Base.UIComponent'Class) return UIParameter_Access_Array is
Result : UIParameter_Access_Array (1 .. UI.Get_Children_Count);
Last : Natural := 0;
procedure Collect (Child : in Base.UIComponent_Access);
pragma Inline (Collect);
procedure Collect (Child : in Base.UIComponent_Access) is
begin
if Child.all in UIParameter'Class then
Last := Last + 1;
Result (Last) := UIParameter (Child.all)'Access;
end if;
end Collect;
procedure Iter is new ASF.Components.Base.Iterate (Process => Collect);
pragma Inline (Iter);
begin
Iter (UI);
return Result (1 .. Last);
end Get_Parameters;
end ASF.Components.Core;
|
Remove the body of UILeaf operations now that they are declared as 'is null' When finalizing the UIText, call the parent finalize operation so that we also release other nodes
|
Remove the body of UILeaf operations now that they are declared as 'is null'
When finalizing the UIText, call the parent finalize operation so that we also release other nodes
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
dc563d587b9ef34462ee2cd85486c3e9753427e2
|
src/sys/os-unix/util-processes-os.ads
|
src/sys/os-unix/util-processes-os.ads
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Raw;
with Util.Systems.Os;
with Interfaces.C;
with Interfaces.C.Strings;
private package Util.Processes.Os is
SHELL : constant String := "/bin/sh";
type System_Process is new Util.Processes.System_Process with record
Argv : Util.Systems.Os.Ptr_Ptr_Array := null;
Argc : Interfaces.C.size_t := 0;
In_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr;
Out_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr;
Err_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr;
Dir : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr;
To_Close : File_Type_Array_Access;
Out_Append : Boolean := False;
Err_Append : Boolean := False;
end record;
-- Wait for the process to exit.
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15);
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE);
-- Append the argument to the process argument list.
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String);
-- Set the process input, output and error streams to redirect and use specified files.
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access);
-- Deletes the storage held by the system process.
overriding
procedure Finalize (Sys : in out System_Process);
private
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
function Create_Stream (File : in Util.Systems.Os.File_Type)
return Util.Streams.Raw.Raw_Stream_Access;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class);
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2016, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Raw;
with Util.Systems.Os;
with Interfaces.C;
with Interfaces.C.Strings;
private package Util.Processes.Os is
SHELL : constant String := "/bin/sh";
type System_Process is new Util.Processes.System_Process with record
Argv : Util.Systems.Os.Ptr_Ptr_Array := null;
Envp : Util.Systems.Os.Ptr_Ptr_Array := null;
Argc : Interfaces.C.size_t := 0;
Envc : Interfaces.C.size_t := 0;
In_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr;
Out_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr;
Err_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr;
Dir : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr;
To_Close : File_Type_Array_Access;
Out_Append : Boolean := False;
Err_Append : Boolean := False;
end record;
-- Wait for the process to exit.
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15);
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE);
-- Append the argument to the process argument list.
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String);
-- Clear the program arguments.
overriding
procedure Clear_Arguments (Sys : in out System_Process);
-- Set the environment variable to be used by the process before its creation.
overriding
procedure Set_Environment (Sys : in out System_Process;
Name : in String;
Value : in String);
-- Set the process input, output and error streams to redirect and use specified files.
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access);
-- Deletes the storage held by the system process.
overriding
procedure Finalize (Sys : in out System_Process);
private
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
function Create_Stream (File : in Util.Systems.Os.File_Type)
return Util.Streams.Raw.Raw_Stream_Access;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class);
end Util.Processes.Os;
|
Add Set_Environment, Clear_Arguments procedures and add a Envp and Envc to the sys process record
|
Add Set_Environment, Clear_Arguments procedures and add a Envp and Envc to the sys process record
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1f4c5c9c455731f92973845ac8c9f1cf26bb1d58
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- 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.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Users.Modules;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Member_List_Bean",
Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Invitation_Bean",
Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager;
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- Create the member instance for this user.
Member.Set_Workspace (WS);
Member.Set_Member (User);
Member.Set_Role ("Owner");
Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => WS.Get_Create_Date));
Member.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS);
Workspace := WS;
end Get_Workspace;
-- ------------------------------
-- Load the invitation from the access key and verify that the key is still valid.
-- ------------------------------
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class;
Inviter : in out AWA.Users.Models.User_Ref) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
begin
Log.Debug ("Loading invitation from key {0}", Key);
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
Inviter := AWA.Users.Models.User_Ref (Invitation.Get_Inviter);
end Load_Invitation;
-- ------------------------------
-- Accept the invitation identified by the access key.
-- ------------------------------
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
Invitation : AWA.Workspaces.Models.Invitation_Ref;
begin
Log.Debug ("Accept invitation with key {0}", Key);
Ctx.Start;
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
DB_Key.Delete (DB);
Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Invitation.Save (DB);
Ctx.Commit;
end Accept_Invitation;
-- ------------------------------
-- Send the invitation to the user.
-- ------------------------------
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
Email : AWA.Users.Models.Email_Ref;
Invitee : AWA.Users.Models.User_Ref;
Invit : AWA.Workspaces.Models.Invitation_Ref;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Email_Address : constant String := Invitation.Get_Email;
begin
Log.Info ("Sending invitation to {0}", Email_Address);
Ctx.Start;
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (DB, Query, Found);
if not Found then
return;
end if;
Query.Clear;
Query.Set_Filter ("o.email = ?");
Query.Add_Param (Email_Address);
Email.Find (DB, Query, Found);
if not Found then
Email.Set_User_Id (0);
Email.Set_Email (Email_Address);
Email.Save (DB);
Invitee.Set_Email (Email);
Invitee.Set_Name (Email_Address);
Invitee.Save (DB);
Email.Set_User_Id (Invitee.Get_Id);
Email.Save (DB);
else
Invitee.Load (DB, Email.Get_User_Id);
end if;
-- Create the workspace member relation.
Query.Clear;
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (Invitee.Get_Id);
Query.Add_Param (WS.Get_Id);
Member.Find (DB, Query, Found);
if not Found then
Member.Set_Member (Invitee);
Member.Set_Workspace (WS);
Member.Set_Role ("Invited");
Member.Save (DB);
end if;
-- Check for a previous invitation for the user and delete it.
Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?");
Invit.Find (DB, Query, Found);
if Found then
Key := AWA.Users.Models.Access_Key_Ref (Invit.Get_Access_Key);
Key.Delete (DB);
if not Invitation.Is_Inserted or else Invit.Get_Id /= Invitation.Get_Id then
Invit.Delete (DB);
end if;
end if;
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB);
Key.Save (DB);
Invitation.Set_Access_Key (Key);
Invitation.Set_Inviter (User);
Invitation.Set_Invitee (Invitee);
Invitation.Set_Workspace (WS);
Invitation.Set_Create_Date (Ada.Calendar.Clock);
Invitation.Save (DB);
-- Send the email with the reset password key
declare
Event : AWA.Events.Module_Event;
begin
Event.Set_Parameter ("key", Key.Get_Access_Key);
Event.Set_Parameter ("email", Email_Address);
Event.Set_Parameter ("name", Invitee.Get_Name);
Event.Set_Parameter ("message", Invitation.Get_Message);
Event.Set_Parameter ("inviter", User.Get_Name);
Event.Set_Event_Kind (Invite_User_Event.Kind);
Module.Send_Event (Event);
end;
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- 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.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Users.Modules;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Member_List_Bean",
Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Invitation_Bean",
Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager;
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- Create the member instance for this user.
Member.Set_Workspace (WS);
Member.Set_Member (User);
Member.Set_Role ("Owner");
Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => WS.Get_Create_Date));
Member.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS);
Workspace := WS;
end Get_Workspace;
-- ------------------------------
-- Load the invitation from the access key and verify that the key is still valid.
-- ------------------------------
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class;
Inviter : in out AWA.Users.Models.User_Ref) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
begin
Log.Debug ("Loading invitation from key {0}", Key);
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
Inviter := AWA.Users.Models.User_Ref (Invitation.Get_Inviter);
end Load_Invitation;
-- ------------------------------
-- Accept the invitation identified by the access key.
-- ------------------------------
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String) is
use type Ada.Calendar.Time;
use type ADO.Identifier;
Ctx : constant ASC.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);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
Invitation : AWA.Workspaces.Models.Invitation_Ref;
Invitee_Id : ADO.Identifier;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Log.Debug ("Accept invitation with key {0}", Key);
Ctx.Start;
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Now then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Invitee_Id := DB_Key.Get_User.Get_Id;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", Invitee_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
-- Update the workspace member relation.
Query.Clear;
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (Invitee_Id);
Query.Add_Param (Invitation.Get_Workspace.Get_Id);
Member.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
-- The user who received the invitation is different from the user who is
-- logged and accepted the validation. Since the key is verified, this is
-- the same user but the user who accepted the invitation registered using
-- another email address.
if Invitee_Id /= User.Get_Id then
Invitation.Set_Invitee (User);
Member.Set_Member (User);
Log.Info ("Invitation accepted by user with another email address");
end if;
Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Now));
Member.Save (DB);
DB_Key.Delete (DB);
Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Now));
Invitation.Save (DB);
Ctx.Commit;
end Accept_Invitation;
-- ------------------------------
-- Send the invitation to the user.
-- ------------------------------
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
Email : AWA.Users.Models.Email_Ref;
Invitee : AWA.Users.Models.User_Ref;
Invit : AWA.Workspaces.Models.Invitation_Ref;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Email_Address : constant String := Invitation.Get_Email;
begin
Log.Info ("Sending invitation to {0}", Email_Address);
Ctx.Start;
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (DB, Query, Found);
if not Found then
return;
end if;
Query.Clear;
Query.Set_Filter ("o.email = ?");
Query.Add_Param (Email_Address);
Email.Find (DB, Query, Found);
if not Found then
Email.Set_User_Id (0);
Email.Set_Email (Email_Address);
Email.Save (DB);
Invitee.Set_Email (Email);
Invitee.Set_Name (Email_Address);
Invitee.Save (DB);
Email.Set_User_Id (Invitee.Get_Id);
Email.Save (DB);
else
Invitee.Load (DB, Email.Get_User_Id);
end if;
-- Create the workspace member relation.
Query.Clear;
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (Invitee.Get_Id);
Query.Add_Param (WS.Get_Id);
Member.Find (DB, Query, Found);
if not Found then
Member.Set_Member (Invitee);
Member.Set_Workspace (WS);
Member.Set_Role ("Invited");
Member.Save (DB);
end if;
-- Check for a previous invitation for the user and delete it.
Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?");
Invit.Find (DB, Query, Found);
if Found then
Key := AWA.Users.Models.Access_Key_Ref (Invit.Get_Access_Key);
Key.Delete (DB);
if not Invitation.Is_Inserted or else Invit.Get_Id /= Invitation.Get_Id then
Invit.Delete (DB);
end if;
end if;
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB);
Key.Save (DB);
Invitation.Set_Access_Key (Key);
Invitation.Set_Inviter (User);
Invitation.Set_Invitee (Invitee);
Invitation.Set_Workspace (WS);
Invitation.Set_Create_Date (Ada.Calendar.Clock);
Invitation.Save (DB);
-- Send the email with the reset password key
declare
Event : AWA.Events.Module_Event;
begin
Event.Set_Parameter ("key", Key.Get_Access_Key);
Event.Set_Parameter ("email", Email_Address);
Event.Set_Parameter ("name", Invitee.Get_Name);
Event.Set_Parameter ("message", Invitation.Get_Message);
Event.Set_Parameter ("inviter", User.Get_Name);
Event.Set_Event_Kind (Invite_User_Event.Kind);
Module.Send_Event (Event);
end;
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
Update the accept_invitation procedure to update the workspace member and update the invitation if the user accepted the invitation from another email address
|
Update the accept_invitation procedure to update the workspace member
and update the invitation if the user accepted the invitation from another email address
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ebf51471cbef2e51731e54f5df964b0617b942a2
|
mat/src/mat-readers-streams-sockets.adb
|
mat/src/mat-readers-streams-sockets.adb
|
-----------------------------------------------------------------------
-- mat-readers-sockets -- Reader for TCP/IP sockets
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Util.Log.Loggers;
package body MAT.Readers.Streams.Sockets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets");
BUFFER_SIZE : constant Natural := 100 * 1024;
-- ------------------------------
-- Initialize the socket listener.
-- ------------------------------
overriding
procedure Initialize (Listener : in out Socket_Listener_Type) is
begin
GNAT.Sockets.Create_Selector (Listener.Accept_Selector);
end Initialize;
-- ------------------------------
-- Destroy the socket listener.
-- ------------------------------
overriding
procedure Finalize (Listener : in out Socket_Listener_Type) is
use type GNAT.Sockets.Selector_Type;
begin
GNAT.Sockets.Close_Selector (Listener.Accept_Selector);
end Finalize;
-- ------------------------------
-- Open the socket to accept connections and start the listener task.
-- ------------------------------
procedure Start (Listener : in out Socket_Listener_Type;
Address : in GNAT.Sockets.Sock_Addr_Type) is
begin
Log.Info ("Starting the listener socket task");
Listener.Listener.Start (Listener'Unchecked_Access, Address);
end Start;
-- ------------------------------
-- Stop the listener socket.
-- ------------------------------
procedure Stop (Listener : in out Socket_Listener_Type) is
begin
GNAT.Sockets.Abort_Selector (Listener.Accept_Selector);
end Stop;
-- Create a target instance for the new client.
procedure Create_Target (Listener : in out Socket_Listener_Type;
Client : in GNAT.Sockets.Socket_Type;
Address : in GNAT.Sockets.Sock_Addr_Type) is
Reader : Socket_Reader_Type_Access := new Socket_Reader_Type;
begin
null;
end Create_Target;
task body Socket_Listener_Task is
use type GNAT.Sockets.Socket_Type;
use type GNAT.Sockets.Selector_Status;
Peer : GNAT.Sockets.Sock_Addr_Type;
Server : GNAT.Sockets.Socket_Type;
Instance : Socket_Listener_Type_Access;
Client : GNAT.Sockets.Socket_Type;
Status : GNAT.Sockets.Selector_Status;
Selector_Status : GNAT.Sockets.Selector_Status;
begin
select
accept Start (Listener : in Socket_Listener_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type) do
Instance := Listener;
GNAT.Sockets.Create_Socket (Server);
GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level,
(GNAT.Sockets.Reuse_Address, True));
GNAT.Sockets.Bind_Socket (Server, Address);
GNAT.Sockets.Listen_Socket (Server);
end Start;
or
terminate;
end select;
loop
GNAT.Sockets.Accept_Socket (Server => Server,
Socket => Client,
Address => Peer,
Timeout => GNAT.Sockets.Forever,
Selector => Instance.Accept_Selector'Access,
Status => Selector_Status);
exit when Selector_Status = GNAT.Sockets.Aborted;
if Selector_Status = GNAT.Sockets.Completed then
GNAT.Sockets.Close_Socket (Client);
end if;
end loop;
GNAT.Sockets.Close_Socket (Server);
end Socket_Listener_Task;
task body Socket_Reader_Task is
use type GNAT.Sockets.Socket_Type;
Instance : Socket_Reader_Type_Access;
Socket : GNAT.Sockets.Socket_Type;
Status : GNAT.Sockets.Selector_Status;
begin
select
accept Start (Reader : in Socket_Reader_Type_Access;
Client : in GNAT.Sockets.Socket_Type) do
Instance := Reader;
Socket := Client;
end Start;
or
terminate;
end select;
Instance.Socket.Open (Socket);
Instance.Read_All;
GNAT.Sockets.Close_Socket (Socket);
exception
when E : others =>
Log.Error ("Exception", E);
GNAT.Sockets.Close_Socket (Socket);
end Socket_Reader_Task;
-- Open the socket to accept connections.
procedure Open (Reader : in out Socket_Reader_Type;
Address : in GNAT.Sockets.Sock_Addr_Type) is
begin
Log.Info ("Reading server stream");
Reader.Stream.Initialize (Size => BUFFER_SIZE,
Input => Reader.Socket'Unchecked_Access,
Output => null);
Reader.Server.Start (Reader'Unchecked_Access, Address);
end Open;
procedure Close (Reader : in out Socket_Reader_Type) is
begin
Reader.Stop := True;
end Close;
end MAT.Readers.Streams.Sockets;
|
-----------------------------------------------------------------------
-- mat-readers-sockets -- Reader for TCP/IP sockets
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Util.Log.Loggers;
package body MAT.Readers.Streams.Sockets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets");
BUFFER_SIZE : constant Natural := 100 * 1024;
-- ------------------------------
-- Initialize the socket listener.
-- ------------------------------
overriding
procedure Initialize (Listener : in out Socket_Listener_Type) is
begin
GNAT.Sockets.Create_Selector (Listener.Accept_Selector);
end Initialize;
-- ------------------------------
-- Destroy the socket listener.
-- ------------------------------
overriding
procedure Finalize (Listener : in out Socket_Listener_Type) is
use type GNAT.Sockets.Selector_Type;
begin
GNAT.Sockets.Close_Selector (Listener.Accept_Selector);
end Finalize;
-- ------------------------------
-- Open the socket to accept connections and start the listener task.
-- ------------------------------
procedure Start (Listener : in out Socket_Listener_Type;
Address : in GNAT.Sockets.Sock_Addr_Type) is
begin
Log.Info ("Starting the listener socket task");
Listener.Listener.Start (Listener'Unchecked_Access, Address);
end Start;
-- ------------------------------
-- Stop the listener socket.
-- ------------------------------
procedure Stop (Listener : in out Socket_Listener_Type) is
begin
GNAT.Sockets.Abort_Selector (Listener.Accept_Selector);
end Stop;
-- Create a target instance for the new client.
procedure Create_Target (Listener : in out Socket_Listener_Type;
Client : in GNAT.Sockets.Socket_Type;
Address : in GNAT.Sockets.Sock_Addr_Type) is
Reader : Socket_Reader_Type_Access := new Socket_Reader_Type;
begin
Reader.Server.Start (Reader, Client);
end Create_Target;
task body Socket_Listener_Task is
use type GNAT.Sockets.Socket_Type;
use type GNAT.Sockets.Selector_Status;
Peer : GNAT.Sockets.Sock_Addr_Type;
Server : GNAT.Sockets.Socket_Type;
Instance : Socket_Listener_Type_Access;
Client : GNAT.Sockets.Socket_Type;
Status : GNAT.Sockets.Selector_Status;
Selector_Status : GNAT.Sockets.Selector_Status;
begin
select
accept Start (Listener : in Socket_Listener_Type_Access;
Address : in GNAT.Sockets.Sock_Addr_Type) do
Instance := Listener;
GNAT.Sockets.Create_Socket (Server);
GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level,
(GNAT.Sockets.Reuse_Address, True));
GNAT.Sockets.Bind_Socket (Server, Address);
GNAT.Sockets.Listen_Socket (Server);
end Start;
or
terminate;
end select;
loop
GNAT.Sockets.Accept_Socket (Server => Server,
Socket => Client,
Address => Peer,
Timeout => GNAT.Sockets.Forever,
Selector => Instance.Accept_Selector'Access,
Status => Selector_Status);
exit when Selector_Status = GNAT.Sockets.Aborted;
if Selector_Status = GNAT.Sockets.Completed then
GNAT.Sockets.Close_Socket (Client);
end if;
end loop;
GNAT.Sockets.Close_Socket (Server);
end Socket_Listener_Task;
task body Socket_Reader_Task is
use type GNAT.Sockets.Socket_Type;
Instance : Socket_Reader_Type_Access;
Socket : GNAT.Sockets.Socket_Type;
Status : GNAT.Sockets.Selector_Status;
begin
select
accept Start (Reader : in Socket_Reader_Type_Access;
Client : in GNAT.Sockets.Socket_Type) do
Instance := Reader;
Socket := Client;
end Start;
or
terminate;
end select;
Instance.Socket.Open (Socket);
Instance.Read_All;
GNAT.Sockets.Close_Socket (Socket);
exception
when E : others =>
Log.Error ("Exception", E);
GNAT.Sockets.Close_Socket (Socket);
end Socket_Reader_Task;
procedure Close (Reader : in out Socket_Reader_Type) is
begin
Reader.Stop := True;
end Close;
end MAT.Readers.Streams.Sockets;
|
Remove the Open procedure
|
Remove the Open procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
c4fa85088112ae53aa0d8a29bdbfb106a403752f
|
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
|
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-tests -- Unit tests for workspaces and invitations
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Strings;
with ADO;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
with ASF.Helpers.Beans;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with Security.Contexts;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
function Get_Invitation_Bean is
new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean,
Element_Access => Beans.Invitation_Bean_Access);
package Caller is new Util.Test_Caller (Test, "Workspaces.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send",
Test_Invite_User'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the blog as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Key : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html");
ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "This invitation is invalid");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html");
ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key,
"invitation-bad2.html");
ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist",
Reply, "Blog post missing page is invalid");
if Key = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html");
ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test sending an invitation.
-- ------------------------------
procedure Test_Invite_User (T : in out Test) is
use type ADO.Identifier;
use type AWA.Workspaces.Beans.Invitation_Bean_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Invite : AWA.Workspaces.Beans.Invitation_Bean_Access;
Check : AWA.Workspaces.Beans.Invitation_Bean;
Key : AWA.Users.Models.Access_Key_Ref;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("message", "I invite you to this application");
Request.Set_Parameter ("send", "1");
Request.Set_Parameter ("invite", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK,
"Invalid response after invitation creation");
-- Verify the invitation by looking at the inviteUser bean.
Invite := Get_Invitation_Bean (Request, "inviteUser");
T.Assert (Invite /= null, "Null inviteUser bean");
T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid");
T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null");
Check.Key := Invite.Get_Access_Key.Get_Access_Key;
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
Check.Load (Outcome);
Util.Tests.Assert_Equals (T, "success", To_String (Outcome), "Invalid invitation key");
end Test_Invite_User;
end AWA.Workspaces.Tests;
|
-----------------------------------------------------------------------
-- awa-workspaces-tests -- Unit tests for workspaces and invitations
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Strings;
with ADO;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
with ASF.Helpers.Beans;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with Security.Contexts;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
function Get_Invitation_Bean is
new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean,
Element_Access => Beans.Invitation_Bean_Access);
package Caller is new Util.Test_Caller (Test, "Workspaces.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send",
Test_Invite_User'Access);
end Add_Tests;
-- ------------------------------
-- Verify the anonymous access for the invitation page.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Key : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html");
ASF.Tests.Assert_Contains (T, "Bad or invalid invitation", Reply,
"This invitation is invalid");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply,
"This invitation is invalid (key)");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key,
"invitation-bad2.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired",
Reply, "This invitation is invalid (key)");
if Key = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html");
ASF.Tests.Assert_Contains (T, "Accept invitation", Reply,
"Accept invitation page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test sending an invitation.
-- ------------------------------
procedure Test_Invite_User (T : in out Test) is
use type ADO.Identifier;
use type AWA.Workspaces.Beans.Invitation_Bean_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Invite : AWA.Workspaces.Beans.Invitation_Bean_Access;
Check : AWA.Workspaces.Beans.Invitation_Bean;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("message", "I invite you to this application");
Request.Set_Parameter ("send", "1");
Request.Set_Parameter ("invite", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK,
"Invalid response after invitation creation");
-- Verify the invitation by looking at the inviteUser bean.
Invite := Get_Invitation_Bean (Request, "inviteUser");
T.Assert (Invite /= null, "Null inviteUser bean");
T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid");
T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null");
Check.Key := Invite.Get_Access_Key.Get_Access_Key;
T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key);
end Test_Invite_User;
end AWA.Workspaces.Tests;
|
Update the test to verify the invitation page
|
Update the test to verify the invitation page
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
411dad65c27bb03a2fff0c12e7b83f1b545d4968
|
src/asf-components-widgets-likes.adb
|
src/asf-components-widgets-likes.adb
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes 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 Util.Locales;
with Util.Beans.Objects;
with Util.Strings.Tokenizers;
-- GNAT bug, the with clause is necessary to call Get_Global on the application.
pragma Warnings (Off, "*is not referenced");
with ASF.Applications.Main;
pragma Warnings (On, "*is not referenced");
with ASF.Requests;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Likes is
FB_LAYOUT_ATTR : aliased constant String := "data-layout";
FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces";
FB_WIDTH_ATTR : aliased constant String := "data-width";
FB_ACTION_ATTR : aliased constant String := "data-action";
FB_FONT_ATTR : aliased constant String := "data-font";
FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme";
FB_REF_ATTR : aliased constant String := "data-ref";
FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site";
FB_SEND_ATTR : aliased constant String := "data-send";
TW_VIA_ATTR : aliased constant String := "data-via";
TW_COUNT_ATTR : aliased constant String := "data-count";
TW_SIZE_ATTR : aliased constant String := "data-size";
G_ANNOTATION_ATTR : aliased constant String := "data-annotation";
G_WIDTH_ATTR : aliased constant String := "data-width";
FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script";
GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script";
TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script";
type Like_Generator_Binding is record
Name : Util.Strings.Name_Access;
Generator : Like_Generator_Access;
end record;
type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding;
FB_NAME : aliased constant String := "facebook";
FB_GENERATOR : aliased Facebook_Like_Generator;
G_NAME : aliased constant String := "google+";
G_GENERATOR : aliased Google_Like_Generator;
TWITTER_NAME : aliased constant String := "twitter";
TWITTER_GENERATOR : aliased Twitter_Like_Generator;
Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access),
2 => (G_NAME'Access, G_GENERATOR'Access),
3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access),
others => (null, null));
-- ------------------------------
-- Render the facebook like button according to the component attributes.
-- ------------------------------
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];"
& "if (d.getElementById(id)) return;"
& "js = d.createElement(s); js.id = id;js.async=true;"
& "js.src = ""//connect.facebook.net/");
Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale));
Writer.Queue_Script ("/all.js#xfbml=1&;appId=");
declare
App_Id : constant String
:= Context.Get_Application.Get_Config (P_Facebook_App_Id.P);
begin
if App_Id'Length = 0 then
UI.Log_Error ("The facebook client application id is empty");
UI.Log_Error ("Please, configure the '{0}' property "
& "in the application", P_Facebook_App_Id.PARAM_NAME);
else
Writer.Queue_Script (App_Id);
end if;
end;
Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);"
& "}(document, 'script', 'facebook-jssdk'));");
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", "fb-root");
Writer.End_Element ("div");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "fb-like");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Google like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "g-plusone");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Tweeter like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Twitter_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale);
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],"
& "p=/^http:/.test(d.location)?'http':'https';"
& "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;"
& "js.src=p+'://platform.twitter.com/widgets.js';"
& "fjs.parentNode.insertBefore(js,fjs);}}"
& "(document, 'script', 'twitter-wjs');");
end if;
Writer.Start_Element ("a");
Writer.Write_Attribute ("href", "https://twitter.com/share");
Writer.Write_Attribute ("class", "twitter-share-button");
Writer.Write_Attribute ("data-url", Href);
Writer.Write_Attribute ("data-lang", Lang);
UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer);
Writer.Write_Text ("Tweet");
Writer.End_Element ("a");
end Render_Like;
-- ------------------------------
-- Get the link to submit in the like action.
-- ------------------------------
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Href : constant String := UI.Get_Attribute ("href", Context, "");
begin
if Href'Length > 0 then
return Href;
else
return Context.Get_Request.Get_Request_URI;
end if;
end Get_Link;
-- ------------------------------
-- Render an image with the source link created from an email address to the Gravatars service.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Writer : constant Contexts.Writer.Response_Writer_Access
:= Context.Get_Response_Writer;
Kind : constant String := UI.Get_Attribute ("type", Context, "");
Href : constant String := UILike'Class (UI).Get_Link (Context);
Style : constant String := UI.Get_Attribute ("style", Context, "");
Class : constant String := UI.Get_Attribute ("styleClass", Context, "");
procedure Render (Name : in String; Done : out Boolean);
procedure Render (Name : in String;
Done : out Boolean) is
use type Util.Strings.Name_Access;
begin
Done := False;
for I in Generators'Range loop
exit when Generators (I).Name = null;
if Generators (I).Name.all = Name then
Writer.Start_Element ("div");
if Style'Length > 0 then
Writer.Write_Attribute ("style", Style);
end if;
if Class'Length > 0 then
Writer.Write_Attribute ("class", Class);
end if;
Generators (I).Generator.Render_Like (UI, Href, Context);
Writer.End_Element ("div");
return;
end if;
end loop;
UI.Log_Error ("Like type {0} is not recognized", Name);
end Render;
begin
if Kind'Length = 0 then
UI.Log_Error ("The like type is empty.");
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",",
Process => Render'Access);
end if;
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Register the like generator under the given name.
-- ------------------------------
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access) is
use type Util.Strings.Name_Access;
begin
for I in Generators'Range loop
if Generators (I).Name = null then
Generators (I).Name := Name;
Generators (I).Generator := Generator;
return;
end if;
end loop;
end Register_Like;
begin
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access);
end ASF.Components.Widgets.Likes;
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes Components
-- Copyright (C) 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Locales;
with Util.Beans.Objects;
with Util.Strings.Tokenizers;
-- GNAT bug, the with clause is necessary to call Get_Global on the application.
pragma Warnings (Off, "*is not referenced");
with ASF.Applications.Main;
pragma Warnings (On, "*is not referenced");
with ASF.Requests;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Likes is
FB_LAYOUT_ATTR : aliased constant String := "data-layout";
FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces";
FB_WIDTH_ATTR : aliased constant String := "data-width";
FB_ACTION_ATTR : aliased constant String := "data-action";
FB_FONT_ATTR : aliased constant String := "data-font";
FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme";
FB_REF_ATTR : aliased constant String := "data-ref";
FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site";
FB_SEND_ATTR : aliased constant String := "data-send";
TW_VIA_ATTR : aliased constant String := "data-via";
TW_COUNT_ATTR : aliased constant String := "data-count";
TW_SIZE_ATTR : aliased constant String := "data-size";
TW_COUNTURL_ATTR : aliased constant String := "data-counturl";
TW_TEXT_ATTR : aliased constant String := "data-text";
TW_RELATED_ATTR : aliased constant String := "data-related";
TW_LANG_ATTR : aliased constant String := "data-lang";
TW_HASHTAGS_ATTR : aliased constant String := "data-hashtags";
G_ANNOTATION_ATTR : aliased constant String := "data-annotation";
G_WIDTH_ATTR : aliased constant String := "data-width";
FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script";
GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script";
TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script";
type Like_Generator_Binding is record
Name : Util.Strings.Name_Access;
Generator : Like_Generator_Access;
end record;
type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding;
FB_NAME : aliased constant String := "facebook";
FB_GENERATOR : aliased Facebook_Like_Generator;
G_NAME : aliased constant String := "google+";
G_GENERATOR : aliased Google_Like_Generator;
TWITTER_NAME : aliased constant String := "twitter";
TWITTER_GENERATOR : aliased Twitter_Like_Generator;
Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access),
2 => (G_NAME'Access, G_GENERATOR'Access),
3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access),
others => (null, null));
-- ------------------------------
-- Render the facebook like button according to the component attributes.
-- ------------------------------
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];"
& "if (d.getElementById(id)) return;"
& "js = d.createElement(s); js.id = id;js.async=true;"
& "js.src = ""//connect.facebook.net/");
Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale));
Writer.Queue_Script ("/all.js#xfbml=1&;appId=");
declare
App_Id : constant String
:= Context.Get_Application.Get_Config (P_Facebook_App_Id.P);
begin
if App_Id'Length = 0 then
UI.Log_Error ("The facebook client application id is empty");
UI.Log_Error ("Please, configure the '{0}' property "
& "in the application", P_Facebook_App_Id.PARAM_NAME);
else
Writer.Queue_Script (App_Id);
end if;
end;
Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);"
& "}(document, 'script', 'facebook-jssdk'));");
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", "fb-root");
Writer.End_Element ("div");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "fb-like");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Google like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "g-plusone");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Tweeter like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Twitter_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale);
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],"
& "p=/^http:/.test(d.location)?'http':'https';"
& "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;"
& "js.src=p+'://platform.twitter.com/widgets.js';"
& "fjs.parentNode.insertBefore(js,fjs);}}"
& "(document, 'script', 'twitter-wjs');");
end if;
Writer.Start_Element ("a");
Writer.Write_Attribute ("href", "https://twitter.com/share");
Writer.Write_Attribute ("class", "twitter-share-button");
Writer.Write_Attribute ("data-url", Href);
Writer.Write_Attribute ("data-lang", Lang);
UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer);
Writer.Write_Text ("Tweet");
Writer.End_Element ("a");
end Render_Like;
-- ------------------------------
-- Get the link to submit in the like action.
-- ------------------------------
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Href : constant String := UI.Get_Attribute ("href", Context, "");
begin
if Href'Length > 0 then
return Href;
else
return Context.Get_Request.Get_Request_URI;
end if;
end Get_Link;
-- ------------------------------
-- Render an image with the source link created from an email address to the Gravatars service.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Writer : constant Contexts.Writer.Response_Writer_Access
:= Context.Get_Response_Writer;
Kind : constant String := UI.Get_Attribute ("type", Context, "");
Href : constant String := UILike'Class (UI).Get_Link (Context);
Style : constant String := UI.Get_Attribute ("style", Context, "");
Class : constant String := UI.Get_Attribute ("styleClass", Context, "");
procedure Render (Name : in String; Done : out Boolean);
procedure Render (Name : in String;
Done : out Boolean) is
use type Util.Strings.Name_Access;
begin
Done := False;
for I in Generators'Range loop
exit when Generators (I).Name = null;
if Generators (I).Name.all = Name then
Writer.Start_Element ("div");
if Style'Length > 0 then
Writer.Write_Attribute ("style", Style);
end if;
if Class'Length > 0 then
Writer.Write_Attribute ("class", Class);
end if;
Generators (I).Generator.Render_Like (UI, Href, Context);
Writer.End_Element ("div");
return;
end if;
end loop;
UI.Log_Error ("Like type {0} is not recognized", Name);
end Render;
begin
if Kind'Length = 0 then
UI.Log_Error ("The like type is empty.");
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",",
Process => Render'Access);
end if;
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Register the like generator under the given name.
-- ------------------------------
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access) is
use type Util.Strings.Name_Access;
begin
for I in Generators'Range loop
if Generators (I).Name = null then
Generators (I).Name := Name;
Generators (I).Generator := Generator;
return;
end if;
end loop;
end Register_Like;
begin
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNTURL_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_TEXT_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_RELATED_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_LANG_ATTR'Access);
TWITTER_ATTRIBUTE_NAMES.Insert (TW_HASHTAGS_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access);
end ASF.Components.Widgets.Likes;
|
Add several Twitter attributes for the Tweet button
|
Add several Twitter attributes for the Tweet button
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
fcbd117a30d40ea03fc4af8b7e4aa145e7cda0da
|
src/asf-components-widgets-likes.ads
|
src/asf-components-widgets-likes.ads
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes 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 Util.Strings;
with ASF.Components.Html;
with ASF.Contexts.Faces;
package ASF.Components.Widgets.Likes is
-- ------------------------------
-- UILike
-- ------------------------------
-- The <b>UILike</b> component displays a social like button to recommend a page.
type UILike is new ASF.Components.Html.UIHtmlComponent with null record;
-- Get the link to submit in the like action.
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String;
-- Render the like button for Facebook or Google+.
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Like Generator
-- ------------------------------
-- The <tt>Like_Generator</tt> represents the specific method for the generation of
-- a social like generator. A generator is registered under a given name with the
-- <tt>Register_Like</tt> operation. The current implementation provides a Facebook
-- like generator.
type Like_Generator is limited interface;
type Like_Generator_Access is access all Like_Generator'Class;
-- Render the like button according to the generator and the component attributes.
procedure Render_Like (Generator : in Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract;
-- Maximum number of generators that can be registered.
MAX_LIKE_GENERATOR : constant Positive := 5;
-- Register the like generator under the given name.
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access);
-- ------------------------------
-- Facebook like generator
-- ------------------------------
type Facebook_Like_Generator is new Like_Generator with record
App_Id : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end ASF.Components.Widgets.Likes;
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes 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 Util.Strings;
with ASF.Components.Html;
with ASF.Contexts.Faces;
package ASF.Components.Widgets.Likes is
-- ------------------------------
-- UILike
-- ------------------------------
-- The <b>UILike</b> component displays a social like button to recommend a page.
type UILike is new ASF.Components.Html.UIHtmlComponent with null record;
-- Get the link to submit in the like action.
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String;
-- Render the like button for Facebook or Google+.
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Like Generator
-- ------------------------------
-- The <tt>Like_Generator</tt> represents the specific method for the generation of
-- a social like generator. A generator is registered under a given name with the
-- <tt>Register_Like</tt> operation. The current implementation provides a Facebook
-- like generator.
type Like_Generator is limited interface;
type Like_Generator_Access is access all Like_Generator'Class;
-- Render the like button according to the generator and the component attributes.
procedure Render_Like (Generator : in Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract;
-- Maximum number of generators that can be registered.
MAX_LIKE_GENERATOR : constant Positive := 5;
-- Register the like generator under the given name.
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access);
-- ------------------------------
-- Facebook like generator
-- ------------------------------
type Facebook_Like_Generator is new Like_Generator with record
App_Id : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Google like generator
-- ------------------------------
type Google_Like_Generator is new Like_Generator with null record;
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end ASF.Components.Widgets.Likes;
|
Define the Google_Like_Generator type
|
Define the Google_Like_Generator type
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b5a0e2dd5d74d178391a7d2ce6c76be469e359b4
|
src/asf-navigations.adb
|
src/asf-navigations.adb
|
-----------------------------------------------------------------------
-- asf-navigations -- Navigations
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Root;
with Util.Strings;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ASF.Applications.Main;
with ASF.Navigations.Render;
package body ASF.Navigations is
-- ------------------------------
-- Navigation Case
-- ------------------------------
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Navigations");
-- ------------------------------
-- Check if the navigator specific condition matches the current execution context.
-- ------------------------------
function Matches (Navigator : in Navigation_Case;
Action : in String;
Outcome : in String;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is
begin
-- outcome must match
if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then
return False;
end if;
-- action must match
if Navigator.Action /= null and then Navigator.Action.all /= Action then
return False;
end if;
-- condition must be true
if not Navigator.Condition.Is_Constant then
declare
Value : constant Util.Beans.Objects.Object
:= Navigator.Condition.Get_Value (Context.Get_ELContext.all);
begin
if not Util.Beans.Objects.To_Boolean (Value) then
return False;
end if;
end;
end if;
return True;
end Matches;
-- ------------------------------
-- Navigation Rule
-- ------------------------------
-- ------------------------------
-- Search for the navigator that matches the current action, outcome and context.
-- Returns the navigator or null if there was no match.
-- ------------------------------
function Find_Navigation (Controller : in Rule;
Action : in String;
Outcome : in String;
Context : in Contexts.Faces.Faces_Context'Class)
return Navigation_Access is
Iter : Navigator_Vector.Cursor := Controller.Navigators.First;
Navigator : Navigation_Access;
begin
while Navigator_Vector.Has_Element (Iter) loop
Navigator := Navigator_Vector.Element (Iter);
-- Check if this navigator matches the action/outcome.
if Navigator.Matches (Action, Outcome, Context) then
return Navigator;
end if;
Navigator_Vector.Next (Iter);
end loop;
return null;
end Find_Navigation;
-- ------------------------------
-- Clear the navigation rules.
-- ------------------------------
procedure Clear (Controller : in out Rule) is
procedure Free is new Ada.Unchecked_Deallocation (Navigation_Case'Class,
Navigation_Access);
begin
while not Controller.Navigators.Is_Empty loop
declare
Iter : Navigator_Vector.Cursor := Controller.Navigators.Last;
Navigator : Navigation_Access := Navigator_Vector.Element (Iter);
begin
Free (Navigator.Outcome);
Free (Navigator.Action);
Free (Navigator);
Controller.Navigators.Delete (Iter);
end;
end loop;
end Clear;
-- ------------------------------
-- Clear the navigation rules.
-- ------------------------------
procedure Clear (Controller : in out Navigation_Rules) is
procedure Free is new Ada.Unchecked_Deallocation (Rule'Class, Rule_Access);
begin
while not Controller.Rules.Is_Empty loop
declare
Iter : Rule_Map.Cursor := Controller.Rules.First;
Rule : Rule_Access := Rule_Map.Element (Iter);
begin
Rule.Clear;
Free (Rule);
Controller.Rules.Delete (Iter);
end;
end loop;
end Clear;
-- ------------------------------
-- Navigation Handler
-- ------------------------------
-- ------------------------------
-- Provide a default navigation rules for the view and the outcome when no application
-- navigation was found. The default looks for an XHTML file in the same directory as
-- the view and which has the base name defined by <b>Outcome</b>.
-- ------------------------------
procedure Handle_Default_Navigation (Handler : in Navigation_Handler;
View : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Pos : constant Natural := Util.Strings.Rindex (View, '/');
Root : Components.Root.UIViewRoot;
View_Handler : access ASF.Applications.Views.View_Handler'Class := Handler.View_Handler;
begin
if View_Handler = null then
View_Handler := Handler.Application.Get_View_Handler;
end if;
if Pos > 0 then
declare
Name : constant String := View (View'First .. Pos) & Outcome;
begin
Log.Debug ("Using default navigatation from view {0} to {1}", View, Name);
View_Handler.Create_View (Name, Context, Root);
end;
else
Log.Debug ("Using default navigatation from view {0} to {1}", View, View);
View_Handler.Create_View (Outcome, Context, Root);
end if;
-- If the 'outcome' refers to a real view, use it. Otherwise keep the current view.
if Components.Root.Get_Root (Root) /= null then
Context.Set_View_Root (Root);
end if;
exception
when others =>
Log.Debug ("No suitable navigation rule to navigate from view {0}: {1}",
View, Outcome);
raise;
end Handle_Default_Navigation;
-- ------------------------------
-- After executing an action and getting the action outcome, proceed to the navigation
-- to the next page.
-- ------------------------------
procedure Handle_Navigation (Handler : in Navigation_Handler;
Action : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Nav_Rules : constant Navigation_Rules_Access := Handler.Rules;
View : constant Components.Root.UIViewRoot := Context.Get_View_Root;
Name : constant String := Components.Root.Get_View_Id (View);
function Find_Navigation (View : in String) return Navigation_Access;
function Find_Navigation (View : in String) return Navigation_Access is
Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View));
begin
if not Rule_Map.Has_Element (Pos) then
return null;
end if;
return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context);
end Find_Navigation;
Navigator : Navigation_Access;
begin
Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome);
-- Find an exact match
Navigator := Find_Navigation (Name);
-- Find a wildcard match
if Navigator = null then
declare
Last : Natural := Name'Last;
N : Natural;
begin
loop
N := Util.Strings.Rindex (Name, '/', Last);
exit when N = 0;
Navigator := Find_Navigation (Name (Name'First .. N) & "*");
exit when Navigator /= null or N = Name'First;
Last := N - 1;
end loop;
end;
end if;
-- Execute the navigation action.
if Navigator /= null then
Navigator.Navigate (Context);
else
Log.Debug ("No navigation rule found for view {0}, action {1} and outcome {2}",
Name, Action, Outcome);
Navigation_Handler'Class (Handler).Handle_Default_Navigation (Name, Outcome, Context);
end if;
end Handle_Navigation;
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Handler : in out Navigation_Handler;
App : access ASF.Applications.Main.Application'Class) is
begin
Handler.Rules := new Navigation_Rules;
Handler.Application := App;
end Initialize;
-- ------------------------------
-- Free the storage used by the navigation handler.
-- ------------------------------
overriding
procedure Finalize (Handler : in out Navigation_Handler) is
procedure Free is new Ada.Unchecked_Deallocation (Navigation_Rules, Navigation_Rules_Access);
begin
if Handler.Rules /= null then
Clear (Handler.Rules.all);
Free (Handler.Rules);
end if;
end Finalize;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- to the result view identified by <b>To</b>. Some optional conditions are evaluated
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler;
From : in String;
To : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
C : constant Navigation_Access := Render.Create_Render_Navigator (To);
begin
Handler.Add_Navigation_Case (C, From, Outcome, Action, Condition);
end Add_Navigation_Case;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- by using the navigation rule defined by <b>Navigator</b>.
-- Some optional conditions are evaluated:
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class;
Navigator : in Navigation_Access;
From : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
pragma Unreferenced (Condition);
begin
Log.Info ("Add navigation from {0} with outcome {1}", From, Outcome);
if Outcome'Length > 0 then
Navigator.Outcome := new String '(Outcome);
end if;
if Action'Length > 0 then
Navigator.Action := new String '(Action);
end if;
if Handler.View_Handler = null then
Handler.View_Handler := Handler.Application.Get_View_Handler;
end if;
Navigator.View_Handler := Handler.View_Handler;
declare
View : constant Unbounded_String := To_Unbounded_String (From);
Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View);
R : Rule_Access;
begin
if not Rule_Map.Has_Element (Pos) then
R := new Rule;
Handler.Rules.Rules.Include (Key => View,
New_Item => R);
else
R := Rule_Map.Element (Pos);
end if;
R.Navigators.Append (Navigator);
end;
end Add_Navigation_Case;
end ASF.Navigations;
|
-----------------------------------------------------------------------
-- asf-navigations -- Navigations
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Root;
with Util.Strings;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ASF.Applications.Main;
with ASF.Navigations.Render;
package body ASF.Navigations is
-- ------------------------------
-- Navigation Case
-- ------------------------------
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Navigations");
-- ------------------------------
-- Check if the navigator specific condition matches the current execution context.
-- ------------------------------
function Matches (Navigator : in Navigation_Case;
Action : in String;
Outcome : in String;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is
begin
-- outcome must match
if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then
return False;
end if;
-- action must match
if Navigator.Action /= null and then Navigator.Action.all /= Action then
return False;
end if;
-- condition must be true
if not Navigator.Condition.Is_Constant then
declare
Value : constant Util.Beans.Objects.Object
:= Navigator.Condition.Get_Value (Context.Get_ELContext.all);
begin
if not Util.Beans.Objects.To_Boolean (Value) then
return False;
end if;
end;
end if;
return True;
end Matches;
-- ------------------------------
-- Navigation Rule
-- ------------------------------
-- ------------------------------
-- Search for the navigator that matches the current action, outcome and context.
-- Returns the navigator or null if there was no match.
-- ------------------------------
function Find_Navigation (Controller : in Rule;
Action : in String;
Outcome : in String;
Context : in Contexts.Faces.Faces_Context'Class)
return Navigation_Access is
Iter : Navigator_Vector.Cursor := Controller.Navigators.First;
Navigator : Navigation_Access;
begin
while Navigator_Vector.Has_Element (Iter) loop
Navigator := Navigator_Vector.Element (Iter);
-- Check if this navigator matches the action/outcome.
if Navigator.Matches (Action, Outcome, Context) then
return Navigator;
end if;
Navigator_Vector.Next (Iter);
end loop;
return null;
end Find_Navigation;
-- ------------------------------
-- Clear the navigation rules.
-- ------------------------------
procedure Clear (Controller : in out Rule) is
procedure Free is new Ada.Unchecked_Deallocation (Navigation_Case'Class,
Navigation_Access);
begin
while not Controller.Navigators.Is_Empty loop
declare
Iter : Navigator_Vector.Cursor := Controller.Navigators.Last;
Navigator : Navigation_Access := Navigator_Vector.Element (Iter);
begin
Free (Navigator.Outcome);
Free (Navigator.Action);
Free (Navigator);
Controller.Navigators.Delete (Iter);
end;
end loop;
end Clear;
-- ------------------------------
-- Clear the navigation rules.
-- ------------------------------
procedure Clear (Controller : in out Navigation_Rules) is
procedure Free is new Ada.Unchecked_Deallocation (Rule'Class, Rule_Access);
begin
while not Controller.Rules.Is_Empty loop
declare
Iter : Rule_Map.Cursor := Controller.Rules.First;
Rule : Rule_Access := Rule_Map.Element (Iter);
begin
Rule.Clear;
Free (Rule);
Controller.Rules.Delete (Iter);
end;
end loop;
end Clear;
-- ------------------------------
-- Navigation Handler
-- ------------------------------
-- ------------------------------
-- Provide a default navigation rules for the view and the outcome when no application
-- navigation was found. The default looks for an XHTML file in the same directory as
-- the view and which has the base name defined by <b>Outcome</b>.
-- ------------------------------
procedure Handle_Default_Navigation (Handler : in Navigation_Handler;
View : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Pos : constant Natural := Util.Strings.Rindex (View, '/');
Root : Components.Root.UIViewRoot;
View_Handler : access ASF.Applications.Views.View_Handler'Class := Handler.View_Handler;
begin
if View_Handler = null then
View_Handler := Handler.Application.Get_View_Handler;
end if;
if Pos > 0 then
declare
Name : constant String := View (View'First .. Pos) & Outcome;
begin
Log.Debug ("Using default navigation from view {0} to {1}", View, Name);
View_Handler.Create_View (Name, Context, Root);
end;
else
Log.Debug ("Using default navigation from view {0} to {1}", View, View);
View_Handler.Create_View (Outcome, Context, Root);
end if;
-- If the 'outcome' refers to a real view, use it. Otherwise keep the current view.
if Components.Root.Get_Root (Root) /= null then
Context.Set_View_Root (Root);
end if;
exception
when others =>
Log.Debug ("No suitable navigation rule to navigate from view {0}: {1}",
View, Outcome);
raise;
end Handle_Default_Navigation;
-- ------------------------------
-- After executing an action and getting the action outcome, proceed to the navigation
-- to the next page.
-- ------------------------------
procedure Handle_Navigation (Handler : in Navigation_Handler;
Action : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Nav_Rules : constant Navigation_Rules_Access := Handler.Rules;
View : constant Components.Root.UIViewRoot := Context.Get_View_Root;
Name : constant String := Components.Root.Get_View_Id (View);
function Find_Navigation (View : in String) return Navigation_Access;
function Find_Navigation (View : in String) return Navigation_Access is
Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View));
begin
if not Rule_Map.Has_Element (Pos) then
return null;
end if;
return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context);
end Find_Navigation;
Navigator : Navigation_Access;
begin
Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome);
-- Find an exact match
Navigator := Find_Navigation (Name);
-- Find a wildcard match
if Navigator = null then
declare
Last : Natural := Name'Last;
N : Natural;
begin
loop
N := Util.Strings.Rindex (Name, '/', Last);
exit when N = 0;
Navigator := Find_Navigation (Name (Name'First .. N) & "*");
exit when Navigator /= null or N = Name'First;
Last := N - 1;
end loop;
end;
end if;
-- Execute the navigation action.
if Navigator /= null then
Navigator.Navigate (Context);
else
Log.Debug ("No navigation rule found for view {0}, action {1} and outcome {2}",
Name, Action, Outcome);
Navigation_Handler'Class (Handler).Handle_Default_Navigation (Name, Outcome, Context);
end if;
end Handle_Navigation;
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Handler : in out Navigation_Handler;
App : access ASF.Applications.Main.Application'Class) is
begin
Handler.Rules := new Navigation_Rules;
Handler.Application := App;
end Initialize;
-- ------------------------------
-- Free the storage used by the navigation handler.
-- ------------------------------
overriding
procedure Finalize (Handler : in out Navigation_Handler) is
procedure Free is new Ada.Unchecked_Deallocation (Navigation_Rules, Navigation_Rules_Access);
begin
if Handler.Rules /= null then
Clear (Handler.Rules.all);
Free (Handler.Rules);
end if;
end Finalize;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- to the result view identified by <b>To</b>. Some optional conditions are evaluated
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler;
From : in String;
To : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
C : constant Navigation_Access := Render.Create_Render_Navigator (To);
begin
Handler.Add_Navigation_Case (C, From, Outcome, Action, Condition);
end Add_Navigation_Case;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- by using the navigation rule defined by <b>Navigator</b>.
-- Some optional conditions are evaluated:
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class;
Navigator : in Navigation_Access;
From : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
pragma Unreferenced (Condition);
begin
Log.Info ("Add navigation from {0} with outcome {1}", From, Outcome);
if Outcome'Length > 0 then
Navigator.Outcome := new String '(Outcome);
end if;
if Action'Length > 0 then
Navigator.Action := new String '(Action);
end if;
if Handler.View_Handler = null then
Handler.View_Handler := Handler.Application.Get_View_Handler;
end if;
Navigator.View_Handler := Handler.View_Handler;
declare
View : constant Unbounded_String := To_Unbounded_String (From);
Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View);
R : Rule_Access;
begin
if not Rule_Map.Has_Element (Pos) then
R := new Rule;
Handler.Rules.Rules.Include (Key => View,
New_Item => R);
else
R := Rule_Map.Element (Pos);
end if;
R.Navigators.Append (Navigator);
end;
end Add_Navigation_Case;
end ASF.Navigations;
|
Fix log messages in navigation rules.
|
Fix log messages in navigation rules.
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
dd4f6db84891976f03c569b59af4bf193a86b383
|
src/orka/interface/sdl/orka-inputs-sdl.ads
|
src/orka/interface/sdl/orka-inputs-sdl.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2019 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 SDL.Events.Mice;
with SDL.Video.Windows;
with Orka.Inputs.Pointers.Default;
package Orka.Inputs.SDL is
pragma Preelaborate;
type SDL_Pointer_Input is new Pointers.Default.Abstract_Pointer_Input with private;
overriding
procedure Set_Cursor_Mode
(Object : in out SDL_Pointer_Input;
Mode : Pointers.Default.Cursor_Mode);
procedure Set_Button_State
(Object : in out SDL_Pointer_Input;
Subject : Standard.SDL.Events.Mice.Buttons;
State : Pointers.Button_State);
procedure Set_Window
(Object : in out SDL_Pointer_Input;
Window : Standard.SDL.Video.Windows.Window);
function Create_Pointer_Input return Inputs.Pointers.Pointer_Input_Ptr;
private
type SDL_Pointer_Input is new Pointers.Default.Abstract_Pointer_Input with record
Window : Standard.SDL.Video.Windows.ID;
end record;
end Orka.Inputs.SDL;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2019 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 SDL.Events.Mice;
with SDL.Video.Windows;
with Orka.Inputs.Pointers.Default;
package Orka.Inputs.SDL is
type SDL_Pointer_Input is new Pointers.Default.Abstract_Pointer_Input with private;
overriding
procedure Set_Cursor_Mode
(Object : in out SDL_Pointer_Input;
Mode : Pointers.Default.Cursor_Mode);
procedure Set_Button_State
(Object : in out SDL_Pointer_Input;
Subject : Standard.SDL.Events.Mice.Buttons;
State : Pointers.Button_State);
procedure Set_Window
(Object : in out SDL_Pointer_Input;
Window : Standard.SDL.Video.Windows.Window);
function Create_Pointer_Input return Inputs.Pointers.Pointer_Input_Ptr;
private
type SDL_Pointer_Input is new Pointers.Default.Abstract_Pointer_Input with record
Window : Standard.SDL.Video.Windows.ID;
end record;
end Orka.Inputs.SDL;
|
Fix compiling orka-sdl library
|
orka: Fix compiling orka-sdl library
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
2947a361bc1b9d09b100bf8cbab35b35cc168137
|
tools/druss-commands.adb
|
tools/druss-commands.adb
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- 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 Druss.Commands.Bboxes;
with Druss.Commands.Get;
with Druss.Commands.Status;
with Druss.Commands.Wifi;
package body Druss.Commands is
Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type;
Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type;
Get_Commands : aliased Druss.Commands.Get.Command_Type;
Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type) is
begin
if Args.Get_Count < Arg_Pos + 1 then
Druss.Commands.Driver.Usage (Args);
end if;
declare
Param : constant String := Args.Get_Argument (Arg_Pos);
Gw : Druss.Gateways.Gateway_Ref;
procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is
begin
Process (Gateway, Param);
end Operation;
begin
if Args.Get_Count = Arg_Pos then
Druss.Gateways.Iterate (Context.Gateways, Operation'Access);
else
for I in Arg_Pos + 1 .. Args.Get_Count loop
Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I));
if not Gw.Is_Null then
Operation (Gw.Value.all);
end if;
end loop;
end if;
end;
end Gateway_Command;
procedure Initialize is
begin
Driver.Set_Description ("Druss - The Bbox master controller");
Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF &
"where:" & ASCII.LF &
" -v Verbose execution mode" & ASCII.LF &
" -c config Use the configuration file" &
" (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF &
" -o file The output file to use");
Driver.Add_Command ("help", Help_Command'Access);
Driver.Add_Command ("bbox", Bbox_Commands'Access);
Driver.Add_Command ("get", Get_Commands'Access);
Driver.Add_Command ("wifi", Wifi_Commands'Access);
Driver.Add_Command ("status", Druss.Commands.Status.Wan_Status'Access);
end Initialize;
end Druss.Commands;
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- 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 Druss.Commands.Bboxes;
with Druss.Commands.Get;
with Druss.Commands.Status;
with Druss.Commands.Wifi;
package body Druss.Commands is
Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type;
Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type;
Get_Commands : aliased Druss.Commands.Get.Command_Type;
Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type;
Status_Commands : aliased Druss.Commands.Status.Command_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type) is
begin
if Args.Get_Count < Arg_Pos + 1 then
Druss.Commands.Driver.Usage (Args);
end if;
declare
Param : constant String := Args.Get_Argument (Arg_Pos);
Gw : Druss.Gateways.Gateway_Ref;
procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is
begin
Process (Gateway, Param);
end Operation;
begin
if Args.Get_Count = Arg_Pos then
Druss.Gateways.Iterate (Context.Gateways, Operation'Access);
else
for I in Arg_Pos + 1 .. Args.Get_Count loop
Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I));
if not Gw.Is_Null then
Operation (Gw.Value.all);
end if;
end loop;
end if;
end;
end Gateway_Command;
procedure Initialize is
begin
Driver.Set_Description ("Druss - The Bbox master controller");
Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF &
"where:" & ASCII.LF &
" -v Verbose execution mode" & ASCII.LF &
" -c config Use the configuration file" &
" (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF &
" -o file The output file to use");
Driver.Add_Command ("help", Help_Command'Access);
Driver.Add_Command ("bbox", Bbox_Commands'Access);
Driver.Add_Command ("get", Get_Commands'Access);
Driver.Add_Command ("wifi", Wifi_Commands'Access);
Driver.Add_Command ("status", Status_Commands'Access);
end Initialize;
end Druss.Commands;
|
Update to add the status command
|
Update to add the status command
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
5ba0ff1950cda97c019401e56cba37a5eeec0596
|
resources/scripts/scrape/duckduckgo.ads
|
resources/scripts/scrape/duckduckgo.ads
|
-- Copyright 2021 Jeff Foley. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
name = "DuckDuckGo"
type = "scrape"
function start()
setratelimit(1)
end
function vertical(ctx, domain)
scrape(ctx, {['url']="https://html.duckduckgo.com/html/?q=site:" .. domain})
end
|
-- Copyright 2021 Jeff Foley. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
name = "DuckDuckGo"
type = "scrape"
function start()
setratelimit(1)
end
function vertical(ctx, domain)
scrape(ctx, {['url']=buildurl(domain)})
end
function buildurl(domain)
return "https://html.duckduckgo.com/html/?q=site:" .. domain .. " -site:www." .. domain
end
|
Exclude www from DuckDuckGo search result
|
Exclude www from DuckDuckGo search result
|
Ada
|
apache-2.0
|
caffix/amass,caffix/amass
|
1c4b4f689602137fad5309484dd5cd5d1a96571a
|
src/security-permissions.adb
|
src/security-permissions.adb
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Log.Loggers;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Permissions is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- A global map to translate a string to a permission index.
package Permission_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Permission_Index,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
protected type Global_Index is
-- Get the permission index
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;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := Permission_Index'First;
end Global_Index;
protected body Global_Index is
function Get_Permission_Index (Name : in String) return Permission_Index is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
return Permission_Maps.Element (Pos);
else
raise Invalid_Name with "There is no permission '" & Name & "'";
end if;
end Get_Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index is
begin
return Next_Index;
end Get_Last_Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
Index := Permission_Maps.Element (Pos);
else
Index := Next_Index;
Log.Debug ("Creating permission index {1} for {0}",
Name, Permission_Index'Image (Index));
Map.Insert (Name, Index);
Next_Index := Next_Index + 1;
end if;
end Add_Permission;
end Global_Index;
Permission_Indexes : Global_Index;
-- ------------------------------
-- Get the permission index associated with the name.
-- ------------------------------
function Get_Permission_Index (Name : in String) return Permission_Index is
begin
return Permission_Indexes.Get_Permission_Index (Name);
end Get_Permission_Index;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Permission_Indexes.Get_Last_Permission_Index;
end Get_Last_Permission_Index;
-- ------------------------------
-- Add the permission name and allocate a unique permission index.
-- ------------------------------
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
begin
Permission_Indexes.Add_Permission (Name, Index);
end Add_Permission;
package body Permission_ACL is
P : Permission_Index;
function Permission return Permission_Index is
begin
return P;
end Permission;
begin
Add_Permission (Name => Name, Index => P);
end Permission_ACL;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Log.Loggers;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Permissions is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- A global map to translate a string to a permission index.
package Permission_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Permission_Index,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
protected type Global_Index is
-- Get the permission index
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;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := Permission_Index'First;
end Global_Index;
protected body Global_Index is
function Get_Permission_Index (Name : in String) return Permission_Index is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
return Permission_Maps.Element (Pos);
else
raise Invalid_Name with "There is no permission '" & Name & "'";
end if;
end Get_Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index is
begin
return Next_Index;
end Get_Last_Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
Index := Permission_Maps.Element (Pos);
else
Index := Next_Index;
Log.Debug ("Creating permission index {1} for {0}",
Name, Permission_Index'Image (Index));
Map.Insert (Name, Index);
Next_Index := Next_Index + 1;
end if;
end Add_Permission;
end Global_Index;
Permission_Indexes : Global_Index;
-- ------------------------------
-- Get the permission index associated with the name.
-- ------------------------------
function Get_Permission_Index (Name : in String) return Permission_Index is
begin
return Permission_Indexes.Get_Permission_Index (Name);
end Get_Permission_Index;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Permission_Indexes.Get_Last_Permission_Index;
end Get_Last_Permission_Index;
-- ------------------------------
-- Add the permission name and allocate a unique permission index.
-- ------------------------------
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
begin
Permission_Indexes.Add_Permission (Name, Index);
end Add_Permission;
package body Definition is
P : Permission_Index;
function Permission return Permission_Index is
begin
return P;
end Permission;
begin
Add_Permission (Name => Name, Index => P);
end Definition;
end Security.Permissions;
|
Rename Permission_ACL into Definition
|
Rename Permission_ACL into Definition
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
cd2e8547f1584d5e10874a758fe787bb53dc989f
|
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 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 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 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
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Permission is abstract tagged limited null record;
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
private
use Util.Strings;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
end Security.Permissions;
|
Remove the operation and types which are now in Security.Policy
|
Remove the operation and types which are now in Security.Policy
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
770131eaa728c72870aac53299ca0d08e682e697
|
src/util-properties-json.adb
|
src/util-properties-json.adb
|
-----------------------------------------------------------------------
-- util-properties-json -- read json files into properties
-- Copyright (C) 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.JSON;
with Util.Stacks;
with Util.Beans.Objects;
package body Util.Properties.JSON is
type Natural_Access is access all Natural;
package Length_Stack is new Util.Stacks (Element_Type => Natural,
Element_Type_Access => Natural_Access);
type Parser is abstract limited new Util.Serialize.IO.Reader with record
Base_Name : Ada.Strings.Unbounded.Unbounded_String;
Lengths : Length_Stack.Stack;
Separator : Ada.Strings.Unbounded.Unbounded_String;
Separator_Length : Natural;
end record;
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String);
overriding
procedure Start_Array (Handler : in out Parser;
Name : in String);
overriding
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural);
-- 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);
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String) is
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Append (Handler.Base_Name, Name);
Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator);
Length_Stack.Push (Handler.Lengths);
Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length;
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name);
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Delete (Handler.Base_Name,
Len - Name'Length - Handler.Separator_Length + 1, Len);
end if;
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Parser;
Name : in String) is
begin
Handler.Start_Object (Name);
-- Util.Serialize.IO.JSON.Parser (Handler).Start_Array (Name);
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural) is
begin
Parser'Class (Handler).Set_Member ("length", Util.Beans.Objects.To_Object (Count));
Handler.Finish_Object (Name);
-- Util.Serialize.IO.JSON.Parser (Handler).Finish_Array (Name, Count);
end Finish_Array;
-- 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) is
begin
null;
end Error;
-- -----------------------
-- Parse the JSON content and put the flattened content in the property manager.
-- -----------------------
procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class;
Content : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with record
Manager : access Util.Properties.Manager'Class;
end record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
R : Util.Serialize.IO.JSON.Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Manager := Manager'Access;
R.Parse_String (Content, P);
if R.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Parse_JSON;
-- -----------------------
-- Read the JSON file into the property manager.
-- The JSON content is flatten into Flatten the JSON content and add the properties.
-- -----------------------
procedure Read_JSON (Manager : in out Util.Properties.Manager'Class;
Path : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with record
Manager : access Util.Properties.Manager'Class;
end record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
R : Util.Serialize.IO.JSON.Parser;
begin
P.Manager := Manager'Access;
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
R.Parse (Path, P);
if R.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Read_JSON;
end Util.Properties.JSON;
|
-----------------------------------------------------------------------
-- util-properties-json -- read json files into properties
-- Copyright (C) 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.JSON;
with Util.Stacks;
with Util.Log;
with Util.Beans.Objects;
package body Util.Properties.JSON is
type Natural_Access is access all Natural;
package Length_Stack is new Util.Stacks (Element_Type => Natural,
Element_Type_Access => Natural_Access);
type Parser is abstract limited new Util.Serialize.IO.Reader with record
Base_Name : Ada.Strings.Unbounded.Unbounded_String;
Lengths : Length_Stack.Stack;
Separator : Ada.Strings.Unbounded.Unbounded_String;
Separator_Length : Natural;
end record;
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String;
Logger : in out Util.Log.Logging'Class);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String;
Logger : in out Util.Log.Logging'Class);
overriding
procedure Start_Array (Handler : in out Parser;
Name : in String;
Logger : in out Util.Log.Logging'Class);
overriding
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class);
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Append (Handler.Base_Name, Name);
Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator);
Length_Stack.Push (Handler.Lengths);
Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length;
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name);
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Delete (Handler.Base_Name,
Len - Name'Length - Handler.Separator_Length + 1, Len);
end if;
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Parser;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
begin
Handler.Start_Object (Name, Logger);
-- Util.Serialize.IO.JSON.Parser (Handler).Start_Array (Name);
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) is
begin
Parser'Class (Handler).Set_Member ("length", Util.Beans.Objects.To_Object (Count), Logger);
Handler.Finish_Object (Name, Logger);
-- Util.Serialize.IO.JSON.Parser (Handler).Finish_Array (Name, Count);
end Finish_Array;
-- -----------------------
-- Parse the JSON content and put the flattened content in the property manager.
-- -----------------------
procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class;
Content : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with record
Manager : access Util.Properties.Manager'Class;
end record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
R : Util.Serialize.IO.JSON.Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Manager := Manager'Access;
R.Parse_String (Content, P);
if R.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Parse_JSON;
-- -----------------------
-- Read the JSON file into the property manager.
-- The JSON content is flatten into Flatten the JSON content and add the properties.
-- -----------------------
procedure Read_JSON (Manager : in out Util.Properties.Manager'Class;
Path : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with record
Manager : access Util.Properties.Manager'Class;
end record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
R : Util.Serialize.IO.JSON.Parser;
begin
P.Manager := Manager'Access;
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
R.Parse (Path, P);
if R.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Read_JSON;
end Util.Properties.JSON;
|
Update the Parser operations to add a Logger parameter to report errors
|
Update the Parser operations to add a Logger parameter to report errors
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9e58cc3cad52bca160619c44bd64bdbd2ae8966c
|
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;
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_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;
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;
|
Update the post URI to save it in DB
|
Update the post URI to save it in DB
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
458c1019318afb31b6735526e2c0060728d88acb
|
src/base/beans/util-beans-objects-hash.adb
|
src/base/beans/util-beans-objects-hash.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-hash -- Hash on an object
-- Copyright (C) 2010, 2011, 2017, 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.Strings.Wide_Wide_Hash;
with Ada.Unchecked_Conversion;
with Interfaces;
with Util.Beans.Basic;
function Util.Beans.Objects.Hash (Key : in Object) return Ada.Containers.Hash_Type is
use Ada.Containers;
use Ada.Strings;
use Interfaces;
use Util.Beans.Basic;
type Unsigned_32_Array is array (Natural range <>) of Unsigned_32;
subtype U32_For_Float is Unsigned_32_Array (1 .. Long_Long_Float'Size / 32);
subtype U32_For_Duration is Unsigned_32_Array (1 .. Duration'Size / 32);
subtype U32_For_Long is Unsigned_32_Array (1 .. Long_Long_Integer'Size / 32);
subtype U32_For_Access is Unsigned_32_Array (1 .. Readonly_Bean_Access'Size / 32);
-- Hash the integer and floats using 32-bit values.
function To_U32_For_Long is new Ada.Unchecked_Conversion (Source => Long_Long_Integer,
Target => U32_For_Long);
-- Likewise for floats.
function To_U32_For_Float is new Ada.Unchecked_Conversion (Source => Long_Long_Float,
Target => U32_For_Float);
-- Likewise for duration.
function To_U32_For_Duration is new Ada.Unchecked_Conversion (Source => Duration,
Target => U32_For_Duration);
-- Likewise for the bean pointer
function To_U32_For_Access is new Ada.Unchecked_Conversion (Source => Readonly_Bean_Access,
Target => U32_For_Access);
begin
case Key.V.Of_Type is
when TYPE_NULL =>
return 0;
when TYPE_BOOLEAN =>
if Key.V.Bool_Value then
return 1;
else
return 2;
end if;
when TYPE_INTEGER =>
declare
U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Int_Value);
Val : Unsigned_32 := U32 (U32'First);
begin
for I in U32'First + 1 .. U32'Last loop
Val := Val xor U32 (I);
end loop;
return Hash_Type (Val);
end;
when TYPE_FLOAT =>
declare
U32 : constant U32_For_Float := To_U32_For_Float (Key.V.Float_Value);
Val : Unsigned_32 := U32 (U32'First);
begin
for I in U32'First + 1 .. U32'Last loop
Val := Val xor U32 (I);
end loop;
return Hash_Type (Val);
end;
when TYPE_STRING =>
if Key.V.String_Proxy = null then
return 0;
else
return Hash (Key.V.String_Proxy.Value);
end if;
when TYPE_TIME =>
declare
U32 : constant U32_For_Duration := To_U32_For_Duration (Key.V.Time_Value);
Val : Unsigned_32 := U32 (U32'First);
begin
for I in U32'First + 1 .. U32'Last loop
Val := Val xor U32 (I);
end loop;
return Hash_Type (Val);
end;
when TYPE_WIDE_STRING =>
if Key.V.Wide_Proxy = null then
return 0;
else
return Wide_Wide_Hash (Key.V.Wide_Proxy.Value);
end if;
when TYPE_BEAN =>
if Key.V.Proxy = null or else Bean_Proxy (Key.V.Proxy.all).Bean = null then
return 0;
end if;
declare
U32 : constant U32_For_Access
:= To_U32_For_Access (Bean_Proxy (Key.V.Proxy.all).Bean.all'Access);
Val : Unsigned_32 := U32 (U32'First);
-- The loop is not executed if pointers are 32-bit wide.
pragma Warnings (Off);
begin
for I in U32'First + 1 .. U32'Last loop
Val := Val xor U32 (I);
end loop;
return Hash_Type (Val);
end;
when TYPE_RECORD =>
return 0;
when TYPE_ARRAY =>
declare
Result : Unsigned_32 := 0;
begin
for Object of Key.V.Array_Proxy.Values loop
Result := Result xor Unsigned_32 (Hash (Object));
end loop;
return Hash_Type (Result);
end;
end case;
end Util.Beans.Objects.Hash;
|
-----------------------------------------------------------------------
-- util-beans-objects-hash -- Hash on an object
-- Copyright (C) 2010, 2011, 2017, 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.Strings.Wide_Wide_Hash;
with Ada.Unchecked_Conversion;
with Interfaces;
with Util.Beans.Basic;
function Util.Beans.Objects.Hash (Key : in Object) return Ada.Containers.Hash_Type is
use Ada.Containers;
use Ada.Strings;
use Interfaces;
use Util.Beans.Basic;
type Unsigned_32_Array is array (Natural range <>) of Unsigned_32;
subtype U32_For_Float is Unsigned_32_Array (1 .. Long_Long_Float'Size / 32);
subtype U32_For_Duration is Unsigned_32_Array (1 .. Duration'Size / 32);
subtype U32_For_Long is Unsigned_32_Array (1 .. Long_Long_Integer'Size / 32);
subtype U32_For_Access is Unsigned_32_Array (1 .. Readonly_Bean_Access'Size / 32);
-- Hash the integer and floats using 32-bit values.
function To_U32_For_Long is new Ada.Unchecked_Conversion (Source => Long_Long_Integer,
Target => U32_For_Long);
-- Likewise for floats.
function To_U32_For_Float is new Ada.Unchecked_Conversion (Source => Long_Long_Float,
Target => U32_For_Float);
-- Likewise for duration.
function To_U32_For_Duration is new Ada.Unchecked_Conversion (Source => Duration,
Target => U32_For_Duration);
-- Likewise for the bean pointer
function To_U32_For_Access is new Ada.Unchecked_Conversion (Source => Readonly_Bean_Access,
Target => U32_For_Access);
begin
case Key.V.Of_Type is
when TYPE_NULL =>
return 0;
when TYPE_BOOLEAN =>
if Key.V.Bool_Value then
return 1;
else
return 2;
end if;
when TYPE_INTEGER =>
declare
U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Int_Value);
Val : Unsigned_32 := U32 (U32'First);
begin
for I in U32'First + 1 .. U32'Last loop
Val := Val xor U32 (I);
end loop;
return Hash_Type (Val);
end;
when TYPE_FLOAT =>
declare
U32 : constant U32_For_Float := To_U32_For_Float (Key.V.Float_Value);
Val : Unsigned_32 := U32 (U32'First);
begin
for I in U32'First + 1 .. U32'Last loop
Val := Val xor U32 (I);
end loop;
return Hash_Type (Val);
end;
when TYPE_STRING =>
if Key.V.String_Proxy = null then
return 0;
else
return Hash (Key.V.String_Proxy.Value);
end if;
when TYPE_TIME =>
declare
U32 : constant U32_For_Duration := To_U32_For_Duration (Key.V.Time_Value);
Val : Unsigned_32 := U32 (U32'First);
begin
for I in U32'First + 1 .. U32'Last loop
Val := Val xor U32 (I);
end loop;
return Hash_Type (Val);
end;
when TYPE_WIDE_STRING =>
if Key.V.Wide_Proxy = null then
return 0;
else
return Wide_Wide_Hash (Key.V.Wide_Proxy.Value);
end if;
when TYPE_BEAN =>
if Key.V.Proxy = null or else Bean_Proxy (Key.V.Proxy.all).Bean = null then
return 0;
end if;
declare
U32 : constant U32_For_Access
:= To_U32_For_Access (Bean_Proxy (Key.V.Proxy.all).Bean.all'Access);
Val : Unsigned_32 := U32 (U32'First);
-- The loop is not executed if pointers are 32-bit wide.
pragma Warnings (Off);
begin
for I in U32'First + 1 .. U32'Last loop
Val := Val xor U32 (I);
end loop;
return Hash_Type (Val);
end;
when TYPE_RECORD =>
return 0;
when TYPE_ARRAY =>
declare
Result : Unsigned_32 := 0;
begin
for Object of Key.V.Array_Proxy.Values loop
Result := Result xor Unsigned_32 (Hash (Object));
end loop;
return Hash_Type (Result);
end;
when TYPE_BLOB =>
declare
Result : Unsigned_32 := 0;
Blob : Util.Blobs.Blob_Ref := Key.V.Blob_Proxy.Blob;
begin
if not Blob.Is_Null then
for Val of Blob.Value.Data loop
Result := Result xor Unsigned_32 (Val);
end loop;
end if;
return Hash_Type (Result);
end;
end case;
end Util.Beans.Objects.Hash;
|
Add support for TYPE_BLOB
|
Add support for TYPE_BLOB
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
58ed772731764e6c69ea82df1fd5308699febc91
|
src/base/beans/util-beans-objects-maps.ads
|
src/base/beans/util-beans-objects-maps.ads
|
-----------------------------------------------------------------------
-- util-beans-objects-maps -- Object maps
-- Copyright (C) 2010, 2011, 2012, 2017, 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.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Beans.Basic;
-- == Object maps ==
-- The `Util.Beans.Objects.Maps` package provides a map of objects with a `String`
-- as index. This allows to associated names to objects.
-- To create an instance of the map, it is possible to use the `Create` function
-- as follows:
--
-- Person : Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Create;
--
-- Then, it becomes possible to populate the map with objects by using
-- the `Set_Value` procedure as follows:
--
-- Util.Beans.Objects.Set_Value (Person, "name", To_Object (Name));
-- Util.Beans.Objects.Set_Value (Person, "last_name", To_Object (Last_Name));
-- Util.Beans.Objects.Set_Value (Person, "age", To_Object (Age));
--
-- Getting a value from the map is done by using the `Get_Value` function:
--
-- Name : Util.Beans.Objects.Object := Get_Value (Person, "name");
--
-- It is also possible to iterate over the values of the map by using
-- the `Iterate` procedure.
package Util.Beans.Objects.Maps is
package Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Object,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
subtype Cursor is Maps.Cursor;
subtype Map is Maps.Map;
-- Make all the Maps operations available (a kind of 'use Maps' for anybody).
function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length;
function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty;
procedure Clear (Container : in out Map) renames Maps.Clear;
function Key (Position : Cursor) return String renames Maps.Key;
procedure Include (Container : in out Map;
Key : in String;
New_Item : in Object) renames Maps.Include;
procedure Query_Element (Position : in Cursor;
Process : not null access procedure (Key : String;
Element : Object))
renames Maps.Query_Element;
function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element;
function Element (Position : Cursor) return Object renames Maps.Element;
procedure Next (Position : in out Cursor) renames Maps.Next;
function Next (Position : Cursor) return Cursor renames Maps.Next;
function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : Cursor; Right : String) return Boolean
renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : String; Right : Cursor) return Boolean
renames Maps.Equivalent_Keys;
function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map
renames Maps.Copy;
-- ------------------------------
-- Map Bean
-- ------------------------------
-- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface.
-- This allows the map to be available and accessed from an Object instance.
type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private;
type Map_Bean_Access is access all Map_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Map_Bean;
Name : in String) return Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
procedure Set_Value (From : in out Map_Bean;
Name : in String;
Value : in Object);
-- Create an object that contains a <tt>Map_Bean</tt> instance.
function Create return Object;
-- Iterate over the members of the map.
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object));
private
type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record;
end Util.Beans.Objects.Maps;
|
-----------------------------------------------------------------------
-- util-beans-objects-maps -- Object maps
-- Copyright (C) 2010, 2011, 2012, 2017, 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.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Beans.Basic;
with Util.Beans.Objects.Iterators;
-- == Object maps ==
-- The `Util.Beans.Objects.Maps` package provides a map of objects with a `String`
-- as key. This allows to associated names to objects.
-- To create an instance of the map, it is possible to use the `Create` function
-- as follows:
--
-- with Util.Beans.Objects.Maps;
-- ...
-- Person : Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Create;
--
-- Then, it becomes possible to populate the map with objects by using
-- the `Set_Value` procedure as follows:
--
-- Util.Beans.Objects.Set_Value (Person, "name",
-- To_Object (Name));
-- Util.Beans.Objects.Set_Value (Person, "last_name",
-- To_Object (Last_Name));
-- Util.Beans.Objects.Set_Value (Person, "age",
-- To_Object (Age));
--
-- Getting a value from the map is done by using the `Get_Value` function:
--
-- Name : Util.Beans.Objects.Object := Get_Value (Person, "name");
--
-- It is also possible to iterate over the values of the map by using
-- the `Iterate` procedure or by using the iterator support provided by
-- the `Util.Beans.Objects.Iterators` package.
package Util.Beans.Objects.Maps is
subtype Iterator_Bean is Util.Beans.Objects.Iterators.Iterator_Bean;
package Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Object,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
subtype Cursor is Maps.Cursor;
subtype Map is Maps.Map;
-- Make all the Maps operations available (a kind of 'use Maps' for anybody).
function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length;
function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty;
procedure Clear (Container : in out Map) renames Maps.Clear;
function Key (Position : Cursor) return String renames Maps.Key;
procedure Include (Container : in out Map;
Key : in String;
New_Item : in Object) renames Maps.Include;
procedure Query_Element (Position : in Cursor;
Process : not null access procedure (Key : String;
Element : Object))
renames Maps.Query_Element;
function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element;
function Element (Position : Cursor) return Object renames Maps.Element;
procedure Next (Position : in out Cursor) renames Maps.Next;
function Next (Position : Cursor) return Cursor renames Maps.Next;
function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : Cursor; Right : String) return Boolean
renames Maps.Equivalent_Keys;
function Equivalent_Keys (Left : String; Right : Cursor) return Boolean
renames Maps.Equivalent_Keys;
function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map
renames Maps.Copy;
-- ------------------------------
-- Map Bean
-- ------------------------------
-- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface.
-- This allows the map to be available and accessed from an Object instance.
type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean and Iterator_Bean with private;
type Map_Bean_Access is access all Map_Bean'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 Map_Bean;
Name : in String) return Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Map_Bean;
Name : in String;
Value : in Object);
-- Get an iterator to iterate starting with the first element.
overriding
function First (From : in Map_Bean) return Iterators.Proxy_Iterator_Access;
-- Get an iterator to iterate starting with the last element.
overriding
function Last (From : in Map_Bean) return Iterators.Proxy_Iterator_Access;
-- Create an object that contains a <tt>Map_Bean</tt> instance.
function Create return Object;
-- Iterate over the members of the map.
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object));
private
type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean
and Iterator_Bean with null record;
type Map_Iterator is new Iterators.Proxy_Map_Iterator with record
Pos : Cursor;
end record;
type Map_Iterator_Access is access all Map_Iterator;
overriding
function Has_Element (Iter : in Map_Iterator) return Boolean;
overriding
procedure Next (Iter : in out Map_Iterator);
overriding
procedure Previous (Iter : in out Map_Iterator);
overriding
function Element (Iter : in Map_Iterator) return Object;
overriding
function Key (Iter : in Map_Iterator) return String;
end Util.Beans.Objects.Maps;
|
Add some documentation and implement the Iterator_Bean
|
Add some documentation and implement the Iterator_Bean
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8d9ba7b09f77ebed9513d463eac10c7f4270e5e4
|
mat/src/mat-targets.adb
|
mat/src/mat-targets.adb
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Targets.Readers;
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Set the console instance.
-- ------------------------------
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access) is
begin
Target.Console := Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Targets.Readers.Initialize (Target => Target,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Process : out Target_Process_Type_Access) is
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create;
Target.Processes.Insert (Pid, Process);
end if;
if Target.Current = null then
Target.Current := Process;
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Targets.Readers;
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Set the console instance.
-- ------------------------------
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access) is
begin
Target.Console := Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Targets.Readers.Initialize (Target => Target,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access) is
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Process.Path := Path;
Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create;
Target.Processes.Insert (Pid, Process);
Target.Console.Notice (MAT.Consoles.N_PID_INFO,
"Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created");
Target.Console.Notice (MAT.Consoles.N_PATH_INFO,
"Path " & Ada.Strings.Unbounded.To_String (Path));
end if;
if Target.Current = null then
Target.Current := Process;
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
end MAT.Targets;
|
Store the process path and report the created process with its path
|
Store the process path and report the created process with its path
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
e62a74e34957506bce1dc653b6b46aa3792d3345
|
mat/src/mat-commands.ads
|
mat/src/mat-commands.ads
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Sockets;
with MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- 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 recieved.
Load_Symbols : Boolean := True;
-- Enable the graphical mode (when available).
Graphical : Boolean := False;
-- Define the server listening address.
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
procedure Interactive (Target : in out MAT.Targets.Target_Type'Class);
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class;
Options : in out Options_Type);
-- Initialize the process targets by loading the MAT files.
procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class);
-- 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;
-- Symbol command.
-- Load the symbols from the binary file.
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
end MAT.Commands;
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Sockets;
with MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
procedure Interactive (Target : in out MAT.Targets.Target_Type'Class);
-- Initialize the process targets by loading the MAT files.
procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class);
-- 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;
-- Symbol command.
-- Load the symbols from the binary file.
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
end MAT.Commands;
|
Move the Initialize_Options to the MAT.Targets package
|
Move the Initialize_Options to the MAT.Targets package
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ebe9e400ee1938a1bd27bb3d5a7fd244f3bc9a96
|
awa/plugins/awa-tags/src/awa-tags-beans.adb
|
awa/plugins/awa-tags/src/awa-tags-beans.adb
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
package body AWA.Tags.Beans is
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a tag on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the tags associated with the given database identifier.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Set the list of tags to add.
-- ------------------------------
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Added := Tags;
end Set_Added;
-- ------------------------------
-- Set the list of tags to remove.
-- ------------------------------
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Deleted := Tags;
end Set_Deleted;
-- ------------------------------
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
-- ------------------------------
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier) is
use type AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type);
Service : AWA.Tags.Modules.Tag_Module_Access := From.Module;
begin
if Service = null then
Service := AWA.Tags.Modules.Get_Tag_Module;
end if;
Service.Update_Tags (Id => For_Entity_Id,
Entity_Type => Entity_Type,
Permission => Ada.Strings.Unbounded.To_String (From.Permission),
Added => From.Added,
Deleted => From.Deleted);
end Update_Tags;
-- ------------------------------
-- Create the tag list bean instance.
-- ------------------------------
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_List_Bean_Access := new Tag_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Search the tags that match the search string.
-- ------------------------------
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_Search);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("search", Search & "%");
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Search_Tags;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "search" then
declare
Session : constant ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Search_Tags (Session, Util.Beans.Objects.To_String (Value));
end;
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Create the tag search bean instance.
-- ------------------------------
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Search_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
declare
Session : ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Load_Tags (Session);
end;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of tags.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All);
Query.Bind_Param ("entity_type", Kind);
AWA.Tags.Models.List (Into, Session, Query);
end Load_Tags;
-- ------------------------------
-- Create the tag info list bean instance.
-- ------------------------------
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Info_List_Bean;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Entity_Tag_Maps.Element (Pos);
else
return null;
end if;
end Get_Tags;
-- ------------------------------
-- Load the list of tags associated with a list of entities.
-- ------------------------------
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector) is
Query : ADO.Queries.Context;
Kind : ADO.Entity_Type;
begin
if List.Is_Empty then
return;
end if;
Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type);
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All);
Query.Bind_Param ("entity_id_list", ADO.Utils.To_Parameter_List (List));
Query.Bind_Param ("entity_type", Kind);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Id : ADO.Identifier;
List : Util.Beans.Lists.Strings.List_Bean_Access;
Pos : Entity_Tag_Maps.Cursor;
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Id := Stmt.Get_Identifier (0);
Pos := Into.Tags.Find (Id);
if not Entity_Tag_Maps.Has_Element (Pos) then
List := new Util.Beans.Lists.Strings.List_Bean;
Into.Tags.Insert (Id, List);
else
List := Entity_Tag_Maps.Element (Pos);
end if;
List.List.Append (Stmt.Get_String (1));
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
procedure Clear (List : in out Entity_Tag_Map) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class,
Name => Util.Beans.Lists.Strings.List_Bean_Access);
Pos : Entity_Tag_Maps.Cursor;
Tags : Util.Beans.Lists.Strings.List_Bean_Access;
begin
loop
Pos := List.Tags.First;
exit when not Entity_Tag_Maps.Has_Element (Pos);
Tags := Entity_Tag_Maps.Element (Pos);
List.Tags.Delete (Pos);
Free (Tags);
end loop;
end Clear;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
overriding
procedure Finalize (List : in out Entity_Tag_Map) is
begin
List.Clear;
end Finalize;
end AWA.Tags.Beans;
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
package body AWA.Tags.Beans is
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a tag on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the tags associated with the given database identifier.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Set the list of tags to add.
-- ------------------------------
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Added := Tags;
end Set_Added;
-- ------------------------------
-- Set the list of tags to remove.
-- ------------------------------
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Deleted := Tags;
end Set_Deleted;
-- ------------------------------
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
-- ------------------------------
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier) is
use type AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type);
Service : AWA.Tags.Modules.Tag_Module_Access := From.Module;
begin
if Service = null then
Service := AWA.Tags.Modules.Get_Tag_Module;
end if;
Service.Update_Tags (Id => For_Entity_Id,
Entity_Type => Entity_Type,
Permission => Ada.Strings.Unbounded.To_String (From.Permission),
Added => From.Added,
Deleted => From.Deleted);
end Update_Tags;
-- ------------------------------
-- Create the tag list bean instance.
-- ------------------------------
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_List_Bean_Access := new Tag_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Search the tags that match the search string.
-- ------------------------------
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_Search);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("search", Search & "%");
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Search_Tags;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "search" then
declare
Session : constant ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Search_Tags (Session, Util.Beans.Objects.To_String (Value));
end;
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Create the tag search bean instance.
-- ------------------------------
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Search_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
declare
Session : ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Load_Tags (Session);
end;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of tags.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All);
Query.Bind_Param ("entity_type", Kind);
AWA.Tags.Models.List (Into, Session, Query);
end Load_Tags;
-- ------------------------------
-- Create the tag info list bean instance.
-- ------------------------------
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Info_List_Bean;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Entity_Tag_Maps.Element (Pos);
else
return null;
end if;
end Get_Tags;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Util.Beans.Objects.To_Object (Value => Entity_Tag_Maps.Element (Pos).all'Access,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Tags;
-- ------------------------------
-- Load the list of tags associated with a list of entities.
-- ------------------------------
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector) is
Query : ADO.Queries.Context;
Kind : ADO.Entity_Type;
begin
Into.Clear;
if List.Is_Empty then
return;
end if;
Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type);
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_For_Entities);
Query.Bind_Param ("entity_id_list", List);
Query.Bind_Param ("entity_type", Kind);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Id : ADO.Identifier;
List : Util.Beans.Lists.Strings.List_Bean_Access;
Pos : Entity_Tag_Maps.Cursor;
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Id := Stmt.Get_Identifier (0);
Pos := Into.Tags.Find (Id);
if not Entity_Tag_Maps.Has_Element (Pos) then
List := new Util.Beans.Lists.Strings.List_Bean;
Into.Tags.Insert (Id, List);
else
List := Entity_Tag_Maps.Element (Pos);
end if;
List.List.Append (Stmt.Get_String (1));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
procedure Clear (List : in out Entity_Tag_Map) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class,
Name => Util.Beans.Lists.Strings.List_Bean_Access);
Pos : Entity_Tag_Maps.Cursor;
Tags : Util.Beans.Lists.Strings.List_Bean_Access;
begin
loop
Pos := List.Tags.First;
exit when not Entity_Tag_Maps.Has_Element (Pos);
Tags := Entity_Tag_Maps.Element (Pos);
List.Tags.Delete (Pos);
Free (Tags);
end loop;
end Clear;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
overriding
procedure Finalize (List : in out Entity_Tag_Map) is
begin
List.Clear;
end Finalize;
end AWA.Tags.Beans;
|
Implement the new Get_Tags operation Fix Load_Tags to use the correct query, bind the list of identifiers to search, and collect the result
|
Implement the new Get_Tags operation
Fix Load_Tags to use the correct query, bind the list of identifiers
to search, and collect the result
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6b9c55397ffa9f8715deee49cba1e73506f0248f
|
demo/texture.adb
|
demo/texture.adb
|
-- Simple Lumen demo/test program, using earliest incomplete library.
with Ada.Command_Line;
with System.Address_To_Access_Conversions;
with Lumen.Events.Animate;
with Lumen.Image;
with Lumen.Window;
with GL;
with GLU;
procedure Texture is
---------------------------------------------------------------------------
-- Rotation wraps around at this point, in degrees
Max_Rotation : constant := 359;
-- Traditional cinema framrate, in frames per second
Framerate : constant := 24;
---------------------------------------------------------------------------
Win : Lumen.Window.Handle;
Direct : Boolean := True;
Event : Lumen.Events.Event_Data;
Wide : Natural; -- no longer have default values since they're now set by the image size
High : Natural;
Rotation : Natural := 0;
Image : Lumen.Image.Descriptor;
Img_Wide : GL.glFloat;
Img_High : GL.glFloat;
Tx_Name : aliased GL.GLuint;
---------------------------------------------------------------------------
Program_Exit : exception;
---------------------------------------------------------------------------
-- Create a texture and bind a 2D image to it
procedure Create_Texture is
use GL;
use GLU;
package GLB is new System.Address_To_Access_Conversions (GLubyte);
IP : GLpointer;
begin -- Create_Texture
-- Allocate a texture name
glGenTextures (1, Tx_Name'Unchecked_Access);
-- Bind texture operations to the newly-created texture name
glBindTexture (GL_TEXTURE_2D, Tx_Name);
-- Select modulate to mix texture with color for shading
glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-- Wrap textures at both edges
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
-- How the texture behaves when minified and magnified
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-- Create a pointer to the image. This sort of horror show is going to
-- be disappearing once Lumen includes its own OpenGL bindings.
IP := GLB.To_Pointer (Image.Values (0, 0)'Address).all'Unchecked_Access;
-- Build our texture from the image we loaded earlier
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0,
GL_RGBA, GL_UNSIGNED_BYTE, IP);
end Create_Texture;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
use GL;
use GLU;
Aspect : GLdouble;
begin -- Set_View
-- Viewport dimensions
glViewport (0, 0, GLsizei (W), GLsizei (H));
-- Size of rectangle upon which image is mapped
if Wide > High then
Img_Wide := glFloat (1.5);
Img_High := glFloat (1.5) * glFloat (Float (High) / Float (Wide));
else
Img_Wide := glFloat (1.5) * glFloat (Float (Wide) / Float (High));
Img_High := glFloat (1.5);
end if;
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
glMatrixMode (GL_PROJECTION);
glLoadIdentity;
-- Set up a 3D viewing frustum, which is basically a truncated pyramid
-- in which the scene takes place. Roughly, the narrow end is your
-- screen, and the wide end is 10 units away from the camera.
if W <= H then
Aspect := GLdouble (H) / GLdouble (W);
glFrustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0);
else
Aspect := GLdouble (W) / GLdouble (H);
glFrustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0);
end if;
end Set_View;
---------------------------------------------------------------------------
-- Draw our scene
procedure Draw is
use GL;
begin -- Draw
-- Set a black background
glClearColor (0.8, 0.8, 0.8, 1.0);
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
-- Draw a texture-mapped rectangle with the same aspect ratio as the
-- original image
glBegin (GL_POLYGON);
begin
glTexCoord3f (0.0, 1.0, 0.0);
glVertex3f (-Img_Wide, -Img_High, 0.0);
glTexCoord3f (0.0, 0.0, 0.0);
glVertex3f (-Img_Wide, Img_High, 0.0);
glTexCoord3f (1.0, 0.0, 0.0);
glVertex3f ( Img_Wide, Img_High, 0.0);
glTexCoord3f (1.0, 1.0, 0.0);
glVertex3f ( Img_Wide, -Img_High, 0.0);
end;
glEnd;
-- Rotate the object around the Y and Z axes by the current amount, to
-- give a "tumbling" effect.
glMatrixMode (GL_MODELVIEW);
glLoadIdentity;
glTranslated (0.0, 0.0, -4.0);
glRotated (GLdouble (Rotation), 0.0, 1.0, 0.0);
glRotated (GLdouble (Rotation), 0.0, 0.0, 1.0);
glFlush;
-- Now show it
Lumen.Window.Swap (Win);
end Draw;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses and close-window events
procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Quit_Handler
raise Program_Exit;
end Quit_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Exposed events
procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Expose_Handler
Draw;
end Expose_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Resized events
procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Resize_Handler
Wide := Event.Resize_Data.Width;
High := Event.Resize_Data.Height;
Set_View (Wide, High);
Draw;
end Resize_Handler;
---------------------------------------------------------------------------
-- Our draw-a-frame routine, should get called FPS times a second
procedure New_Frame (Frame_Delta : in Duration) is
begin -- New_Frame
if Rotation >= Max_Rotation then
Rotation := 0;
else
Rotation := Rotation + 1;
end if;
Draw;
end New_Frame;
---------------------------------------------------------------------------
begin -- Texture
-- If we haven't been given an image to work with, just do nothing
if Ada.Command_Line.Argument_Count < 1 then
raise Program_Exit;
end if;
-- Read image and use it to size the window. This will suck if your image
-- is very large.
Image := Lumen.Image.From_File (Ada.Command_Line.Argument (1));
Wide := Image.Width;
High := Image.Height;
-- If the user provides a second argument, it means "no direct rendering"
-- for the OpenGL context
if Ada.Command_Line.Argument_Count > 1 then
Direct := False;
end if;
-- Create Lumen window, accepting most defaults; turn double buffering off
-- for simplicity
Lumen.Window.Create (Win, Name => "Spinning Picture Demo",
Width => Wide,
Height => High,
Direct => Direct,
Events => (Lumen.Window.Want_Key_Press => True,
Lumen.Window.Want_Exposure => True,
others => False));
-- Set up the viewport and scene parameters
Set_View (Wide, High);
-- Now create the texture and set up to use it
Create_Texture;
GL.glEnable (GL.GL_TEXTURE_2D);
GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name);
-- Enter the event loop
declare
use Lumen.Events;
begin
Animate.Select_Events (Win => Win,
Calls => (Key_Press => Quit_Handler'Unrestricted_Access,
Exposed => Expose_Handler'Unrestricted_Access,
Resized => Resize_Handler'Unrestricted_Access,
Close_Window => Quit_Handler'Unrestricted_Access,
others => No_Callback),
FPS => Framerate,
Frame => New_Frame'Unrestricted_Access);
end;
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Texture;
|
-- Simple Lumen demo/test program, using earliest incomplete library.
with Ada.Command_Line;
with System.Address_To_Access_Conversions;
with Lumen.Events.Animate;
with Lumen.Image;
with Lumen.Window;
with GL;
with GLU;
procedure Texture is
---------------------------------------------------------------------------
-- Rotation wraps around at this point, in degrees
Max_Rotation : constant := 359;
-- Traditional cinema framrate, in frames per second
Framerate : constant := 24;
---------------------------------------------------------------------------
Win : Lumen.Window.Handle;
Direct : Boolean := True;
Event : Lumen.Events.Event_Data;
Wide : Natural; -- no longer have default values since they're now set by the image size
High : Natural;
Rotation : Natural := 0;
Image : Lumen.Image.Descriptor;
Img_Wide : GL.glFloat;
Img_High : GL.glFloat;
Tx_Name : aliased GL.GLuint;
---------------------------------------------------------------------------
Program_Exit : exception;
---------------------------------------------------------------------------
-- Create a texture and bind a 2D image to it
procedure Create_Texture is
use GL;
use GLU;
package GLB is new System.Address_To_Access_Conversions (GLubyte);
IP : GLpointer;
begin -- Create_Texture
-- Allocate a texture name
glGenTextures (1, Tx_Name'Unchecked_Access);
-- Bind texture operations to the newly-created texture name
glBindTexture (GL_TEXTURE_2D, Tx_Name);
-- Select modulate to mix texture with color for shading
glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-- Wrap textures at both edges
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
-- How the texture behaves when minified and magnified
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-- Create a pointer to the image. This sort of horror show is going to
-- be disappearing once Lumen includes its own OpenGL bindings.
IP := GLB.To_Pointer (Image.Values.all'Address).all'Unchecked_Access;
-- Build our texture from the image we loaded earlier
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0,
GL_RGBA, GL_UNSIGNED_BYTE, IP);
end Create_Texture;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
use GL;
use GLU;
Aspect : GLdouble;
begin -- Set_View
-- Viewport dimensions
glViewport (0, 0, GLsizei (W), GLsizei (H));
-- Size of rectangle upon which image is mapped
if Wide > High then
Img_Wide := glFloat (1.5);
Img_High := glFloat (1.5) * glFloat (Float (High) / Float (Wide));
else
Img_Wide := glFloat (1.5) * glFloat (Float (Wide) / Float (High));
Img_High := glFloat (1.5);
end if;
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
glMatrixMode (GL_PROJECTION);
glLoadIdentity;
-- Set up a 3D viewing frustum, which is basically a truncated pyramid
-- in which the scene takes place. Roughly, the narrow end is your
-- screen, and the wide end is 10 units away from the camera.
if W <= H then
Aspect := GLdouble (H) / GLdouble (W);
glFrustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0);
else
Aspect := GLdouble (W) / GLdouble (H);
glFrustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0);
end if;
end Set_View;
---------------------------------------------------------------------------
-- Draw our scene
procedure Draw is
use GL;
begin -- Draw
-- Set a black background
glClearColor (0.8, 0.8, 0.8, 1.0);
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
-- Draw a texture-mapped rectangle with the same aspect ratio as the
-- original image
glBegin (GL_POLYGON);
begin
glTexCoord3f (0.0, 1.0, 0.0);
glVertex3f (-Img_Wide, -Img_High, 0.0);
glTexCoord3f (0.0, 0.0, 0.0);
glVertex3f (-Img_Wide, Img_High, 0.0);
glTexCoord3f (1.0, 0.0, 0.0);
glVertex3f ( Img_Wide, Img_High, 0.0);
glTexCoord3f (1.0, 1.0, 0.0);
glVertex3f ( Img_Wide, -Img_High, 0.0);
end;
glEnd;
-- Rotate the object around the Y and Z axes by the current amount, to
-- give a "tumbling" effect.
glMatrixMode (GL_MODELVIEW);
glLoadIdentity;
glTranslated (0.0, 0.0, -4.0);
glRotated (GLdouble (Rotation), 0.0, 1.0, 0.0);
glRotated (GLdouble (Rotation), 0.0, 0.0, 1.0);
glFlush;
-- Now show it
Lumen.Window.Swap (Win);
end Draw;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses and close-window events
procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Quit_Handler
raise Program_Exit;
end Quit_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Exposed events
procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Expose_Handler
Draw;
end Expose_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Resized events
procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Resize_Handler
Wide := Event.Resize_Data.Width;
High := Event.Resize_Data.Height;
Set_View (Wide, High);
Draw;
end Resize_Handler;
---------------------------------------------------------------------------
-- Our draw-a-frame routine, should get called FPS times a second
procedure New_Frame (Frame_Delta : in Duration) is
begin -- New_Frame
if Rotation >= Max_Rotation then
Rotation := 0;
else
Rotation := Rotation + 1;
end if;
Draw;
end New_Frame;
---------------------------------------------------------------------------
begin -- Texture
-- If we haven't been given an image to work with, just do nothing
if Ada.Command_Line.Argument_Count < 1 then
raise Program_Exit;
end if;
-- Read image and use it to size the window. This will suck if your image
-- is very large.
Image := Lumen.Image.From_File (Ada.Command_Line.Argument (1));
Wide := Image.Width;
High := Image.Height;
-- If the user provides a second argument, it means "no direct rendering"
-- for the OpenGL context
if Ada.Command_Line.Argument_Count > 1 then
Direct := False;
end if;
-- Create Lumen window, accepting most defaults; turn double buffering off
-- for simplicity
Lumen.Window.Create (Win, Name => "Spinning Picture Demo",
Width => Wide,
Height => High,
Direct => Direct,
Events => (Lumen.Window.Want_Key_Press => True,
Lumen.Window.Want_Exposure => True,
others => False));
-- Set up the viewport and scene parameters
Set_View (Wide, High);
-- Now create the texture and set up to use it
Create_Texture;
GL.glEnable (GL.GL_TEXTURE_2D);
GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name);
-- Enter the event loop
declare
use Lumen.Events;
begin
Animate.Select_Events (Win => Win,
Calls => (Key_Press => Quit_Handler'Unrestricted_Access,
Exposed => Expose_Handler'Unrestricted_Access,
Resized => Resize_Handler'Unrestricted_Access,
Close_Window => Quit_Handler'Unrestricted_Access,
others => No_Callback),
FPS => Framerate,
Frame => New_Frame'Unrestricted_Access);
end;
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Texture;
|
Use a more general address capture for the image buffer
|
Use a more general address capture for the image buffer
|
Ada
|
isc
|
darkestkhan/lumen2,darkestkhan/lumen
|
a3958ca762d888e30ec4f9a85519db7597624c48
|
awa/src/awa-permissions.ads
|
awa/src/awa-permissions.ads
|
-----------------------------------------------------------------------
-- awa-permissions -- Permissions module
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Permissions;
with Security.Policies;
with Util.Serialize.IO.XML;
with ADO;
-- == Introduction ==
-- The *AWA.Permissions* framework defines and controls the permissions used by an application
-- to verify and grant access to the data and application service. The framework provides a
-- set of services and API that helps an application in enforcing its specific permissions.
-- Permissions are verified by a permission controller which uses the service context to
-- have information about the user and other context. The framework allows to use different
-- kinds of permission controllers. The `Entity_Controller` is the default permission
-- controller which uses the database and an XML configuration to verify a permission.
--
-- === Declaration ===
-- To be used in the application, the first step is to declare the permission.
-- This is a static definition of the permission that will be used to ask to verify the
-- permission. The permission is given a unique name that will be used in configuration files:
--
-- package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
--
-- === Checking for a permission ===
-- A permission can be checked in Ada as well as in the presentation pages.
-- This is done by using the `Check` procedure and the permission definition. This operation
-- acts as a barrier: it does not return anything but returns normally if the permission is
-- granted. If the permission is denied, it raises the `NO_PERMISSION` exception.
--
-- Several `Check` operation exists. Some require not argument and some others need a context
-- such as some entity identifier to perform the check.
--
-- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
-- Entity => Blog_Id);
--
-- === Configuring a permission ===
-- The *AWA.Permissions* framework supports a simple permission model
-- The application configuration file must provide some information to help in checking the
-- permission. The permission name is referenced by the `name` XML entity. The `entity-type`
-- refers to the database entity (ie, the table) that the permission concerns.
-- The `sql` XML entity represents the SQL statement that must be used to verify the permission.
--
-- <entity-permission>
-- <name>blog-create-post</name>
-- <entity-type>blog</entity-type>
-- <description>Permission to create a new post.</description>
-- <sql>
-- SELECT acl.id FROM acl
-- WHERE acl.entity_type = :entity_type
-- AND acl.user_id = :user_id
-- AND acl.entity_id = :entity_id
-- </sql>
-- </entity-permission>
--
-- === Adding a permission ===
-- Adding a permission means to create an `ACL` database record that links a given database
-- entity to the user. This is done easily with the `Add_Permission` procedure:
--
-- AWA.Permissions.Services.Add_Permission (Session => DB,
-- User => User,
-- Entity => Blog);
--
-- == Data Model ==
-- @include Permission.hbm.xml
--
-- == Queries ==
-- @include permissions.xml
--
package AWA.Permissions is
NAME : constant String := "Entity-Policy";
-- Exception raised by the <b>Check</b> procedure if the user does not have
-- the permission.
NO_PERMISSION : exception;
type Permission_Type is (READ, WRITE);
type Entity_Permission is new Security.Permissions.Permission with private;
-- Verify that the permission represented by <b>Permission</b> is granted.
--
procedure Check (Permission : in Security.Permissions.Permission_Index);
-- Verify that the permission represented by <b>Permission</b> is granted to access the
-- database entity represented by <b>Entity</b>.
procedure Check (Permission : in Security.Permissions.Permission_Index;
Entity : in ADO.Identifier);
--
-- -- Get from the security context <b>Context</b> an identifier stored under the
-- -- name <b>Name</b>. Returns NO_IDENTIFIER if the security context does not define
-- -- such name or the value is not a valid identifier.
-- function Get_Context (Context : in Security.Contexts.Security_Context'Class;
-- Name : in String) return ADO.Identifier;
private
type Entity_Permission is new Security.Permissions.Permission with record
Entity : ADO.Identifier;
end record;
type Entity_Policy is new Security.Policies.Policy with null record;
type Entity_Policy_Access is access all Entity_Policy'Class;
-- Get the policy name.
overriding
function Get_Name (From : in Entity_Policy) return String;
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out Entity_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
overriding
procedure Finish_Config (Into : in out Entity_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
end AWA.Permissions;
|
-----------------------------------------------------------------------
-- awa-permissions -- Permissions module
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Permissions;
with Security.Policies;
with Util.Serialize.IO.XML;
with ADO;
-- == Introduction ==
-- The *AWA.Permissions* framework defines and controls the permissions used by an application
-- to verify and grant access to the data and application service. The framework provides a
-- set of services and API that helps an application in enforcing its specific permissions.
-- Permissions are verified by a permission controller which uses the service context to
-- have information about the user and other context. The framework allows to use different
-- kinds of permission controllers. The `Entity_Controller` is the default permission
-- controller which uses the database and an XML configuration to verify a permission.
--
-- === Declaration ===
-- To be used in the application, the first step is to declare the permission.
-- This is a static definition of the permission that will be used to ask to verify the
-- permission. The permission is given a unique name that will be used in configuration files:
--
-- package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
--
-- === Checking for a permission ===
-- A permission can be checked in Ada as well as in the presentation pages.
-- This is done by using the `Check` procedure and the permission definition. This operation
-- acts as a barrier: it does not return anything but returns normally if the permission is
-- granted. If the permission is denied, it raises the `NO_PERMISSION` exception.
--
-- Several `Check` operation exists. Some require not argument and some others need a context
-- such as some entity identifier to perform the check.
--
-- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
-- Entity => Blog_Id);
--
-- === Configuring a permission ===
-- The *AWA.Permissions* framework supports a simple permission model
-- The application configuration file must provide some information to help in checking the
-- permission. The permission name is referenced by the `name` XML entity. The `entity-type`
-- refers to the database entity (ie, the table) that the permission concerns.
-- The `sql` XML entity represents the SQL statement that must be used to verify the permission.
--
-- <entity-permission>
-- <name>blog-create-post</name>
-- <entity-type>blog</entity-type>
-- <description>Permission to create a new post.</description>
-- <sql>
-- SELECT acl.id FROM acl
-- WHERE acl.entity_type = :entity_type
-- AND acl.user_id = :user_id
-- AND acl.entity_id = :entity_id
-- </sql>
-- </entity-permission>
--
-- === Adding a permission ===
-- Adding a permission means to create an `ACL` database record that links a given database
-- entity to the user. This is done easily with the `Add_Permission` procedure:
--
-- AWA.Permissions.Services.Add_Permission (Session => DB,
-- User => User,
-- Entity => Blog);
--
-- == Data Model ==
-- @include Permission.hbm.xml
--
-- == Queries ==
-- @include permissions.xml
--
package AWA.Permissions is
NAME : constant String := "Entity-Policy";
-- Exception raised by the <b>Check</b> procedure if the user does not have
-- the permission.
NO_PERMISSION : exception;
type Permission_Type is (READ, WRITE);
type Entity_Permission is new Security.Permissions.Permission with private;
-- Verify that the permission represented by <b>Permission</b> is granted.
--
procedure Check (Permission : in Security.Permissions.Permission_Index);
-- Verify that the permission represented by <b>Permission</b> is granted to access the
-- database entity represented by <b>Entity</b>.
procedure Check (Permission : in Security.Permissions.Permission_Index;
Entity : in ADO.Identifier);
--
-- -- Get from the security context <b>Context</b> an identifier stored under the
-- -- name <b>Name</b>. Returns NO_IDENTIFIER if the security context does not define
-- -- such name or the value is not a valid identifier.
-- function Get_Context (Context : in Security.Contexts.Security_Context'Class;
-- Name : in String) return ADO.Identifier;
private
type Entity_Permission is new Security.Permissions.Permission with record
Entity : ADO.Identifier;
end record;
type Entity_Policy is new Security.Policies.Policy with null record;
type Entity_Policy_Access is access all Entity_Policy'Class;
-- Get the policy name.
overriding
function Get_Name (From : in Entity_Policy) return String;
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out Entity_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
end AWA.Permissions;
|
Remove Finish_Config
|
Remove Finish_Config
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b89258360e96546926e091fb127838714187cdee
|
samples/upload_server.adb
|
samples/upload_server.adb
|
-----------------------------------------------------------------------
-- upload_server -- Example of server with a servlet
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Server.Web;
with ASF.Servlets;
with Upload_Servlet;
with Util.Log.Loggers;
procedure Upload_Server is
Upload : aliased Upload_Servlet.Servlet;
App : aliased ASF.Servlets.Servlet_Registry;
WS : ASF.Server.Web.AWS_Container;
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Upload_Server");
begin
-- Register the servlets and filters
App.Add_Servlet (Name => "upload", Server => Upload'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "upload", Pattern => "*.html");
WS.Register_Application ("/upload", App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/upload/upload.html");
WS.Start;
delay 6000.0;
end Upload_Server;
|
-----------------------------------------------------------------------
-- upload_server -- Example of server with a servlet
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Server.Web;
with ASF.Servlets;
with Upload_Servlet;
with Util.Log.Loggers;
procedure Upload_Server is
Upload : aliased Upload_Servlet.Servlet;
App : aliased ASF.Servlets.Servlet_Registry;
WS : ASF.Server.Web.AWS_Container;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Upload_Server");
begin
-- Register the servlets and filters
App.Add_Servlet (Name => "upload", Server => Upload'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "upload", Pattern => "*.html");
WS.Register_Application ("/upload", App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/upload/upload.html");
WS.Start;
delay 6000.0;
end Upload_Server;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
26d90343a36285238e6aa896c128184329ad4d0a
|
src/gen-utils-gnat.ads
|
src/gen-utils-gnat.ads
|
-----------------------------------------------------------------------
-- gen-utils-gnat -- GNAT utilities
-- 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.Containers.Vectors;
with Util.Properties;
-- This package encapsulate a set of high level operations on top of the GNAT project
-- files. It uses the GNAT project reader which is packaged in the GNAT compiler (4.6.0).
-- A minimal supset of GNAT compiler was copied in <b>src/gnat</b> to ensure that a
-- compatible API is defined. The GNAT files stored in <b>src/gnat</b> are licensed
-- under the GNU General Public License.
package Gen.Utils.GNAT is
-- Directory which contains the GNAT project files installed on the system.
-- This is overriden by the configuration property 'generator.gnat.projects.dir'.
DEFAULT_GNAT_PROJECT_DIR : constant String := "/usr/lib/gnat";
type Project_Info is record
Path : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Project_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Project_Info);
-- Initialize the GNAT project runtime for reading the GNAT project tree.
-- Configure it according to the dynamo configuration properties.
procedure Initialize (Config : in Util.Properties.Manager'Class);
-- Read the GNAT project file identified by <b>Project_File_Name</b> and get
-- in <b>Project_List</b> an ordered list of absolute project paths used by
-- the root project.
procedure Read_GNAT_Project_List (Project_File_Name : in String;
Project_List : out Project_Info_Vectors.Vector);
end Gen.Utils.GNAT;
|
-----------------------------------------------------------------------
-- gen-utils-gnat -- GNAT utilities
-- 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.Containers.Vectors;
with Util.Properties;
-- This package encapsulate a set of high level operations on top of the GNAT project
-- files. It uses the GNAT project reader which is packaged in the GNAT compiler (4.6.0).
-- A minimal supset of GNAT compiler was copied in <b>src/gnat</b> to ensure that a
-- compatible API is defined. The GNAT files stored in <b>src/gnat</b> are licensed
-- under the GNU General Public License.
package Gen.Utils.GNAT is
-- Directory which contains the GNAT project files installed on the system.
-- This is overriden by the configuration property 'generator.gnat.projects.dir'.
DEFAULT_GNAT_PROJECT_DIR : constant String := "/usr/lib/gnat";
ADA_PROJECT_PATH_NAME : constant String := "ADA_PROJECT_PATH";
type Project_Info is record
Path : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Project_Info_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Project_Info);
-- Initialize the GNAT project runtime for reading the GNAT project tree.
-- Configure it according to the dynamo configuration properties.
procedure Initialize (Config : in Util.Properties.Manager'Class);
-- Read the GNAT project file identified by <b>Project_File_Name</b> and get
-- in <b>Project_List</b> an ordered list of absolute project paths used by
-- the root project.
procedure Read_GNAT_Project_List (Project_File_Name : in String;
Project_List : out Project_Info_Vectors.Vector);
end Gen.Utils.GNAT;
|
Declare the ADA_GNAT_PROJECT_NAME constant
|
Declare the ADA_GNAT_PROJECT_NAME constant
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
b49df52c326ede56b63a0750cf0405292fc3b65e
|
src/orka/interface/orka-rendering-fences.ads
|
src/orka/interface/orka-rendering-fences.ads
|
-- 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 GL.Fences;
generic
type Index_Type is mod <>;
Maximum_Wait : Duration := 0.010;
package Orka.Rendering.Fences is
type Buffer_Fence is tagged private;
type Fence_Status is (Not_Initialized, Signaled, Not_Signaled);
function Create_Buffer_Fence return Buffer_Fence;
procedure Prepare_Index (Object : in out Buffer_Fence; Status : out Fence_Status);
-- Perform a client wait sync for the fence corresponding to the
-- current index
procedure Advance_Index (Object : in out Buffer_Fence);
-- Set a fence for the corresponding index and then increment it
private
type Fence_Array is array (Index_Type) of GL.Fences.Fence;
type Buffer_Fence is tagged record
Fences : Fence_Array;
Index : Index_Type;
end record;
end Orka.Rendering.Fences;
|
-- 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 GL.Fences;
generic
type Index_Type is mod <>;
Maximum_Wait : Duration := 0.010;
package Orka.Rendering.Fences is
pragma Preelaborate;
type Buffer_Fence is tagged private;
type Fence_Status is (Not_Initialized, Signaled, Not_Signaled);
function Create_Buffer_Fence return Buffer_Fence;
procedure Prepare_Index (Object : in out Buffer_Fence; Status : out Fence_Status);
-- Perform a client wait sync for the fence corresponding to the
-- current index
procedure Advance_Index (Object : in out Buffer_Fence);
-- Set a fence for the corresponding index and then increment it
private
type Fence_Array is array (Index_Type) of GL.Fences.Fence;
type Buffer_Fence is tagged record
Fences : Fence_Array;
Index : Index_Type;
end record;
end Orka.Rendering.Fences;
|
Make package Orka.Rendering.Fences preelaborated
|
orka: Make package Orka.Rendering.Fences preelaborated
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
1cc1f4e38e51f123bc96dcdf581dcd16860c954a
|
src/nanomsg-socket.adb
|
src/nanomsg-socket.adb
|
with Ada.Unchecked_Conversion;
with Interfaces.C.Strings;
with Interfaces.C.Pointers;
with Nanomsg.Errors;
with System;
package body Nanomsg.Socket is
package C renames Interfaces.C;
use type C.Int;
function Is_Null (Obj : in Socket_T) return Boolean is (Obj.Fd = -1);
procedure Init (Obj : out Socket_T;
Domain : in Nanomsg.Domains.Domain_T;
Protocol : in Nanomsg.Protocols.Protocol_T
) is
function C_Nn_Socket (Domain : in C.Int; Protocol : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_socket";
begin
Obj.Fd := Integer (C_Nn_Socket (Nanomsg.Domains.To_C (Domain),
Nanomsg.Protocols.To_C (Protocol)));
if Obj.Fd < 0 then
raise Socket_Exception with "Init: " & Nanomsg.Errors.Errno_Text;
end if;
end Init;
procedure Close (Obj : in out Socket_T) is
function C_Nn_Close (Socket : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_close";
begin
if C_Nn_Close (C.Int (Obj.Fd)) /= 0 then
raise Socket_Exception with "Close: " & Nanomsg.Errors.Errno_Text;
end if;
Obj.Fd := -1;
end Close;
procedure Bind (Obj : in Socket_T;
Address : in String) is
function C_Bind (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_bind";
Endpoint : C.Int := -1;
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Endpoint := C_Bind(C.Int (Obj.Fd), C_Address);
C.Strings.Free (C_Address);
if Endpoint < -1 then
raise Socket_Exception with "Bind: " & Nanomsg.Errors.Errno_Text;
end if;
-- FIXME
-- Add endpoints container
end Bind;
procedure Connect (Obj : in Socket_T;
Address : in String) is
function C_Connect (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_connect";
Endpoint : C.Int := -1;
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Endpoint := C_Connect(C.Int (Obj.Fd), C_Address) ;
C.Strings.Free (C_Address);
if Endpoint < 0 then
raise Socket_Exception with "Connect: " & Nanomsg.Errors.Errno_Text;
end if;
end Connect;
function Get_Fd (Obj : in Socket_T) return Integer is (Obj.Fd);
procedure Receive (Obj : in out Socket_T;
Message : out Nanomsg.Messages.Message_T) is
Payload : System.Address;
use type System.Address;
Received : Integer;
use type C.Size_T;
Flags : constant C.Int := 0;
Nn_Msg : constant C.Size_T := C.Size_T'Last;
function Nn_Recv (Socket : C.Int;
Buf_Access : in out System.Address;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_recv";
-- function Free_Msg (Buf_Access : in out System.Address) return C.Int
-- with Import, Convention => C, External_Name => "nn_freemsg";
begin
Received := Integer (Nn_Recv (C.Int (Obj.Fd), Payload, Nn_Msg, Flags));
if Received < 0 then
raise Socket_Exception with "Receive: " & Nanomsg.Errors.Errno_Text;
end if;
Message.Set_Length (Received);
declare
Data : Nanomsg.Messages.Bytes_Array_T (1 .. Received);
for Data'Address use Payload;
begin
Message.Set_Payload (new Nanomsg.Messages.Bytes_Array_T'(Data));
end;
-- if Free_Msg (Payload) < 0 then
-- raise Socket_Exception;
-- end if;
end Receive;
procedure Send (Obj : in Socket_T; Message : Nanomsg.Messages.Message_T) is
Flags : C.Int := 0;
function Nn_Send (Socket : C.Int;
Buf_Access : Nanomsg.Messages.Bytes_Array_T;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_send";
Sent : Integer;
begin
Sent := Integer (Nn_Send (C.Int (Obj.Fd),
Message.Get_Payload.all,
C.Size_T (Message.Get_Length),
Flags));
if Sent < 0 then
raise Socket_Exception with "Send: " & Nanomsg.Errors.Errno_Text;
end if;
if Sent /= Message.Get_Length then
raise Socket_Exception with "Send/Receive count doesn't match";
end if;
end Send;
end Nanomsg.Socket;
|
with Ada.Unchecked_Conversion;
with Interfaces.C.Strings;
with Interfaces.C.Pointers;
with Nanomsg.Errors;
with System;
package body Nanomsg.Socket is
package C renames Interfaces.C;
use type C.Int;
function Is_Null (Obj : in Socket_T) return Boolean is (Obj.Fd = -1);
procedure Init (Obj : out Socket_T;
Domain : in Nanomsg.Domains.Domain_T;
Protocol : in Nanomsg.Protocols.Protocol_T
) is
function C_Nn_Socket (Domain : in C.Int; Protocol : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_socket";
begin
Obj.Fd := Integer (C_Nn_Socket (Nanomsg.Domains.To_C (Domain),
Nanomsg.Protocols.To_C (Protocol)));
if Obj.Fd < 0 then
raise Socket_Exception with "Init: " & Nanomsg.Errors.Errno_Text;
end if;
end Init;
procedure Close (Obj : in out Socket_T) is
function C_Nn_Close (Socket : in C.Int) return C.Int
with Import, Convention => C, External_Name => "nn_close";
begin
if C_Nn_Close (C.Int (Obj.Fd)) /= 0 then
raise Socket_Exception with "Close: " & Nanomsg.Errors.Errno_Text;
end if;
Obj.Fd := -1;
end Close;
procedure Bind (Obj : in Socket_T;
Address : in String) is
function C_Bind (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_bind";
Endpoint : C.Int := -1;
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Endpoint := C_Bind(C.Int (Obj.Fd), C_Address);
C.Strings.Free (C_Address);
if Endpoint < -1 then
raise Socket_Exception with "Bind: " & Nanomsg.Errors.Errno_Text;
end if;
-- FIXME
-- Add endpoints container
end Bind;
procedure Connect (Obj : in Socket_T;
Address : in String) is
function C_Connect (Socket : in C.Int; Address : in C.Strings.Chars_Ptr) return C.Int
with Import, Convention => C, External_Name => "nn_connect";
Endpoint : C.Int := -1;
C_Address : C.Strings.Chars_Ptr := C.Strings.New_String (Address);
begin
Endpoint := C_Connect(C.Int (Obj.Fd), C_Address) ;
C.Strings.Free (C_Address);
if Endpoint < 0 then
raise Socket_Exception with "Connect: " & Nanomsg.Errors.Errno_Text;
end if;
end Connect;
function Get_Fd (Obj : in Socket_T) return Integer is (Obj.Fd);
procedure Receive (Obj : in out Socket_T;
Message : out Nanomsg.Messages.Message_T) is
type Payload_T is null record;
type Payload_Access_T is access all Payload_T;
Payload : Payload_Access_T := new Payload_T;
use type System.Address;
Received : Integer;
use type C.Size_T;
Flags : constant C.Int := 0;
Nn_Msg : constant C.Size_T := C.Size_T'Last;
function Nn_Recv (Socket : C.Int;
Buf_Access : out Payload_Access_T;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_recv";
function Free_Msg (Buf_Access : in out System.Address) return C.Int
with Import, Convention => C, External_Name => "nn_freemsg";
begin
Received := Integer (Nn_Recv (C.Int (Obj.Fd), Payload, Nn_Msg, Flags));
if Received < 0 then
raise Socket_Exception with "Receive: " & Nanomsg.Errors.Errno_Text;
end if;
Message.Set_Length (Received);
declare
Data : Nanomsg.Messages.Bytes_Array_T (1 .. Received);
for Data'Address use Payload.all'Address;
begin
Message.Set_Payload (new Nanomsg.Messages.Bytes_Array_T'(Data));
end;
end Receive;
procedure Send (Obj : in Socket_T; Message : Nanomsg.Messages.Message_T) is
Flags : C.Int := 0;
function Nn_Send (Socket : C.Int;
Buf_Access : Nanomsg.Messages.Bytes_Array_T;
Size : C.Size_T;
Flags : C.Int
) return C.Int with Import, Convention => C, External_Name => "nn_send";
Sent : Integer;
begin
Sent := Integer (Nn_Send (C.Int (Obj.Fd),
Message.Get_Payload.all,
C.Size_T (Message.Get_Length),
Flags));
if Sent < 0 then
raise Socket_Exception with "Send: " & Nanomsg.Errors.Errno_Text;
end if;
if Sent /= Message.Get_Length then
raise Socket_Exception with "Send/Receive count doesn't match";
end if;
end Send;
end Nanomsg.Socket;
|
Use heap instead of stack for message allocation
|
Use heap instead of stack for message allocation
|
Ada
|
mit
|
landgraf/nanomsg-ada
|
5fc541f19c518a4ccab59687d47ebb7ae299ba8e
|
src/wiki-documents.adb
|
src/wiki-documents.adb
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
use Wiki.Nodes.Lists;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
pragma Unreferenced (Tag);
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Returns True if the current node is the root document node.
-- ------------------------------
function Is_Root_Node (Doc : in Document) return Boolean is
begin
return Doc.Current = null;
end Is_Root_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Parent => Into.Current,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0,
Parent => Into.Current));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0,
Parent => Into.Current));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0,
Parent => Into.Current));
when N_LIST_ITEM =>
Append (Into, new Node_Type '(Kind => N_LIST_ITEM, Len => 0,
Parent => Into.Current));
when N_LIST_END =>
Append (Into, new Node_Type '(Kind => N_LIST_END, Len => 0,
Parent => Into.Current));
when N_NUM_LIST_END =>
Append (Into, new Node_Type '(Kind => N_NUM_LIST_END, Len => 0,
Parent => Into.Current));
when N_LIST_ITEM_END =>
Append (Into, new Node_Type '(Kind => N_LIST_ITEM_END, Len => 0,
Parent => Into.Current));
when N_NEWLINE =>
Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0,
Parent => Into.Current));
when N_END_DEFINITION =>
Append (Into, new Node_Type '(Kind => N_END_DEFINITION, Len => 0,
Parent => Into.Current));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0,
Parent => Into.Current));
Into.Using_TOC := True;
when N_NONE =>
null;
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Parent => Into.Current,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a definition item at end of the document.
-- ------------------------------
procedure Add_Definition (Into : in out Document;
Definition : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_DEFINITION,
Len => Definition'Length,
Parent => Into.Current,
Header => Definition,
Level => 0));
end Add_Definition;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- Add a list (<ul> or <ol>) starting at the given number.
-- ------------------------------
procedure Add_List (Into : in out Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST_START, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST_START, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
end if;
end Add_List;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
end Add_Blockquote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Parent => Into.Current,
Preformatted => Text,
Language => Strings.To_UString (Format)));
end Add_Preformatted;
-- ------------------------------
-- Add a new row to the current table.
-- ------------------------------
procedure Add_Row (Into : in out Document) is
Table : Node_Type_Access;
Row : Node_Type_Access;
begin
-- Identify the current table.
Table := Into.Current;
while Table /= null and then Table.Kind /= N_TABLE loop
Table := Table.Parent;
end loop;
-- Create the current table.
if Table = null then
Table := new Node_Type '(Kind => N_TABLE,
Len => 0,
Tag_Start => TABLE_TAG,
Children => null,
Parent => Into.Current,
others => <>);
Append (Into, Table);
end if;
-- Add the row.
Row := new Node_Type '(Kind => N_ROW,
Len => 0,
Tag_Start => TR_TAG,
Children => null,
Parent => Table,
others => <>);
Append (Table, Row);
Into.Current := Row;
end Add_Row;
-- ------------------------------
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
-- ------------------------------
procedure Add_Column (Into : in out Document;
Attributes : in out Wiki.Attributes.Attribute_List) is
Row : Node_Type_Access;
Col : Node_Type_Access;
begin
-- Identify the current row.
Row := Into.Current;
while Row /= null and then Row.Kind /= N_ROW loop
Row := Row.Parent;
end loop;
-- Add the new column.
Col := new Node_Type '(Kind => N_COLUMN,
Len => 0,
Tag_Start => TD_TAG,
Children => null,
Parent => Row,
Attributes => Attributes);
Append (Row, Col);
Into.Current := Col;
end Add_Column;
-- ------------------------------
-- Finish the creation of the table.
-- ------------------------------
procedure Finish_Table (Into : in out Document) is
Table : Node_Type_Access;
begin
-- Identify the current table.
Table := Into.Current;
while Table /= null and then Table.Kind /= N_TABLE loop
Table := Table.Parent;
end loop;
if Table /= null then
Into.Current := Table.Parent;
else
Into.Current := null;
end if;
end Finish_Table;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Returns True if the table of contents is visible and must be rendered.
-- ------------------------------
function Is_Visible_TOC (Doc : in Document) return Boolean is
begin
return Doc.Visible_TOC;
end Is_Visible_TOC;
-- ------------------------------
-- Hide the table of contents.
-- ------------------------------
procedure Hide_TOC (Doc : in out Document) is
begin
Doc.Visible_TOC := False;
end Hide_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref) is
begin
if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Set a link definition.
-- ------------------------------
procedure Set_Link (Doc : in out Document;
Name : in Wiki.Strings.WString;
Link : in Wiki.Strings.WString) is
begin
Doc.Links.Include (Name, Link);
end Set_Link;
-- ------------------------------
-- Get a link definition.
-- ------------------------------
function Get_Link (Doc : in out Document;
Name : in Wiki.Strings.WString) return Wiki.Strings.WString is
Pos : constant Wiki.Strings.Maps.Cursor := Doc.Links.Find (Name);
begin
if Wiki.Strings.Maps.Has_Element (Pos) then
return Wiki.Strings.Maps.Element (Pos);
else
return "";
end if;
end Get_Link;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Characters.Handling;
package body Wiki.Documents is
use Wiki.Nodes;
use Wiki.Nodes.Lists;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Start_Block (Into : in out Document;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Natural) is
Node : Node_Type_Access;
begin
case Kind is
when N_HEADER =>
Node := new Node_Type '(Kind => N_HEADER,
Len => 0,
Level => Level,
Content => null,
Parent => Into.Current);
when others =>
return;
end case;
Append (Into, Node);
Into.Current := Node;
end Start_Block;
procedure End_Block (From : in out Document;
Kind : in Wiki.Nodes.Node_Kind) is
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end End_Block;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
pragma Unreferenced (Tag);
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Returns True if the current node is the root document node.
-- ------------------------------
function Is_Root_Node (Doc : in Document) return Boolean is
begin
return Doc.Current = null;
end Is_Root_Node;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0,
Parent => Into.Current));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0,
Parent => Into.Current));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0,
Parent => Into.Current));
when N_LIST_ITEM =>
Append (Into, new Node_Type '(Kind => N_LIST_ITEM, Len => 0,
Parent => Into.Current));
when N_LIST_END =>
Append (Into, new Node_Type '(Kind => N_LIST_END, Len => 0,
Parent => Into.Current));
when N_NUM_LIST_END =>
Append (Into, new Node_Type '(Kind => N_NUM_LIST_END, Len => 0,
Parent => Into.Current));
when N_LIST_ITEM_END =>
Append (Into, new Node_Type '(Kind => N_LIST_ITEM_END, Len => 0,
Parent => Into.Current));
when N_NEWLINE =>
Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0,
Parent => Into.Current));
when N_END_DEFINITION =>
Append (Into, new Node_Type '(Kind => N_END_DEFINITION, Len => 0,
Parent => Into.Current));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0,
Parent => Into.Current));
Into.Using_TOC := True;
when N_NONE =>
null;
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Parent => Into.Current,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a definition item at end of the document.
-- ------------------------------
procedure Add_Definition (Into : in out Document;
Definition : in Wiki.Strings.WString) is
begin
-- Append (Into, new Node_Type '(Kind => N_DEFINITION,
-- Len => Definition'Length,
-- Parent => Into.Current,
-- Header => Definition,
-- Level => 0));
null;
end Add_Definition;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add a link reference with the given label.
-- ------------------------------
procedure Add_Link_Ref (Into : in out Document;
Label : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_LINK_REF, Len => Label'Length,
Parent => Into.Current,
Title => Label, others => <>));
end Add_Link_Ref;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Parent => Into.Current,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- Add a list (<ul> or <ol>) starting at the given number.
-- ------------------------------
procedure Add_List (Into : in out Document;
Level : in Natural;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST_START, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST_START, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
end if;
end Add_List;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Parent => Into.Current,
Level => Level, others => <>));
end Add_Blockquote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Parent => Into.Current,
Preformatted => Text,
Language => Strings.To_UString (Format)));
end Add_Preformatted;
-- ------------------------------
-- Add a new row to the current table.
-- ------------------------------
procedure Add_Row (Into : in out Document) is
Table : Node_Type_Access;
Row : Node_Type_Access;
begin
-- Identify the current table.
Table := Into.Current;
while Table /= null and then Table.Kind /= N_TABLE loop
Table := Table.Parent;
end loop;
-- Create the current table.
if Table = null then
Table := new Node_Type '(Kind => N_TABLE,
Len => 0,
Tag_Start => TABLE_TAG,
Children => null,
Parent => Into.Current,
others => <>);
Append (Into, Table);
end if;
-- Add the row.
Row := new Node_Type '(Kind => N_ROW,
Len => 0,
Tag_Start => TR_TAG,
Children => null,
Parent => Table,
others => <>);
Append (Table, Row);
Into.Current := Row;
end Add_Row;
-- ------------------------------
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
-- ------------------------------
procedure Add_Column (Into : in out Document;
Attributes : in out Wiki.Attributes.Attribute_List) is
Row : Node_Type_Access;
Col : Node_Type_Access;
begin
-- Identify the current row.
Row := Into.Current;
while Row /= null and then Row.Kind /= N_ROW loop
Row := Row.Parent;
end loop;
-- Add the new column.
Col := new Node_Type '(Kind => N_COLUMN,
Len => 0,
Tag_Start => TD_TAG,
Children => null,
Parent => Row,
Attributes => Attributes);
Append (Row, Col);
Into.Current := Col;
end Add_Column;
-- ------------------------------
-- Finish the creation of the table.
-- ------------------------------
procedure Finish_Table (Into : in out Document) is
Table : Node_Type_Access;
begin
-- Identify the current table.
Table := Into.Current;
while Table /= null and then Table.Kind /= N_TABLE loop
Table := Table.Parent;
end loop;
if Table /= null then
Into.Current := Table.Parent;
else
Into.Current := null;
end if;
end Finish_Table;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Returns True if the table of contents is visible and must be rendered.
-- ------------------------------
function Is_Visible_TOC (Doc : in Document) return Boolean is
begin
return Doc.Visible_TOC;
end Is_Visible_TOC;
-- ------------------------------
-- Hide the table of contents.
-- ------------------------------
procedure Hide_TOC (Doc : in out Document) is
begin
Doc.Visible_TOC := False;
end Hide_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref) is
begin
if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Set a link definition.
-- ------------------------------
procedure Set_Link (Doc : in out Document;
Name : in Wiki.Strings.WString;
Link : in Wiki.Strings.WString;
Title : in Wiki.Strings.WString) is
Upper : constant Wiki.Strings.WString
:= Ada.Wide_Wide_Characters.Handling.To_Upper (Name);
begin
if not Doc.Links.Contains (Upper) then
Doc.Links.Include (Upper, Link);
if Title'Length > 0 then
Doc.Titles.Include (Upper, Title);
end if;
end if;
end Set_Link;
-- ------------------------------
-- Get a link definition.
-- ------------------------------
function Get_Link (Doc : in Document;
Label : in Wiki.Strings.WString) return Wiki.Strings.WString is
Upper : constant Wiki.Strings.WString
:= Ada.Wide_Wide_Characters.Handling.To_Upper (Label);
Pos : constant Wiki.Strings.Maps.Cursor := Doc.Links.Find (Upper);
begin
if Wiki.Strings.Maps.Has_Element (Pos) then
return Wiki.Strings.Maps.Element (Pos);
else
return "";
end if;
end Get_Link;
-- ------------------------------
-- Get a link definition.
-- ------------------------------
function Get_Link_Title (Doc : in Document;
Label : in Wiki.Strings.WString) return Wiki.Strings.WString is
Upper : constant Wiki.Strings.WString
:= Ada.Wide_Wide_Characters.Handling.To_Upper (Label);
Pos : constant Wiki.Strings.Maps.Cursor := Doc.Titles.Find (Upper);
begin
if Wiki.Strings.Maps.Has_Element (Pos) then
return Wiki.Strings.Maps.Element (Pos);
else
return "";
end if;
end Get_Link_Title;
end Wiki.Documents;
|
Implement Start_Block, End_Block, Get_Link_Title
|
Implement Start_Block, End_Block, Get_Link_Title
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
301909d996504873da08595b3a62ad5d059bbb3a
|
tools/druss-commands.ads
|
tools/druss-commands.ads
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- 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.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type);
procedure Initialize;
end Druss.Commands;
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- 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.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_WAN_IP,
F_INTERNET,
F_VOIP,
F_WIFI,
F_WIFI5,
F_ACCESS_CONTROL,
F_DYNDNS,
F_DEVICES,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type);
procedure Initialize;
end Druss.Commands;
|
Declare several new fields for the bbox status command
|
Declare several new fields for the bbox status command
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
a215949742d226135a6e149c66b297930153a3ab
|
src/gl/implementation/gl-enums-textures.ads
|
src/gl/implementation/gl-enums-textures.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- 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.
private with GL.Low_Level;
package GL.Enums.Textures is
pragma Preelaborate;
-- Texture_Kind is declared in GL.Low_Level.Enums to be accessible for
-- OpenCLAda
type Parameter is (Border_Color, Mag_Filter, Min_Filter, Wrap_S,
Wrap_T, Wrap_R, Min_LoD, Max_LoD,
Base_Level, Max_Level, Immutable_Levels, Max_Anisotropy,
LoD_Bias, Compare_Mode, Compare_Func, Cube_Map_Seamless);
-- needs to be declared here because of subtypes
for Parameter use (Border_Color => 16#1004#,
Mag_Filter => 16#2800#,
Min_Filter => 16#2801#,
Wrap_S => 16#2802#,
Wrap_T => 16#2803#,
Wrap_R => 16#8072#,
Min_LoD => 16#813A#,
Max_LoD => 16#813B#,
Base_Level => 16#813C#,
Max_Level => 16#813D#,
Immutable_Levels => 16#82DF#,
Max_Anisotropy => 16#84FE#,
LoD_Bias => 16#8501#,
Compare_Mode => 16#884C#,
Compare_Func => 16#884D#,
Cube_Map_Seamless => 16#884F#);
for Parameter'Size use Low_Level.Enum'Size;
subtype LoD is Parameter range Min_LoD .. Max_Level;
type Compare_Kind is (None, Compare_R_To_Texture);
type Env_Parameter is (LoD_Bias, Src1_Alpha);
type Level_Parameter is (Width, Height, Internal_Format, Red_Size,
Green_Size, Blue_Size, Alpha_Size, Depth,
Compressed_Image_Size, Compressed,
Depth_Size, Stencil_Size,
Red_Type, Green_Type, Blue_Type,
Alpha_Type, Depth_Type, Shared_Size,
Samples, Fixed_Sample_Locations,
Buffer_Offset, Buffer_Size);
Texture_Unit_Start_Rep : constant := 16#84C0#;
private
for Compare_Kind use (None => 0, Compare_R_To_Texture => 16#884E#);
for Compare_Kind'Size use Low_Level.Enum'Size;
for Env_Parameter use (LoD_Bias => 16#8501#,
Src1_Alpha => 16#8589#);
for Env_Parameter'Size use Low_Level.Enum'Size;
for Level_Parameter use (Width => 16#1000#,
Height => 16#1001#,
Internal_Format => 16#1003#,
Red_Size => 16#805C#,
Green_Size => 16#805D#,
Blue_Size => 16#805E#,
Alpha_Size => 16#805F#,
Depth => 16#8071#,
Compressed_Image_Size => 16#86A0#,
Compressed => 16#86A1#,
Depth_Size => 16#884A#,
Stencil_Size => 16#88F1#,
Red_Type => 16#8C10#,
Green_Type => 16#8C11#,
Blue_Type => 16#8C12#,
Alpha_Type => 16#8C13#,
Depth_Type => 16#8C16#,
Shared_Size => 16#8C3F#,
Samples => 16#9106#,
Fixed_Sample_Locations => 16#9107#,
Buffer_Offset => 16#919D#,
Buffer_Size => 16#919E#);
for Level_Parameter'Size use Low_Level.Enum'Size;
end GL.Enums.Textures;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- 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.
private with GL.Low_Level;
package GL.Enums.Textures is
pragma Preelaborate;
type Parameter is (Border_Color, Mag_Filter, Min_Filter, Wrap_S,
Wrap_T, Wrap_R, Min_LoD, Max_LoD,
Base_Level, Max_Level, Immutable_Levels, Max_Anisotropy,
LoD_Bias, Compare_Mode, Compare_Func, Cube_Map_Seamless);
type Compare_Kind is (None, Compare_R_To_Texture);
type Level_Parameter is (Width, Height, Internal_Format, Red_Size,
Green_Size, Blue_Size, Alpha_Size, Depth,
Compressed_Image_Size, Compressed,
Depth_Size, Stencil_Size,
Red_Type, Green_Type, Blue_Type,
Alpha_Type, Depth_Type, Shared_Size,
Samples, Fixed_Sample_Locations,
Buffer_Offset, Buffer_Size);
private
for Parameter use (Border_Color => 16#1004#,
Mag_Filter => 16#2800#,
Min_Filter => 16#2801#,
Wrap_S => 16#2802#,
Wrap_T => 16#2803#,
Wrap_R => 16#8072#,
Min_LoD => 16#813A#,
Max_LoD => 16#813B#,
Base_Level => 16#813C#,
Max_Level => 16#813D#,
Immutable_Levels => 16#82DF#,
Max_Anisotropy => 16#84FE#,
LoD_Bias => 16#8501#,
Compare_Mode => 16#884C#,
Compare_Func => 16#884D#,
Cube_Map_Seamless => 16#884F#);
for Parameter'Size use Low_Level.Enum'Size;
for Compare_Kind use (None => 0, Compare_R_To_Texture => 16#884E#);
for Compare_Kind'Size use Low_Level.Enum'Size;
for Level_Parameter use (Width => 16#1000#,
Height => 16#1001#,
Internal_Format => 16#1003#,
Red_Size => 16#805C#,
Green_Size => 16#805D#,
Blue_Size => 16#805E#,
Alpha_Size => 16#805F#,
Depth => 16#8071#,
Compressed_Image_Size => 16#86A0#,
Compressed => 16#86A1#,
Depth_Size => 16#884A#,
Stencil_Size => 16#88F1#,
Red_Type => 16#8C10#,
Green_Type => 16#8C11#,
Blue_Type => 16#8C12#,
Alpha_Type => 16#8C13#,
Depth_Type => 16#8C16#,
Shared_Size => 16#8C3F#,
Samples => 16#9106#,
Fixed_Sample_Locations => 16#9107#,
Buffer_Offset => 16#919D#,
Buffer_Size => 16#919E#);
for Level_Parameter'Size use Low_Level.Enum'Size;
end GL.Enums.Textures;
|
Remove some unused types and constants in package GL.Enums.Textures
|
gl: Remove some unused types and constants in package GL.Enums.Textures
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
49547e9ae0fa2c5a424363cdff323eec23913cc6
|
src/wiki-render-wiki.ads
|
src/wiki-render-wiki.ads
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Writers;
with Wiki.Parsers;
-- == Wiki Renderer ==
-- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private;
-- Set the output writer.
procedure Set_Writer (Document : in out Wiki_Renderer;
Writer : in Writers.Writer_Type_Access;
Format : in Parsers.Wiki_Syntax_Type);
-- Add a section header in the document.
overriding
procedure Add_Header (Document : in out Wiki_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
overriding
procedure Add_Line_Break (Document : in out Wiki_Renderer);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
overriding
procedure Add_Paragraph (Document : in out Wiki_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
overriding
procedure Add_Blockquote (Document : in out Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
overriding
procedure Add_List_Item (Document : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
overriding
procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer);
-- Add a link.
overriding
procedure Add_Link (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
overriding
procedure Add_Image (Document : in out Wiki_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
overriding
procedure Add_Quote (Document : in out Wiki_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
overriding
procedure Add_Text (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
overriding
procedure Start_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Attribute_List_Type);
overriding
procedure End_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Wiki_Renderer);
-- Set the text style format.
procedure Set_Format (Document : in out Wiki_Renderer;
Format : in Documents.Format_Map);
private
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End, Link_Separator,
Preformat_Start, Preformat_End,
List_Start, List_Item, List_Ordered_Item,
Line_Break, Escape_Rule,
Horizontal_Rule,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
type Wiki_Format_Array is array (Documents.Format_Type) of Wide_String_Access;
-- Emit a new line.
procedure New_Line (Document : in out Wiki_Renderer);
procedure Close_Paragraph (Document : in out Wiki_Renderer);
procedure Open_Paragraph (Document : in out Wiki_Renderer);
procedure Start_Keep_Content (Document : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Documents.Document_Reader with record
Writer : Writers.Writer_Type_Access := null;
Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE;
Format : Documents.Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Keep_Content : Boolean := False;
In_List : Boolean := False;
Invert_Header_Level : Boolean := False;
Allow_Link_Language : Boolean := False;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
UL_List_Level : Natural := 0;
OL_List_Level : Natural := 0;
Current_Style : Documents.Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to Wiki renderer
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Maps;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Writers;
with Wiki.Parsers;
-- == Wiki Renderer ==
-- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private;
-- Set the output writer.
procedure Set_Writer (Document : in out Wiki_Renderer;
Writer : in Writers.Writer_Type_Access;
Format : in Parsers.Wiki_Syntax_Type);
-- Add a section header in the document.
overriding
procedure Add_Header (Document : in out Wiki_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
overriding
procedure Add_Line_Break (Document : in out Wiki_Renderer);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
overriding
procedure Add_Paragraph (Document : in out Wiki_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
overriding
procedure Add_Blockquote (Document : in out Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
overriding
procedure Add_List_Item (Document : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
overriding
procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer);
-- Add a link.
overriding
procedure Add_Link (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
overriding
procedure Add_Image (Document : in out Wiki_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
overriding
procedure Add_Quote (Document : in out Wiki_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
overriding
procedure Add_Text (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
overriding
procedure Start_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Attribute_List_Type);
overriding
procedure End_Element (Document : in out Wiki_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Wiki_Renderer);
-- Set the text style format.
procedure Set_Format (Document : in out Wiki_Renderer;
Format : in Documents.Format_Map);
private
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End, Link_Separator,
Preformat_Start, Preformat_End,
List_Start, List_Item, List_Ordered_Item,
Line_Break, Escape_Rule,
Horizontal_Rule,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
type Wiki_Format_Array is array (Documents.Format_Type) of Wide_String_Access;
-- Emit a new line.
procedure New_Line (Document : in out Wiki_Renderer);
procedure Close_Paragraph (Document : in out Wiki_Renderer);
procedure Open_Paragraph (Document : in out Wiki_Renderer);
procedure Start_Keep_Content (Document : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Documents.Document_Reader with record
Writer : Writers.Writer_Type_Access := null;
Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE;
Format : Documents.Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set;
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Keep_Content : Boolean := False;
In_List : Boolean := False;
Invert_Header_Level : Boolean := False;
Allow_Link_Language : Boolean := False;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
UL_List_Level : Natural := 0;
OL_List_Level : Natural := 0;
Current_Style : Documents.Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
Add Escape_Set member to define the characters to escape
|
Add Escape_Set member to define the characters to escape
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
adf5332b116bf92c543debf2bc28e6ff0c4dcf04
|
src/base/commands/util-commands.ads
|
src/base/commands/util-commands.ads
|
-----------------------------------------------------------------------
-- util-commands -- Support to make command line tools
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Util.Strings.Vectors;
private with Ada.Strings.Unbounded;
package Util.Commands is
-- The argument list interface that gives access to command arguments.
type Argument_List is limited interface;
-- Get the number of arguments available.
function Get_Count (List : in Argument_List) return Natural is abstract;
-- Get the argument at the given position.
function Get_Argument (List : in Argument_List;
Pos : in Positive) return String is abstract;
-- Get the command name.
function Get_Command_Name (List : in Argument_List) return String is abstract;
type Default_Argument_List (Offset : Natural) is new Argument_List with null record;
-- Get the number of arguments available.
overriding
function Get_Count (List : in Default_Argument_List) return Natural;
-- Get the argument at the given position.
overriding
function Get_Argument (List : in Default_Argument_List;
Pos : in Positive) return String;
-- Get the command name.
function Get_Command_Name (List : in Default_Argument_List) return String;
type String_Argument_List (Max_Length : Positive;
Max_Args : Positive) is new Argument_List with private;
-- Set the argument list to the given string and split the arguments.
procedure Initialize (List : in out String_Argument_List;
Line : in String);
-- Get the number of arguments available.
overriding
function Get_Count (List : in String_Argument_List) return Natural;
-- Get the argument at the given position.
overriding
function Get_Argument (List : in String_Argument_List;
Pos : in Positive) return String;
-- Get the command name.
overriding
function Get_Command_Name (List : in String_Argument_List) return String;
-- The argument list interface that gives access to command arguments.
type Dynamic_Argument_List is limited new Argument_List with private;
-- Get the number of arguments available.
function Get_Count (List : in Dynamic_Argument_List) return Natural;
-- Get the argument at the given position.
function Get_Argument (List : in Dynamic_Argument_List;
Pos : in Positive) return String;
-- Get the command name.
function Get_Command_Name (List : in Dynamic_Argument_List) return String;
private
type Argument_Pos is array (Natural range <>) of Natural;
type String_Argument_List (Max_Length : Positive;
Max_Args : Positive) is new Argument_List
with record
Count : Natural := 0;
Length : Natural := 0;
Line : String (1 .. Max_Length);
Start_Pos : Argument_Pos (0 .. Max_Args) := (others => 0);
End_Pos : Argument_Pos (0 .. Max_Args) := (others => 0);
end record;
type Dynamic_Argument_List is limited new Argument_List with record
List : Util.Strings.Vectors.Vector;
Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Util.Commands;
|
-----------------------------------------------------------------------
-- util-commands -- Support to make command line tools
-- 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.
-----------------------------------------------------------------------
private with Util.Strings.Vectors;
private with Ada.Strings.Unbounded;
package Util.Commands is
-- Exception raised when a command was not found.
Not_Found : exception;
-- The argument list interface that gives access to command arguments.
type Argument_List is limited interface;
-- Get the number of arguments available.
function Get_Count (List : in Argument_List) return Natural is abstract;
-- Get the argument at the given position.
function Get_Argument (List : in Argument_List;
Pos : in Positive) return String is abstract;
-- Get the command name.
function Get_Command_Name (List : in Argument_List) return String is abstract;
type Default_Argument_List (Offset : Natural) is new Argument_List with null record;
-- Get the number of arguments available.
overriding
function Get_Count (List : in Default_Argument_List) return Natural;
-- Get the argument at the given position.
overriding
function Get_Argument (List : in Default_Argument_List;
Pos : in Positive) return String;
-- Get the command name.
function Get_Command_Name (List : in Default_Argument_List) return String;
type String_Argument_List (Max_Length : Positive;
Max_Args : Positive) is new Argument_List with private;
-- Set the argument list to the given string and split the arguments.
procedure Initialize (List : in out String_Argument_List;
Line : in String);
-- Get the number of arguments available.
overriding
function Get_Count (List : in String_Argument_List) return Natural;
-- Get the argument at the given position.
overriding
function Get_Argument (List : in String_Argument_List;
Pos : in Positive) return String;
-- Get the command name.
overriding
function Get_Command_Name (List : in String_Argument_List) return String;
-- The argument list interface that gives access to command arguments.
type Dynamic_Argument_List is limited new Argument_List with private;
-- Get the number of arguments available.
function Get_Count (List : in Dynamic_Argument_List) return Natural;
-- Get the argument at the given position.
function Get_Argument (List : in Dynamic_Argument_List;
Pos : in Positive) return String;
-- Get the command name.
function Get_Command_Name (List : in Dynamic_Argument_List) return String;
private
type Argument_Pos is array (Natural range <>) of Natural;
type String_Argument_List (Max_Length : Positive;
Max_Args : Positive) is new Argument_List
with record
Count : Natural := 0;
Length : Natural := 0;
Line : String (1 .. Max_Length);
Start_Pos : Argument_Pos (0 .. Max_Args) := (others => 0);
End_Pos : Argument_Pos (0 .. Max_Args) := (others => 0);
end record;
type Dynamic_Argument_List is limited new Argument_List with record
List : Util.Strings.Vectors.Vector;
Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Util.Commands;
|
Add the Not_Found exception
|
Add the Not_Found exception
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d4c2fe90b68811e4e61531afb4fd5c85796fa294
|
src/asf-beans.adb
|
src/asf-beans.adb
|
-----------------------------------------------------------------------
-- asf.beans -- Bean Registration and Factory
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body ASF.Beans is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Beans");
-- ------------------------------
-- Register under the name identified by <b>Name</b> the class instance <b>Class</b>.
-- ------------------------------
procedure Register_Class (Factory : in out Bean_Factory;
Name : in String;
Class : in Class_Binding_Access) is
begin
Log.Info ("Register bean class {0}", Name);
Factory.Registry.Include (Name, Class_Binding_Ref.Create (Class));
end Register_Class;
-- ------------------------------
-- Register under the name identified by <b>Name</b> a function to create a bean.
-- This is a simplified class registration.
-- ------------------------------
procedure Register_Class (Factory : in out Bean_Factory;
Name : in String;
Handler : in Create_Bean_Access) is
Class : Default_Class_Binding_Access := new Default_Class_Binding;
begin
Class.Create := Handler;
Register_Class (Factory, Name, Class.all'Access);
end Register_Class;
-- ------------------------------
-- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>.
-- The class must have been registered by using the <b>Register</b> class operation.
-- The scope defines the scope of the bean.
-- ------------------------------
procedure Register (Factory : in out Bean_Factory;
Name : in String;
Class : in String;
Params : in Parameter_Bean_Ref.Ref;
Scope : in Scope_Type := REQUEST_SCOPE) is
begin
Log.Info ("Register bean '{0}' created by '{1}' in scope {2}",
Name, Class, Scope_Type'Image (Scope));
declare
Pos : constant Registry_Maps.Cursor := Factory.Registry.Find (Class);
Binding : Bean_Binding;
begin
if not Registry_Maps.Has_Element (Pos) then
Log.Error ("Class '{0}' does not exist. Cannot register bean '{1}'",
Class, Name);
return;
end if;
Binding.Create := Registry_Maps.Element (Pos);
Binding.Scope := Scope;
Binding.Params := Params;
Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding);
end;
end Register;
-- ------------------------------
-- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>.
-- The class must have been registered by using the <b>Register</b> class operation.
-- The scope defines the scope of the bean.
-- ------------------------------
procedure Register (Factory : in out Bean_Factory;
Name : in String;
Class : in Class_Binding_Access;
Params : in Parameter_Bean_Ref.Ref;
Scope : in Scope_Type := REQUEST_SCOPE) is
Binding : Bean_Binding;
begin
Log.Info ("Register bean '{0}' in scope {2}",
Name, Scope_Type'Image (Scope));
Binding.Create := Class_Binding_Ref.Create (Class);
Binding.Scope := Scope;
Binding.Params := Params;
Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding);
end Register;
-- ------------------------------
-- Register all the definitions from a factory to a main factory.
-- ------------------------------
procedure Register (Factory : in out Bean_Factory;
From : in Bean_Factory) is
begin
declare
Pos : Registry_Maps.Cursor := From.Registry.First;
begin
while Registry_Maps.Has_Element (Pos) loop
Factory.Registry.Include (Key => Registry_Maps.Key (Pos),
New_Item => Registry_Maps.Element (Pos));
Registry_Maps.Next (Pos);
end loop;
end;
declare
Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map);
begin
while Bean_Maps.Has_Element (Pos) loop
Factory.Map.Include (Key => Bean_Maps.Key (Pos),
New_Item => Bean_Maps.Element (Pos));
Bean_Maps.Next (Pos);
end loop;
end;
end Register;
-- ------------------------------
-- Create a bean by using the create operation registered for the name
-- ------------------------------
procedure Create (Factory : in Bean_Factory;
Name : in Unbounded_String;
Context : in EL.Contexts.ELContext'Class;
Result : out Util.Beans.Basic.Readonly_Bean_Access;
Scope : out Scope_Type) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name);
begin
if Bean_Maps.Has_Element (Pos) then
declare
Binding : constant Bean_Binding := Bean_Maps.Element (Pos);
begin
Binding.Create.Value.Create (Name, Result);
if Result /= null and then not Binding.Params.Is_Null then
if Result.all in Util.Beans.Basic.Bean'Class then
EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Result.all),
Binding.Params.Value.Params,
Context);
else
Log.Warn ("Bean {0} cannot be set with pre-defined properties as it does "
& "not implement the Bean interface", To_String (Name));
end if;
end if;
Scope := Binding.Scope;
end;
else
Result := null;
Scope := ANY_SCOPE;
end if;
end Create;
-- ------------------------------
-- Create a bean by using the registered create function.
-- ------------------------------
procedure Create (Factory : in Default_Class_Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access) is
pragma Unreferenced (Name);
begin
Result := Factory.Create.all;
end Create;
end ASF.Beans;
|
-----------------------------------------------------------------------
-- asf.beans -- Bean Registration and Factory
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body ASF.Beans is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Beans");
-- ------------------------------
-- Register under the name identified by <b>Name</b> the class instance <b>Class</b>.
-- ------------------------------
procedure Register_Class (Factory : in out Bean_Factory;
Name : in String;
Class : in Class_Binding_Access) is
begin
Log.Info ("Register bean class {0}", Name);
Factory.Registry.Include (Name, Class_Binding_Ref.Create (Class));
end Register_Class;
-- ------------------------------
-- Register under the name identified by <b>Name</b> a function to create a bean.
-- This is a simplified class registration.
-- ------------------------------
procedure Register_Class (Factory : in out Bean_Factory;
Name : in String;
Handler : in Create_Bean_Access) is
Class : constant Default_Class_Binding_Access := new Default_Class_Binding;
begin
Class.Create := Handler;
Register_Class (Factory, Name, Class.all'Access);
end Register_Class;
-- ------------------------------
-- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>.
-- The class must have been registered by using the <b>Register</b> class operation.
-- The scope defines the scope of the bean.
-- ------------------------------
procedure Register (Factory : in out Bean_Factory;
Name : in String;
Class : in String;
Params : in Parameter_Bean_Ref.Ref;
Scope : in Scope_Type := REQUEST_SCOPE) is
begin
Log.Info ("Register bean '{0}' created by '{1}' in scope {2}",
Name, Class, Scope_Type'Image (Scope));
declare
Pos : constant Registry_Maps.Cursor := Factory.Registry.Find (Class);
Binding : Bean_Binding;
begin
if not Registry_Maps.Has_Element (Pos) then
Log.Error ("Class '{0}' does not exist. Cannot register bean '{1}'",
Class, Name);
return;
end if;
Binding.Create := Registry_Maps.Element (Pos);
Binding.Scope := Scope;
Binding.Params := Params;
Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding);
end;
end Register;
-- ------------------------------
-- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>.
-- The class must have been registered by using the <b>Register</b> class operation.
-- The scope defines the scope of the bean.
-- ------------------------------
procedure Register (Factory : in out Bean_Factory;
Name : in String;
Class : in Class_Binding_Access;
Params : in Parameter_Bean_Ref.Ref;
Scope : in Scope_Type := REQUEST_SCOPE) is
Binding : Bean_Binding;
begin
Log.Info ("Register bean '{0}' in scope {2}",
Name, Scope_Type'Image (Scope));
Binding.Create := Class_Binding_Ref.Create (Class);
Binding.Scope := Scope;
Binding.Params := Params;
Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding);
end Register;
-- ------------------------------
-- Register all the definitions from a factory to a main factory.
-- ------------------------------
procedure Register (Factory : in out Bean_Factory;
From : in Bean_Factory) is
begin
declare
Pos : Registry_Maps.Cursor := From.Registry.First;
begin
while Registry_Maps.Has_Element (Pos) loop
Factory.Registry.Include (Key => Registry_Maps.Key (Pos),
New_Item => Registry_Maps.Element (Pos));
Registry_Maps.Next (Pos);
end loop;
end;
declare
Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map);
begin
while Bean_Maps.Has_Element (Pos) loop
Factory.Map.Include (Key => Bean_Maps.Key (Pos),
New_Item => Bean_Maps.Element (Pos));
Bean_Maps.Next (Pos);
end loop;
end;
end Register;
-- ------------------------------
-- Create a bean by using the create operation registered for the name
-- ------------------------------
procedure Create (Factory : in Bean_Factory;
Name : in Unbounded_String;
Context : in EL.Contexts.ELContext'Class;
Result : out Util.Beans.Basic.Readonly_Bean_Access;
Scope : out Scope_Type) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name);
begin
if Bean_Maps.Has_Element (Pos) then
declare
Binding : constant Bean_Binding := Bean_Maps.Element (Pos);
begin
Binding.Create.Value.Create (Name, Result);
if Result /= null and then not Binding.Params.Is_Null then
if Result.all in Util.Beans.Basic.Bean'Class then
EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Result.all),
Binding.Params.Value.Params,
Context);
else
Log.Warn ("Bean {0} cannot be set with pre-defined properties as it does "
& "not implement the Bean interface", To_String (Name));
end if;
end if;
Scope := Binding.Scope;
end;
else
Result := null;
Scope := ANY_SCOPE;
end if;
end Create;
-- ------------------------------
-- Create a bean by using the registered create function.
-- ------------------------------
procedure Create (Factory : in Default_Class_Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access) is
pragma Unreferenced (Name);
begin
Result := Factory.Create.all;
end Create;
end ASF.Beans;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
859b0b69e4d0ed156ea2a041798e09c008882094
|
src/wiki-streams-html-builders.adb
|
src/wiki-streams-html-builders.adb
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- 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.
-----------------------------------------------------------------------
package body Wiki.Streams.Html.Builders is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class);
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wide_Wide_Character);
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wide_Wide_Character) is
Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
Stream.Start_Element (Name);
Stream.Write_Wide_Text (Content);
Stream.End_Element (Name);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in Content'Range loop
declare
C : constant Wide_Wide_Character := Content (I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in 1 .. Count loop
declare
C : constant Wide_Wide_Character := Element (Content, I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write_String (Name);
Stream.Close_Start := True;
end Start_Element;
procedure End_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
if Stream.Close_Start then
Stream.Write (" />");
Stream.Close_Start := False;
else
Close_Current (Stream);
Stream.Write ("</");
Stream.Write_String (Name);
Stream.Write ('>');
end if;
end End_Element;
procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream;
Content : in Wiki.Strings.WString) is
begin
Close_Current (Stream);
for I in Content'Range loop
Html_Output_Builder_Stream'Class (Stream).Write_Escape (Content (I));
end loop;
end Write_Wide_Text;
end Wiki.Streams.Html.Builders;
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- 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.
-----------------------------------------------------------------------
package body Wiki.Streams.Html.Builders is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class);
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wiki.Strings.WChar);
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Output_Builder_Stream'Class;
Char : in Wiki.Strings.WChar) is
Code : constant Unicode_Char := Wiki.Strings.WChar'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
Stream.Start_Element (Name);
Stream.Write_Wide_Text (Content);
Stream.End_Element (Name);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in Content'Range loop
declare
C : constant Wiki.Strings.WChar := Content (I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in 1 .. Count loop
declare
C : constant Wiki.Strings.WChar := Element (Content, I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write_String (Name);
Stream.Close_Start := True;
end Start_Element;
procedure End_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
if Stream.Close_Start then
Stream.Write (" />");
Stream.Close_Start := False;
else
Close_Current (Stream);
Stream.Write ("</");
Stream.Write_String (Name);
Stream.Write ('>');
end if;
end End_Element;
procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream;
Content : in Wiki.Strings.WString) is
begin
Close_Current (Stream);
for I in Content'Range loop
Html_Output_Builder_Stream'Class (Stream).Write_Escape (Content (I));
end loop;
end Write_Wide_Text;
end Wiki.Streams.Html.Builders;
|
Use Wiki.Strings.WChar type
|
Use Wiki.Strings.WChar type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
704d002bc899fe37e7298e46bef57655f7e036cb
|
src/asf-security-filters.adb
|
src/asf-security-filters.adb
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.Urls;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.Urls;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URI : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URI_Permission (1, URI'Length)
:= URI_Permission '(1, Len => URI'Length, URI => URI);
begin
if not F.Manager.Has_Permission (Context, Perm) then
Log.Info ("Deny access on {0}", URI);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- 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.
-- ------------------------------
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) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.Urls;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.Urls;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URI : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URI_Permission (URI'Length)
:= URI_Permission '(Len => URI'Length, URI => URI);
begin
if not F.Manager.Has_Permission (Context, Perm) then
Log.Info ("Deny access on {0}", URI);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- 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.
-- ------------------------------
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) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
fca3cb3b8b3fb7e6d69fbdd1271a74c9e8b1f164
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Ref (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Send_Invitation (Bean);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Master_Session := Into.Module.Get_Master_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
AWA.Workspaces.Modules.Get_Workspace (Session, Ctx, WS);
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
Count_Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Ref (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Send_Invitation (Bean);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Master_Session := Into.Module.Get_Master_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
AWA.Workspaces.Modules.Get_Workspace (Session, Ctx, WS);
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
Count_Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
Call the Accept_Invitation module procedure to accept the invitation
|
Call the Accept_Invitation module procedure to accept the invitation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
380141f95e254a8a7a459e73bff2bbbacd32d320
|
src/base/log/util-log.ads
|
src/base/log/util-log.ads
|
-----------------------------------------------------------------------
-- util-log -- Utility Log Package
-- Copyright (C) 2001 - 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.
-----------------------------------------------------------------------
-- = Logging =
-- The `Util.Log` package and children provide a simple logging framework inspired
-- from the Java Log4j library. It is intended to provide a subset of logging features
-- available in other languages, be flexible, extensible, small and efficient. Having
-- log messages in large applications is very helpful to understand, track and fix complex
-- issues, some of them being related to configuration issues or interaction with other
-- systems. The overhead of calling a log operation is negligeable when the log is disabled
-- as it is in the order of 30ns and reasonable for a file appender has it is in the order
-- of 5us. To use the packages described here, use the following GNAT project:
--
-- with "utilada_base";
--
-- == Using the log framework ==
-- A bit of terminology:
--
-- * A *logger* is the abstraction that provides operations to emit a message. The message
-- is composed of a text, optional formatting parameters, a log level and a timestamp.
-- * A *formatter* is the abstraction that takes the information about the log to format
-- the final message.
-- * An *appender* is the abstraction that writes the message either to a console, a file
-- or some other final mechanism.
--
-- == Logger Declaration ==
-- Similar to other logging framework such as Java Log4j and Log4cxx, it is necessary to have
-- and instance of a logger to write a log message. The logger instance holds the configuration
-- for the log to enable, disable and control the format and the appender that will receive
-- the message. The logger instance is associated with a name that is used for the
-- configuration. A good practice is to declare a `Log` instance in the package body or
-- the package private part to make available the log instance to all the package operations.
-- The instance is created by using the `Create` function. The name used for the configuration
-- is free but using the full package name is helpful to control precisely the logs.
--
-- with Util.Log.Loggers;
-- package body X.Y is
-- Log : constant Util.Log.Loggers := Util.Log.Loggers.Create ("X.Y");
-- end X.Y;
--
-- == Logger Messages ==
-- A log message is associated with a log level which is used by the logger instance to
-- decide to emit or drop the log message. To keep the logging API simple and make it easily
-- usable in the application, several operations are provided to write a message with different
-- log level.
--
-- A log message is a string that contains optional formatting markers that follow more or
-- less the Java `MessageFormat` class. A parameter is represented by a number enclosed by `{}`.
-- The first parameter is represented by `{0}`, the second by `{1}` and so on. Parameters are
-- replaced in the final message only when the message is enabled by the log configuration.
-- The use of parameters allows to avoid formatting the log message when the log is not used.
--
-- The example below shows several calls to emit a log message with different levels:
--
-- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist");
-- Log.Warn ("The file {0} is empty", Path);
-- Log.Info ("Opening file {0}", Path);
-- Log.Debug ("Reading line {0}", Line);
--
-- The logger also provides a special `Error` procedure that accepts an Ada exception
-- occurence as parameter. The exception name and message are printed together with
-- the error message. It is also possible to activate a complete traceback of the
-- exception and report it in the error message. With this mechanism, an exception
-- can be handled and reported easily:
--
-- begin
-- ...
-- exception
-- when E : others =>
-- Log.Error ("Something bad occurred", E, Trace => True);
-- end;
--
-- == Log Configuration ==
-- The log configuration uses property files close to the Apache Log4j and to the
-- Apache Log4cxx configuration files.
-- The configuration file contains several parts to configure the logging framework:
--
-- * First, the *appender* configuration indicates the appender that exists and can receive
-- a log message.
-- * Second, a root configuration allows to control the default behavior of the logging
-- framework. The root configuration controls the default log level as well as the
-- appenders that can be used.
-- * Last, a logger configuration is defined to control the logging level more precisely
-- for each logger.
--
-- Here is a simple log configuration that creates a file appender where log messages are
-- written. The file appender is given the name `result` and is configured to write the
-- messages in the file `my-log-file.log`. The file appender will use the `level-message`
-- format for the layout of messages. Last is the configuration of the `X.Y` logger
-- that will enable only messages starting from the `WARN` level.
--
-- log4j.rootCategory=DEBUG,result
-- log4j.appender.result=File
-- log4j.appender.result.File=my-log-file.log
-- log4j.appender.result.layout=level-message
-- log4j.logger.X.Y=WARN
--
-- By default when the `layout` is not set or has an invalid value, the full message is
-- reported and the generated log messages will look as follows:
--
-- [2018-02-07 20:39:51] ERROR - X.Y - Cannot open file test.txt: File does not exist
-- [2018-02-07 20:39:51] WARN - X.Y - The file test.txt is empty
-- [2018-02-07 20:39:51] INFO - X.Y - Opening file test.txt
-- [2018-02-07 20:39:51] DEBUG - X.Y - Reading line ......
--
-- When the `layout` configuration is set to `data-level-message`, the message is printed
-- with the date and message level.
--
-- [2018-02-07 20:39:51] ERROR: Cannot open file test.txt: File does not exist
-- [2018-02-07 20:39:51] WARN : The file test.txt is empty
-- [2018-02-07 20:39:51] INFO : X.Y - Opening file test.txt
-- [2018-02-07 20:39:51] DEBUG: X.Y - Reading line ......
--
-- When the `layout` configuration is set to `level-message`, only the message and its
-- level are reported.
--
-- ERROR: Cannot open file test.txt: File does not exist
-- WARN : The file test.txt is empty
-- INFO : X.Y - Opening file test.txt
-- DEBUG: X.Y - Reading line ......
--
-- The last possible configuration for `layout` is `message` which only prints the message.
--
-- Cannot open file test.txt: File does not exist
-- The file test.txt is empty
-- Opening file test.txt
-- Reading line ......
--
package Util.Log is
pragma Preelaborate;
subtype Level_Type is Natural;
FATAL_LEVEL : constant Level_Type := 0;
ERROR_LEVEL : constant Level_Type := 5;
WARN_LEVEL : constant Level_Type := 7;
INFO_LEVEL : constant Level_Type := 10;
DEBUG_LEVEL : constant Level_Type := 20;
-- Get the log level name.
function Get_Level_Name (Level : Level_Type) return String;
-- Get the log level from the property value
function Get_Level (Value : in String;
Default : in Level_Type := INFO_LEVEL) return Level_Type;
-- The <tt>Logging</tt> interface defines operations that can be implemented for a
-- type to report errors or messages.
type Logging is limited interface;
procedure Error (Log : in out Logging;
Message : in String) is abstract;
end Util.Log;
|
-----------------------------------------------------------------------
-- util-log -- Utility Log Package
-- Copyright (C) 2001 - 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.
-----------------------------------------------------------------------
-- = Logging =
-- The `Util.Log` package and children provide a simple logging framework inspired
-- from the Java Log4j library. It is intended to provide a subset of logging features
-- available in other languages, be flexible, extensible, small and efficient. Having
-- log messages in large applications is very helpful to understand, track and fix complex
-- issues, some of them being related to configuration issues or interaction with other
-- systems. The overhead of calling a log operation is negligeable when the log is disabled
-- as it is in the order of 30ns and reasonable for a file appender has it is in the order
-- of 5us. To use the packages described here, use the following GNAT project:
--
-- with "utilada_base";
--
-- == Using the log framework ==
-- A bit of terminology:
--
-- * A *logger* is the abstraction that provides operations to emit a message. The message
-- is composed of a text, optional formatting parameters, a log level and a timestamp.
-- * A *formatter* is the abstraction that takes the information about the log to format
-- the final message.
-- * An *appender* is the abstraction that writes the message either to a console, a file
-- or some other final mechanism.
--
-- == Logger Declaration ==
-- Similar to other logging framework such as Java Log4j and Log4cxx, it is necessary to have
-- and instance of a logger to write a log message. The logger instance holds the configuration
-- for the log to enable, disable and control the format and the appender that will receive
-- the message. The logger instance is associated with a name that is used for the
-- configuration. A good practice is to declare a `Log` instance in the package body or
-- the package private part to make available the log instance to all the package operations.
-- The instance is created by using the `Create` function. The name used for the configuration
-- is free but using the full package name is helpful to control precisely the logs.
--
-- with Util.Log.Loggers;
-- package body X.Y is
-- Log : constant Util.Log.Loggers := Util.Log.Loggers.Create ("X.Y");
-- end X.Y;
--
-- == Logger Messages ==
-- A log message is associated with a log level which is used by the logger instance to
-- decide to emit or drop the log message. To keep the logging API simple and make it easily
-- usable in the application, several operations are provided to write a message with different
-- log level.
--
-- A log message is a string that contains optional formatting markers that follow more or
-- less the Java `MessageFormat` class. A parameter is represented by a number enclosed by `{}`.
-- The first parameter is represented by `{0}`, the second by `{1}` and so on. Parameters are
-- replaced in the final message only when the message is enabled by the log configuration.
-- The use of parameters allows to avoid formatting the log message when the log is not used.
--
-- The example below shows several calls to emit a log message with different levels:
--
-- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist");
-- Log.Warn ("The file {0} is empty", Path);
-- Log.Info ("Opening file {0}", Path);
-- Log.Debug ("Reading line {0}", Line);
--
-- The logger also provides a special `Error` procedure that accepts an Ada exception
-- occurence as parameter. The exception name and message are printed together with
-- the error message. It is also possible to activate a complete traceback of the
-- exception and report it in the error message. With this mechanism, an exception
-- can be handled and reported easily:
--
-- begin
-- ...
-- exception
-- when E : others =>
-- Log.Error ("Something bad occurred", E, Trace => True);
-- end;
--
-- == Log Configuration ==
-- The log configuration uses property files close to the Apache Log4j and to the
-- Apache Log4cxx configuration files.
-- The configuration file contains several parts to configure the logging framework:
--
-- * First, the *appender* configuration indicates the appender that exists and can receive
-- a log message.
-- * Second, a root configuration allows to control the default behavior of the logging
-- framework. The root configuration controls the default log level as well as the
-- appenders that can be used.
-- * Last, a logger configuration is defined to control the logging level more precisely
-- for each logger.
--
-- Here is a simple log configuration that creates a file appender where log messages are
-- written. The file appender is given the name `result` and is configured to write the
-- messages in the file `my-log-file.log`. The file appender will use the `level-message`
-- format for the layout of messages. Last is the configuration of the `X.Y` logger
-- that will enable only messages starting from the `WARN` level.
--
-- log4j.rootCategory=DEBUG,result
-- log4j.appender.result=File
-- log4j.appender.result.File=my-log-file.log
-- log4j.appender.result.layout=level-message
-- log4j.logger.X.Y=WARN
--
-- By default when the `layout` is not set or has an invalid value, the full message is
-- reported and the generated log messages will look as follows:
--
-- [2018-02-07 20:39:51] ERROR - X.Y - Cannot open file test.txt: File does not exist
-- [2018-02-07 20:39:51] WARN - X.Y - The file test.txt is empty
-- [2018-02-07 20:39:51] INFO - X.Y - Opening file test.txt
-- [2018-02-07 20:39:51] DEBUG - X.Y - Reading line ......
--
-- When the `layout` configuration is set to `data-level-message`, the message is printed
-- with the date and message level.
--
-- [2018-02-07 20:39:51] ERROR: Cannot open file test.txt: File does not exist
-- [2018-02-07 20:39:51] WARN : The file test.txt is empty
-- [2018-02-07 20:39:51] INFO : X.Y - Opening file test.txt
-- [2018-02-07 20:39:51] DEBUG: X.Y - Reading line ......
--
-- When the `layout` configuration is set to `level-message`, only the message and its
-- level are reported.
--
-- ERROR: Cannot open file test.txt: File does not exist
-- WARN : The file test.txt is empty
-- INFO : X.Y - Opening file test.txt
-- DEBUG: X.Y - Reading line ......
--
-- The last possible configuration for `layout` is `message` which only prints the message.
--
-- Cannot open file test.txt: File does not exist
-- The file test.txt is empty
-- Opening file test.txt
-- Reading line ......
--
-- The `Console` appender recognises the following configurations:
--
-- | Name | Description |
-- | -------------- | -------------------------------------------------------------- |
-- | layout | Defines the format of the message printed by the appender. |
-- | level | Defines the minimum level above which messages are printed. |
-- | stderr | When 'true' or '1', use the console standard error, |
-- | | by default the appender uses the standard output |
--
-- The `File` appender recognises the following configurations:
--
-- | Name | Description |
-- | -------------- | -------------------------------------------------------------- |
-- | layout | Defines the format of the message printed by the appender. |
-- | level | Defines the minimum level above which messages are printed. |
-- | File | The path used by the appender to create the output file. |
-- | append | When 'true' or '1', the file is opened in append mode otherwise |
-- | | it is truncated (the default is to truncate). |
-- | immediateFlush | When 'true' or '1', the file is flushed after each message log. |
-- | | Immediate flush is useful in some situations to have the log file |
-- | | updated immediately at the expense of slowing down the processing |
-- | | of logs. |
package Util.Log is
pragma Preelaborate;
subtype Level_Type is Natural;
FATAL_LEVEL : constant Level_Type := 0;
ERROR_LEVEL : constant Level_Type := 5;
WARN_LEVEL : constant Level_Type := 7;
INFO_LEVEL : constant Level_Type := 10;
DEBUG_LEVEL : constant Level_Type := 20;
-- Get the log level name.
function Get_Level_Name (Level : Level_Type) return String;
-- Get the log level from the property value
function Get_Level (Value : in String;
Default : in Level_Type := INFO_LEVEL) return Level_Type;
-- The <tt>Logging</tt> interface defines operations that can be implemented for a
-- type to report errors or messages.
type Logging is limited interface;
procedure Error (Log : in out Logging;
Message : in String) is abstract;
end Util.Log;
|
Add some documentation for the configuration of log appenders
|
Add some documentation for the configuration of log appenders
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
4eddf1590f7c0a20131e075223e7cff8d04059a1
|
resources/scripts/scrape/baidu.ads
|
resources/scripts/scrape/baidu.ads
|
-- Copyright 2017 Jeff Foley. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
local url = require("url")
local json = require("json")
name = "Baidu"
type = "scrape"
function start()
setratelimit(1)
end
function vertical(ctx, domain)
for i=0,100,10 do
checkratelimit()
local ok = scrape(ctx, {['url']=buildurl(domain, i)})
if not ok then
break
end
end
end
function buildurl(domain, pagenum)
local query = "site:" .. domain .. " -site:www." .. domain
local params = {
wd=query,
oq=query,
pn=pagenum,
}
return "https://www.baidu.com/s?" .. url.build_query_string(params)
end
|
-- Copyright 2017 Jeff Foley. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
local url = require("url")
local json = require("json")
name = "Baidu"
type = "scrape"
function start()
setratelimit(1)
end
function vertical(ctx, domain)
for i=0,10 do
checkratelimit()
local ok = scrape(ctx, {['url']=buildurl(domain, i)})
if not ok then
break
end
end
end
function buildurl(domain, pagenum)
local query = "site:" .. domain .. " -site:www." .. domain
local params = {
wd=query,
oq=query,
pn=pagenum,
}
return "https://www.baidu.com/s?" .. url.build_query_string(params)
end
|
Update baidu.ads
|
Update baidu.ads
|
Ada
|
apache-2.0
|
caffix/amass,caffix/amass
|
c73b2a83da61a709a748b9a3aa4ddad94be9ac66
|
src/gen-commands-info.ads
|
src/gen-commands-info.ads
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Info is
-- ------------------------------
-- Project Information Command
-- ------------------------------
-- This command collects information about the project and print it.
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Info;
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Info is
-- ------------------------------
-- Project Information Command
-- ------------------------------
-- This command collects information about the project and print it.
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Name : in String;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Info;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
5a14782cdd3ef5481185b0745ca711220bfc24b9
|
src/gen-artifacts-docs-markdown.adb
|
src/gen-artifacts-docs-markdown.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body Gen.Artifacts.Docs.Markdown is
function Has_Scheme (Link : in String) return Boolean;
-- ------------------------------
-- 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) & ".md";
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, "# " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- Return True if the link has either a http:// or a https:// scheme.
-- ------------------------------
function Has_Scheme (Link : in String) return Boolean is
begin
if Link'Length < 8 then
return False;
elsif Link (Link'First .. Link'First + 6) = "http://" then
return True;
elsif Link (Link'First .. Link'First + 7) = "https://" then
return True;
else
return False;
end if;
end Has_Scheme;
-- ------------------------------
-- Write a line doing some link transformation for Markdown.
-- ------------------------------
procedure Write_Text (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Text : in String) is
Pos : Natural;
Start : Natural := Text'First;
End_Pos : Natural;
Last_Pos : Natural;
begin
loop
Pos := Util.Strings.Index (Text, '[', Start);
if Pos = 0 or else Pos = Text'Last then
Ada.Text_IO.Put (File, Text (Start .. Text'Last));
return;
end if;
Ada.Text_IO.Put (File, Text (Start .. Pos));
if Text (Pos + 1) = '[' then
Start := Pos + 1;
Pos := Util.Strings.Index (Text, ']', Pos + 2);
if Pos = 0 then
Ada.Text_IO.Put (File, Text (Start .. Text'Last));
return;
end if;
Ada.Text_IO.Put (File, Text (Start .. Pos));
Start := Pos + 1;
else
Pos := Pos + 1;
End_Pos := Pos;
while End_Pos < Text'Last and Text (End_Pos) /= ' ' loop
End_Pos := End_Pos + 1;
end loop;
Last_Pos := End_Pos;
while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop
Last_Pos := Last_Pos + 1;
end loop;
if Has_Scheme (Text (Pos .. End_Pos)) then
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "(");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, ")");
else
Last_Pos := Last_Pos - 1;
Ada.Text_IO.Put (File, "[");
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "|");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, "]");
end if;
Start := Last_Pos + 1;
end if;
end loop;
end Write_Text;
-- ------------------------------
-- 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;
if Formatter.Mode = L_START_CODE and then Line'Length > 2
and then Line (Line'First .. Line'First + 1) = " "
then
Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last));
elsif Formatter.Mode = L_TEXT then
Formatter.Write_Text (File, Line);
Ada.Text_IO.New_Line (File);
else
Ada.Text_IO.Put_Line (File, Line);
end if;
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;
Formatter.Mode := Line.Kind;
when L_LIST_ITEM =>
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
when L_START_CODE =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "```");
when L_END_CODE =>
Formatter.Mode := L_TEXT;
Formatter.Write_Line (File, "```");
when L_TEXT =>
Formatter.Write_Line (File, Line.Content);
when L_HEADER_1 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "# " & Line.Content);
when L_HEADER_2 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "## " & Line.Content);
when L_HEADER_3 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "### " & Line.Content);
when L_HEADER_4 =>
Formatter.Mode := Line.Kind;
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,
"[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *"
& Source & "*");
end Finish_Document;
end Gen.Artifacts.Docs.Markdown;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body Gen.Artifacts.Docs.Markdown is
function Has_Scheme (Link : in String) return Boolean;
-- ------------------------------
-- 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) & ".md";
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, "# " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- Return True if the link has either a http:// or a https:// scheme.
-- ------------------------------
function Has_Scheme (Link : in String) return Boolean is
begin
if Link'Length < 8 then
return False;
elsif Link (Link'First .. Link'First + 6) = "http://" then
return True;
elsif Link (Link'First .. Link'First + 7) = "https://" then
return True;
else
return False;
end if;
end Has_Scheme;
-- ------------------------------
-- Write a line doing some link transformation for Markdown.
-- ------------------------------
procedure Write_Text (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Text : in String) is
Pos : Natural;
Start : Natural := Text'First;
End_Pos : Natural;
Last_Pos : Natural;
begin
loop
Pos := Util.Strings.Index (Text, '[', Start);
if Pos = 0 or else Pos = Text'Last then
Ada.Text_IO.Put (File, Text (Start .. Text'Last));
return;
end if;
Ada.Text_IO.Put (File, Text (Start .. Pos));
if Text (Pos + 1) = '[' then
Start := Pos + 1;
Pos := Util.Strings.Index (Text, ']', Pos + 2);
if Pos = 0 then
Ada.Text_IO.Put (File, Text (Start .. Text'Last));
return;
end if;
Ada.Text_IO.Put (File, Text (Start .. Pos));
Start := Pos + 1;
else
Pos := Pos + 1;
End_Pos := Pos;
while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop
End_Pos := End_Pos + 1;
end loop;
Last_Pos := End_Pos;
while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop
Last_Pos := Last_Pos + 1;
end loop;
if Has_Scheme (Text (Pos .. End_Pos)) then
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "(");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, ")");
else
Last_Pos := Last_Pos - 1;
Ada.Text_IO.Put (File, "[");
Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos));
Ada.Text_IO.Put (File, "|");
Ada.Text_IO.Put (File, Text (Pos .. End_Pos));
Ada.Text_IO.Put (File, "]");
end if;
Start := Last_Pos + 1;
end if;
end loop;
end Write_Text;
-- ------------------------------
-- 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;
if Formatter.Mode = L_START_CODE and then Line'Length > 2
and then Line (Line'First .. Line'First + 1) = " "
then
Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last));
elsif Formatter.Mode = L_TEXT then
Formatter.Write_Text (File, Line);
Ada.Text_IO.New_Line (File);
else
Ada.Text_IO.Put_Line (File, Line);
end if;
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;
Formatter.Mode := Line.Kind;
when L_LIST_ITEM =>
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
when L_START_CODE =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "```");
when L_END_CODE =>
Formatter.Mode := L_TEXT;
Formatter.Write_Line (File, "```");
when L_TEXT =>
Formatter.Write_Line (File, Line.Content);
when L_HEADER_1 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "# " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_2 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "## " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_3 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "### " & Line.Content);
Formatter.Mode := L_TEXT;
when L_HEADER_4 =>
Formatter.Mode := Line.Kind;
Formatter.Write_Line (File, "#### " & Line.Content);
Formatter.Mode := L_TEXT;
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,
"[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *"
& Source & "*");
end Finish_Document;
end Gen.Artifacts.Docs.Markdown;
|
Fix and improve the generated markdown documentation
|
Fix and improve the generated markdown documentation
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
1eac03ac1940e85c110d85c03ac7121a9108202c
|
regtests/ado-tests.adb
|
regtests/ado-tests.adb
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with AUnit;
with AUnit.Test_Caller;
with ADO.Statements;
with ADO.Objects;
with ADO.Sessions;
with Regtests;
with Regtests.Simple.Model;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
package body ADO.Tests is
use Util.Log;
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests");
package Caller is new AUnit.Test_Caller (Test);
procedure Fail (T : in Test; Message : in String);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Fail (T : in Test; Message : in String) is
begin
T.Assert (False, Message);
end Fail;
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
Fail (T, "Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
Fail (T, "Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
Assert (T, Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Suite.Add_Test (Caller.Create ("Test Object_Ref.Load", Test_Load'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Save", Test_Create_Load'Access));
Suite.Add_Test (Caller.Create ("Test Master_Connection init error", Test_Not_Open'Access));
Suite.Add_Test (Caller.Create ("Test Sequences.Factory", Test_Allocate'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access));
Suite.Add_Test (Caller.Create ("Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access));
end Add_Tests;
end ADO.Tests;
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with AUnit;
with AUnit.Test_Caller;
with ADO.Statements;
with ADO.Objects;
with ADO.Sessions;
with Regtests;
with Regtests.Simple.Model;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
package body ADO.Tests is
use Util.Log;
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests");
package Caller is new AUnit.Test_Caller (Test);
procedure Fail (T : in Test; Message : in String);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Fail (T : in Test; Message : in String) is
begin
T.Assert (False, Message);
end Fail;
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
Fail (T, "Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
Fail (T, "Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Suite.Add_Test (Caller.Create ("Test Object_Ref.Load", Test_Load'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Save", Test_Create_Load'Access));
Suite.Add_Test (Caller.Create ("Test Master_Connection init error", Test_Not_Open'Access));
Suite.Add_Test (Caller.Create ("Test Sequences.Factory", Test_Allocate'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access));
Suite.Add_Test (Caller.Create ("Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access));
Suite.Add_Test (Caller.Create ("Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access));
end Add_Tests;
end ADO.Tests;
|
Fix compilation with GNAT 2011
|
Fix compilation with GNAT 2011
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
baef8b0c0a974dcedbc377b14832707f9cf8f244
|
src/security-policies.adb
|
src/security-policies.adb
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
begin
null;
end Add_Policy;
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
begin
null;
end Add_Permission;
-- 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 Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
package Role_Config is
new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
pragma Warnings (Off, Role_Config);
begin
Log.Info ("Reading policy file {0}", File);
Reader.Parse (File);
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
begin
null;
end Finalize;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
begin
null;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- 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 Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
-- package Role_Config is
-- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
-- pragma Warnings (Off, Role_Config);
begin
Log.Info ("Reading policy file {0}", File);
Reader.Parse (File);
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
begin
null;
end Finalize;
end Security.Policies;
|
Implement Add_Permission
|
Implement Add_Permission
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
ecf4cfcb0b9933bee3dc2d16e87a9b7cb53aa533
|
regtests/util-log-tests.adb
|
regtests/util-log-tests.adb
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
use Util;
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
pragma Unreferenced (T);
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Log;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
end Test_Log_Perf;
-- Test appending the log on several log files
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
use Util;
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
pragma Unreferenced (T);
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Log;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
end Test_Log_Perf;
-- ------------------------------
-- Test appending the log on several log files
-- ------------------------------
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_File_Appender_Modes (T : in out Test) is
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-append.log");
Props.Set ("log4j.appender.test.append", "true");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Error ("This is the error test message");
end;
Props.Set ("log4j.appender.test_append", "File");
Props.Set ("log4j.appender.test_append.File", "test-append.log");
Props.Set ("log4j.appender.test_append.append", "true");
Props.Set ("log4j.appender.test_append.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
declare
L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file");
begin
L1.Info ("Writing a info message");
L2.Info ("{0}: {1}", "Parameter", "Value");
L1.Info ("Done");
L2.Error ("This is the error test2 message");
end;
Props.Set ("log4j.appender.test_append.append", "plop");
Props.Set ("log4j.appender.test_append.immediateFlush", "falsex");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
end Test_File_Appender_Modes;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)",
Test_File_Appender_Modes'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
Add a test to check the immediateFlush and append behavior of the file appender
|
Add a test to check the immediateFlush and append behavior of the file appender
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f4208d7065d4e569e154178f79708580c51a2bf4
|
regtests/util-log-tests.ads
|
regtests/util-log-tests.ads
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- 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 Util.Tests;
package Util.Log.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Log_Perf (T : in out Test);
procedure Test_Log (T : in out Test);
procedure Test_File_Appender (T : in out Test);
procedure Test_List_Appender (T : in out Test);
-- Test file appender with different modes.
procedure Test_File_Appender_Modes (T : in out Test);
end Util.Log.Tests;
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 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 Util.Tests;
package Util.Log.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Log_Perf (T : in out Test);
procedure Test_Log (T : in out Test);
procedure Test_File_Appender (T : in out Test);
procedure Test_List_Appender (T : in out Test);
procedure Test_Console_Appender (T : in out Test);
-- Test file appender with different modes.
procedure Test_File_Appender_Modes (T : in out Test);
end Util.Log.Tests;
|
Add Test_Console_Appender procedure
|
Add Test_Console_Appender procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d9f6e4deb94cfb74b0da67837944cb9a6fa5bfaf
|
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 Util.Test_Caller;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Images.Modules;
package body AWA.Images.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Images.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Images.Create_Image",
Test_Create_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Get_Sizes",
Test_Get_Sizes'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, 0, 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;
end AWA.Images.Modules.Tests;
|
-----------------------------------------------------------------------
-- 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 Util.Test_Caller;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Images.Modules;
package body AWA.Images.Modules.Tests is
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);
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, 0, 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;
end AWA.Images.Modules.Tests;
|
Implement the Test_Scale to check the Scale operation and register the new test
|
Implement the Test_Scale to check the Scale operation and register the new test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a333ef7517c4d3dcffae9d81645e2c2612b4bccd
|
src/asf-streams.ads
|
src/asf-streams.ads
|
-----------------------------------------------------------------------
-- ASF.Streams -- Print streams for servlets
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Util.Streams;
with Util.Streams.Texts;
with EL.Objects;
package ASF.Streams is
pragma Preelaborate;
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is limited new Util.Streams.Output_Stream with private;
procedure Initialize (Stream : in out Print_Stream;
To : in Util.Streams.Texts.Print_Stream_Access);
-- Initialize the stream
procedure Initialize (Stream : in out Print_Stream;
To : in Print_Stream'Class);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write a string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw character on the stream.
procedure Write (Stream : in out Print_Stream;
Char : in Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in String);
-- Write the object converted into a string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in EL.Objects.Object);
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Print_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
procedure Flush (Stream : in out Print_Stream);
private
type Print_Stream is new Ada.Finalization.Limited_Controlled
and Util.Streams.Output_Stream with record
Target : Util.Streams.Texts.Print_Stream_Access;
end record;
end ASF.Streams;
|
-----------------------------------------------------------------------
-- ASF.Streams -- Print streams for servlets
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Util.Streams;
with Util.Streams.Texts;
with EL.Objects;
package ASF.Streams is
pragma Preelaborate;
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is new Ada.Finalization.Limited_Controlled
and Util.Streams.Output_Stream with private;
procedure Initialize (Stream : in out Print_Stream;
To : in Util.Streams.Texts.Print_Stream_Access);
-- Initialize the stream
procedure Initialize (Stream : in out Print_Stream;
To : in Print_Stream'Class);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write a string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw character on the stream.
procedure Write (Stream : in out Print_Stream;
Char : in Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in String);
-- Write the object converted into a string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in EL.Objects.Object);
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Print_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
procedure Flush (Stream : in out Print_Stream);
private
type Print_Stream is new Ada.Finalization.Limited_Controlled
and Util.Streams.Output_Stream with record
Target : Util.Streams.Texts.Print_Stream_Access;
end record;
end ASF.Streams;
|
Fix compilation with gcc 4.3
|
Fix compilation with gcc 4.3
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a1fdc42cfcc130b8332823896e676eb1a21ed9fb
|
matp/src/memory/mat-memory-targets.ads
|
matp/src/memory/mat-memory-targets.ads
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- 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 MAT.Frames;
with MAT.Events.Probes;
with MAT.Memory.Tools;
with MAT.Expressions;
package MAT.Memory.Targets is
-- Define some global statistics about the memory slots.
type Memory_Stat is record
Thread_Count : Natural := 0;
Total_Alloc : MAT.Types.Target_Size := 0;
Total_Free : MAT.Types.Target_Size := 0;
Malloc_Count : Natural := 0;
Free_Count : Natural := 0;
Realloc_Count : Natural := 0;
Used_Count : Natural := 0;
end record;
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
procedure Initialize (Memory : in out Target_Memory;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class);
-- Add the memory region from the list of memory region managed by the program.
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info);
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in out Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation;
Old_Size : out MAT.Types.Target_Size);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
private
protected type Memory_Allocator is
-- Add the memory region from the list of memory region managed by the program.
procedure Add_Region (Region : in Region_Info);
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in out Allocation);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation;
Old_Size : out MAT.Types.Target_Size);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Result : out Memory_Stat);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Regions : Region_Info_Map;
Stats : Memory_Stat;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Manager : MAT.Events.Probes.Probe_Manager_Type_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- 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 MAT.Frames;
with MAT.Events.Probes;
with MAT.Memory.Tools;
with MAT.Expressions;
package MAT.Memory.Targets is
-- Define some global statistics about the memory slots.
type Memory_Stat is record
Thread_Count : Natural := 0;
Total_Alloc : MAT.Types.Target_Size := 0;
Total_Free : MAT.Types.Target_Size := 0;
Malloc_Count : Natural := 0;
Free_Count : Natural := 0;
Realloc_Count : Natural := 0;
Used_Count : Natural := 0;
end record;
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
procedure Initialize (Memory : in out Target_Memory;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class);
-- Add the memory region from the list of memory region managed by the program.
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info);
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation;
Size : out MAT.Types.Target_Size;
By : out MAT.Events.Targets.Event_Id_Type);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation;
Old_Size : out MAT.Types.Target_Size;
By : out MAT.Events.Targets.Event_Id_Type);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
private
protected type Memory_Allocator is
-- Add the memory region from the list of memory region managed by the program.
procedure Add_Region (Region : in Region_Info);
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map);
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation;
Size : out MAT.Types.Target_Size;
By : out MAT.Events.Targets.Event_Id_Type);
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation;
Old_Size : out MAT.Types.Target_Size;
By : out MAT.Events.Targets.Event_Id_Type);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Result : out Memory_Stat);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Regions : Region_Info_Map;
Stats : Memory_Stat;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Manager : MAT.Events.Probes.Probe_Manager_Type_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
Change Probe_Realloc and Probe_Free to return the size of the memory slot and the event ID that previously allocated that memory slot
|
Change Probe_Realloc and Probe_Free to return the size of the memory
slot and the event ID that previously allocated that memory slot
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
c0c0e5230b4ee8e40fce29ce9cc9a98aca90fc1f
|
test_all.adb
|
test_all.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2011, 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. --
------------------------------------------------------------------------------
-----------------------------------------------------------------------
-- Test_All is a binary gathering all tests from Natools components. --
-----------------------------------------------------------------------
with Ada.Command_Line;
with Ada.Text_IO;
with Natools.Getopt_Long_Tests;
with Natools.Tests.Text_IO;
procedure Test_All is
Report : Natools.Tests.Text_IO.Text_Reporter;
begin
Ada.Text_IO.Set_Line_Length (80);
Report.Section ("All Tests");
Report.Section ("Getopt_Long");
Natools.Getopt_Long_Tests.All_Tests (Report);
Report.End_Section;
Natools.Tests.Text_IO.Print_Results (Report.Total_Results);
declare
Results : constant Natools.Tests.Result_Summary := Report.Total_Results;
begin
if Results (Natools.Tests.Fail) > 0 or
Results (Natools.Tests.Error) > 0
then
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
else
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
end if;
end;
Report.End_Section;
end Test_All;
|
------------------------------------------------------------------------------
-- Copyright (c) 2011, 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. --
------------------------------------------------------------------------------
-----------------------------------------------------------------------
-- Test_All is a binary gathering all tests from Natools components. --
-----------------------------------------------------------------------
with Ada.Command_Line;
with Ada.Text_IO;
with Natools.Chunked_Strings.Tests;
with Natools.Getopt_Long_Tests;
with Natools.Tests.Text_IO;
procedure Test_All is
package Uneven_Chunked_Strings is new Natools.Chunked_Strings
(Default_Allocation_Unit => 7,
Default_Chunk_Size => 15);
package Uneven_Chunked_Strings_Tests is new Uneven_Chunked_Strings.Tests;
package Even_Chunked_Strings is new Natools.Chunked_Strings
(Default_Allocation_Unit => 6,
Default_Chunk_Size => 18);
package Even_Chunked_Strings_Tests is new Even_Chunked_Strings.Tests;
package Single_Chunked_Strings is new Natools.Chunked_Strings
(Default_Allocation_Unit => 10,
Default_Chunk_Size => 10);
package Single_Chunked_Strings_Tests is new Single_Chunked_Strings.Tests;
Report : Natools.Tests.Text_IO.Text_Reporter;
begin
Ada.Text_IO.Set_Line_Length (80);
Report.Section ("All Tests");
Report.Section ("Chunked_String with uneven allocation unit");
Uneven_Chunked_Strings_Tests.All_Tests (Report);
Report.End_Section;
Report.Section ("Chunked_String with even allocation unit");
Even_Chunked_Strings_Tests.All_Tests (Report);
Report.End_Section;
Report.Section ("Chunked_String with single allocation unit");
Single_Chunked_Strings_Tests.All_Tests (Report);
Report.End_Section;
Report.Section ("Getopt_Long");
Natools.Getopt_Long_Tests.All_Tests (Report);
Report.End_Section;
Natools.Tests.Text_IO.Print_Results (Report.Total_Results);
declare
Results : constant Natools.Tests.Result_Summary := Report.Total_Results;
begin
if Results (Natools.Tests.Fail) > 0 or
Results (Natools.Tests.Error) > 0
then
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
else
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
end if;
end;
Report.End_Section;
end Test_All;
|
add Chunked_String test suite
|
test_all: add Chunked_String test suite
|
Ada
|
isc
|
faelys/natools
|
420f02951be11bc788cd6a838ab51118ae1ea628
|
src/asf-locales.ads
|
src/asf-locales.ads
|
-----------------------------------------------------------------------
-- asf-locales -- Locale support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Maps;
with Util.Properties.Bundles;
with Util.Locales;
with ASF.Beans;
with ASF.Requests;
-- The <b>ASF.Locales</b> package manages everything related to the locales.
-- It allows to register bundles that contains localized messages and be able
-- to use them in the facelet views.
package ASF.Locales is
-- To keep the implementation simple, the maximum list of supported locales by the
-- application is limited to 32. Most applications support 1 or 2 languages.
MAX_SUPPORTED_LOCALES : constant Positive := 32;
type Bundle is new Util.Properties.Bundles.Manager
and Util.Beans.Basic.Readonly_Bean with null record;
type Bundle_Access is access all Bundle;
type Factory is limited private;
-- Initialize the locale support by using the configuration properties.
-- Properties matching the pattern: <b>bundles</b>.<i>var-name</i>=<i>bundle-name</i>
-- are used to register bindings linking a facelet variable <i>var-name</i>
-- to the resource bundle <i>bundle-name</i>.
procedure Initialize (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Config : in Util.Properties.Manager'Class);
-- Register a bundle and bind it to a facelet variable.
procedure Register (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Name : in String;
Bundle : in String);
-- Load the resource bundle identified by the <b>Name</b> and for the given
-- <b>Locale</b>.
procedure Load_Bundle (Fac : in out Factory;
Name : in String;
Locale : in String;
Result : out Bundle);
-- Compute the locale that must be used according to the <b>Accept-Language</b> request
-- header and the application supported locales.
function Calculate_Locale (Fac : in Factory;
Req : in ASF.Requests.Request'Class)
return Util.Locales.Locale;
-- Get the list of supported locales for this application.
function Get_Supported_Locales (From : in Factory)
return Util.Locales.Locale_Array;
-- Add the locale to the list of supported locales.
procedure Add_Supported_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale);
-- Get the default locale defined by the application.
function Get_Default_Locale (From : in Factory) return Util.Locales.Locale;
-- Set the default locale defined by the application.
procedure Set_Default_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale);
private
type Factory is limited record
Factory : aliased Util.Properties.Bundles.Loader;
Bundles : Util.Strings.Maps.Map;
-- The default locale used by the application.
Default_Locale : Util.Locales.Locale := Util.Locales.ENGLISH;
-- Number of supported locales.
Nb_Locales : Natural := 0;
-- The list of supported locales.
Locales : Util.Locales.Locale_Array (1 .. MAX_SUPPORTED_LOCALES);
end record;
type Factory_Access is access all Factory;
end ASF.Locales;
|
-----------------------------------------------------------------------
-- asf-locales -- Locale support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Basic;
with Util.Strings.Maps;
with Util.Properties.Bundles;
with Util.Locales;
with ASF.Beans;
with ASF.Requests;
-- The <b>ASF.Locales</b> package manages everything related to the locales.
-- It allows to register bundles that contains localized messages and be able
-- to use them in the facelet views.
package ASF.Locales is
-- To keep the implementation simple, the maximum list of supported locales by the
-- application is limited to 32. Most applications support 1 or 2 languages.
MAX_SUPPORTED_LOCALES : constant Positive := 32;
type Bundle is new Util.Properties.Bundles.Manager
and Util.Beans.Basic.Readonly_Bean with null record;
type Bundle_Access is access all Bundle;
type Factory is limited private;
-- Initialize the locale support by using the configuration properties.
-- Properties matching the pattern: <b>bundles</b>.<i>var-name</i>=<i>bundle-name</i>
-- are used to register bindings linking a facelet variable <i>var-name</i>
-- to the resource bundle <i>bundle-name</i>.
procedure Initialize (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Config : in Util.Properties.Manager'Class);
-- Register a bundle and bind it to a facelet variable.
procedure Register (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Name : in String;
Bundle : in String);
-- Load the resource bundle identified by the <b>Name</b> and for the given
-- <b>Locale</b>.
procedure Load_Bundle (Fac : in out Factory;
Name : in String;
Locale : in String;
Result : out Bundle);
-- Compute the locale that must be used according to the <b>Accept-Language</b> request
-- header and the application supported locales.
function Calculate_Locale (Fac : in Factory;
Req : in ASF.Requests.Request'Class)
return Util.Locales.Locale;
-- Get the list of supported locales for this application.
function Get_Supported_Locales (From : in Factory)
return Util.Locales.Locale_Array;
-- Add the locale to the list of supported locales.
procedure Add_Supported_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale);
-- Get the default locale defined by the application.
function Get_Default_Locale (From : in Factory) return Util.Locales.Locale;
-- Set the default locale defined by the application.
procedure Set_Default_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale);
private
type Factory is limited record
Factory : aliased Util.Properties.Bundles.Loader;
Bundles : Util.Strings.Maps.Map;
-- The default locale used by the application.
Default_Locale : Util.Locales.Locale := Util.Locales.ENGLISH;
-- Number of supported locales.
Nb_Locales : Natural := 0;
-- The list of supported locales.
Locales : Util.Locales.Locale_Array (1 .. MAX_SUPPORTED_LOCALES);
end record;
type Factory_Access is access all Factory;
end ASF.Locales;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
915cd14f593565b3945778b5d8382fbbd7ea60b3
|
awa/plugins/awa-tags/src/awa-tags-modules.ads
|
awa/plugins/awa-tags/src/awa-tags-modules.ads
|
-----------------------------------------------------------------------
-- awa-tags-modules -- Module awa-tags
-- 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 ADO.Sessions;
with Util.Strings.Vectors;
with AWA.Modules;
package AWA.Tags.Modules is
-- The name under which the module is registered.
NAME : constant String := "tags";
-- ------------------------------
-- Module awa-tags
-- ------------------------------
type Tag_Module is new AWA.Modules.Module with private;
type Tag_Module_Access is access all Tag_Module'Class;
-- Initialize the tags module.
overriding
procedure Initialize (Plugin : in out Tag_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the tags module.
function Get_Tag_Module return Tag_Module_Access;
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>. The permission represented by <tt>Permission</tt> is checked
-- to make sure the current user can add the tag. If the permission is granted, the
-- tag represented by <tt>Tag</tt> is associated with the said database entity.
procedure Add_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String);
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove the tag.
procedure Remove_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String);
-- Remove the tags defined by the <tt>Deleted</tt> tag list and add the tags defined
-- in the <tt>Added</tt> tag list. The tags are associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove or add the tag.
procedure Update_Tags (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Added : in Util.Strings.Vectors.Vector;
Deleted : in Util.Strings.Vectors.Vector);
-- Find the tag identifier associated with the given tag.
-- Return NO_IDENTIFIER if there is no such tag.
procedure Find_Tag_Id (Session : in out ADO.Sessions.Session'Class;
Tag : in String;
Result : out ADO.Identifier);
private
type Tag_Module is new AWA.Modules.Module with null record;
end AWA.Tags.Modules;
|
-----------------------------------------------------------------------
-- awa-tags-modules -- Module awa-tags
-- 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 ADO.Sessions;
with Util.Strings.Vectors;
with AWA.Modules;
-- == Integration ==
-- The <tt>Tag_Module</tt> manages the tags associated with entities. It provides operations
-- that are used by the tag beans and the <tt>awa:tagList</tt> component to manage the tags.
-- An instance of the <tt>Tag_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
-- Tag_Module : aliased AWA.Votes.Modules.Tag_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Tags.Modules.NAME,
-- URI => "tags",
-- Module => App.Tag_Module'Access);
package AWA.Tags.Modules is
-- The name under which the module is registered.
NAME : constant String := "tags";
-- ------------------------------
-- Module awa-tags
-- ------------------------------
type Tag_Module is new AWA.Modules.Module with private;
type Tag_Module_Access is access all Tag_Module'Class;
-- Initialize the tags module.
overriding
procedure Initialize (Plugin : in out Tag_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the tags module.
function Get_Tag_Module return Tag_Module_Access;
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>. The permission represented by <tt>Permission</tt> is checked
-- to make sure the current user can add the tag. If the permission is granted, the
-- tag represented by <tt>Tag</tt> is associated with the said database entity.
procedure Add_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String);
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove the tag.
procedure Remove_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String);
-- Remove the tags defined by the <tt>Deleted</tt> tag list and add the tags defined
-- in the <tt>Added</tt> tag list. The tags are associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove or add the tag.
procedure Update_Tags (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Added : in Util.Strings.Vectors.Vector;
Deleted : in Util.Strings.Vectors.Vector);
-- Find the tag identifier associated with the given tag.
-- Return NO_IDENTIFIER if there is no such tag.
procedure Find_Tag_Id (Session : in out ADO.Sessions.Session'Class;
Tag : in String;
Result : out ADO.Identifier);
private
type Tag_Module is new AWA.Modules.Module with null record;
end AWA.Tags.Modules;
|
Document how to integrate the Tag_Module in the application
|
Document how to integrate the Tag_Module in the application
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
48688eb8de26db0bcf86898de943eb2c2ec6dab4
|
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.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 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 = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
elsif Name = "title" then
From.Set_Title (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;
end Save;
-- 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;
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.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 From.Is_Null then
return Util.Beans.Objects.Null_Object;
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);
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;
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;
|
Implement the Load procedure to load the wiki page Implement the Get_Value and Set_Value to get/set wiki page content
|
Implement the Load procedure to load the wiki page
Implement the Get_Value and Set_Value to get/set wiki page content
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
befb3eef4ee65dcc0220c04027f8c49dd1a19e40
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "2";
synth_version_minor : constant String := "04";
copyright_years : constant String := "2015-2018";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "2";
synth_version_minor : constant String := "05";
copyright_years : constant String := "2015-2018";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
Bump version in preparation for release
|
Bump version in preparation for release
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
c417097c398b3f70e60f203998b1a67bd6039caa
|
src/gen-model-enums.adb
|
src/gen-model-enums.adb
|
-----------------------------------------------------------------------
-- gen-model-enums -- Enum definitions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Model.Enums is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Value_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "value" then
return Util.Beans.Objects.To_Object (From.Number);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Enum_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "values" then
return From.Values_Bean;
elsif Name = "name" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "isEnum" then
return Util.Beans.Objects.To_Object (True);
elsif Name = "sqlType" then
return Util.Beans.Objects.To_Object (From.Sql_Type);
else
return Mappings.Mapping_Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Compare two enum literals.
-- ------------------------------
function "<" (Left, Right : in Value_Definition_Access) return Boolean is
begin
return Left.Number < Right.Number;
end "<";
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Enum_Definition) is
begin
O.Target := O.Type_Name;
O.Values.Sort;
end Prepare;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Enum_Definition) is
begin
O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Add an enum value to this enum definition and return the new value.
-- ------------------------------
procedure Add_Value (Enum : in out Enum_Definition;
Name : in String;
Value : out Value_Definition_Access) is
begin
Value := new Value_Definition;
Value.Name := To_Unbounded_String (Name);
Value.Number := Enum.Values.Get_Count;
Enum.Values.Append (Value);
end Add_Value;
-- ------------------------------
-- Create an enum with the given name.
-- ------------------------------
function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is
Enum : constant Enum_Definition_Access := new Enum_Definition;
begin
Enum.Name := Name;
declare
Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1);
Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name));
else
Enum.Pkg_Name := To_Unbounded_String ("ADO");
Enum.Type_Name := Enum.Name;
end if;
end;
return Enum;
end Create_Enum;
end Gen.Model.Enums;
|
-----------------------------------------------------------------------
-- gen-model-enums -- Enum definitions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Model.Enums is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Value_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "value" then
return Util.Beans.Objects.To_Object (From.Number);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Enum_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "values" then
return From.Values_Bean;
elsif Name = "name" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "isEnum" then
return Util.Beans.Objects.To_Object (True);
elsif Name = "sqlType" then
return Util.Beans.Objects.To_Object (From.Sql_Type);
else
return Mappings.Mapping_Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Compare two enum literals.
-- ------------------------------
function "<" (Left, Right : in Value_Definition_Access) return Boolean is
begin
return Left.Number < Right.Number;
end "<";
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Enum_Definition) is
procedure Sort is new Value_List.Sort_On ("<");
begin
O.Target := O.Type_Name;
Sort (O.Values);
end Prepare;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Enum_Definition) is
begin
O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Add an enum value to this enum definition and return the new value.
-- ------------------------------
procedure Add_Value (Enum : in out Enum_Definition;
Name : in String;
Value : out Value_Definition_Access) is
begin
Value := new Value_Definition;
Value.Name := To_Unbounded_String (Name);
Value.Number := Enum.Values.Get_Count;
Enum.Values.Append (Value);
end Add_Value;
-- ------------------------------
-- Create an enum with the given name.
-- ------------------------------
function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is
Enum : constant Enum_Definition_Access := new Enum_Definition;
begin
Enum.Name := Name;
declare
Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1);
Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name));
else
Enum.Pkg_Name := To_Unbounded_String ("ADO");
Enum.Type_Name := Enum.Name;
end if;
end;
return Enum;
end Create_Enum;
end Gen.Model.Enums;
|
Fix sorting of enum values
|
Fix sorting of enum values
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
ab43f5d9c65736d2d999cc51a3c67b552b5d09dc
|
src/asf-components-utils-scripts.adb
|
src/asf-components-utils-scripts.adb
|
-----------------------------------------------------------------------
-- components-utils-scripts -- Javascript queue
-- 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.
-----------------------------------------------------------------------
package body ASF.Components.Utils.Scripts is
-- ------------------------------
-- Write the content that was collected by rendering the inner children.
-- Write the content in the Javascript queue.
-- ------------------------------
overriding
procedure Write_Content (UI : in UIScript;
Writer : in out Contexts.Writer.Response_Writer'Class;
Content : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI, Context);
begin
Writer.Queue_Script (Content);
end Write_Content;
end ASF.Components.Utils.Scripts;
|
-----------------------------------------------------------------------
-- components-utils-scripts -- Javascript queue
-- 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.
-----------------------------------------------------------------------
package body ASF.Components.Utils.Scripts is
-- ------------------------------
-- Write the content that was collected by rendering the inner children.
-- Write the content in the Javascript queue.
-- ------------------------------
overriding
procedure Write_Content (UI : in UIScript;
Writer : in out Contexts.Writer.Response_Writer'Class;
Content : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI, Context);
begin
Writer.Queue_Script (Content);
end Write_Content;
-- ------------------------------
-- If the component provides a src attribute, render the <script src='xxx'></script>
-- tag with an optional async attribute.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIScript;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Src : constant String := UI.Get_Attribute (Context => Context, Name => "src");
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
if Src'Length > 0 then
Writer.Queue_Include_Script (URL => Src,
Async => UI.Get_Attribute (Context => Context,
Name => "async"));
end if;
end;
end Encode_Begin;
end ASF.Components.Utils.Scripts;
|
Implement the Encode_Begin procedure to test if the <util:script> component defines a 'src' attribute and generate a <script> command to load the specified javascript source
|
Implement the Encode_Begin procedure to test if the <util:script>
component defines a 'src' attribute and generate a <script> command to
load the specified javascript source
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
e73435c354f06fab4e28f00a6eef2d1dd84442fb
|
src/util-properties.ads
|
src/util-properties.ads
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
function Get (Self : in Manager'Class;
Name : in String) return Manager;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
Declare a Get function that returns a property manager
|
Declare a Get function that returns a property manager
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
bdcaef157c292bebfc18bfb8cea3d92a91db9349
|
src/orka/implementation/orka-ktx.adb
|
src/orka/implementation/orka-ktx.adb
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Interfaces.C.Extensions;
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with Ada.Unchecked_Conversion;
with GL.Pixels.Extensions;
package body Orka.KTX is
package ICE renames Interfaces.C.Extensions;
use Ada.Streams;
type Four_Bytes_Array is array (Positive range 1 .. 4) of Stream_Element
with Size => 32, Pack;
function Convert_Size is new Ada.Unchecked_Conversion
(Source => Four_Bytes_Array, Target => ICE.Unsigned_32);
type Header_Array is array (Positive range 1 .. 13 * 4) of Stream_Element
with Size => 32 * 13, Pack;
type Internal_Header is record
Endianness : ICE.Unsigned_32;
Data_Type : ICE.Unsigned_32;
Type_Size : ICE.Unsigned_32;
Format : ICE.Unsigned_32;
Internal_Format : ICE.Unsigned_32;
Base_Internal_Format : ICE.Unsigned_32;
Width : ICE.Unsigned_32;
Height : ICE.Unsigned_32;
Depth : ICE.Unsigned_32;
Array_Elements : ICE.Unsigned_32;
Faces : ICE.Unsigned_32;
Mipmap_Levels : ICE.Unsigned_32;
Bytes_Key_Value_Data : ICE.Unsigned_32;
end record
with Size => 32 * 13, Pack;
Identifier : constant Resources.Byte_Array
:= (16#AB#, 16#4B#, 16#54#, 16#58#, 16#20#, 16#31#,
16#31#, 16#BB#, 16#0D#, 16#0A#, 16#1A#, 16#0A#);
Endianness_Reference : constant := 16#04030201#;
function Valid_Identifier (Bytes : Bytes_Reference) return Boolean is
(Identifier = Bytes (Bytes.Value'First .. Bytes.Value'First + Identifier'Length - 1));
function Get_Header (Bytes : Bytes_Reference) return Header is
use type ICE.Unsigned_32;
function Convert is new Ada.Unchecked_Conversion
(Source => Header_Array, Target => Internal_Header);
function Convert_To_Data_Type is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => GL.Pixels.Data_Type);
function Convert_To_Format is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => GL.Pixels.Format);
function Convert_To_Internal_Format is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => GL.Pixels.Internal_Format);
function Convert_To_Compressed_Format is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => GL.Pixels.Compressed_Format);
Offset : constant Stream_Element_Offset := Bytes.Value'First + Identifier'Length;
File_Header : constant Internal_Header := Convert (Header_Array
(Bytes (Offset .. Offset + Header_Array'Length - 1)));
Compressed : constant Boolean := File_Header.Data_Type = 0;
begin
pragma Assert (File_Header.Endianness = Endianness_Reference);
pragma Assert (File_Header.Type_Size in 1 | 2 | 4);
return Result : Header (Compressed) do
pragma Assert (File_Header.Width > 0);
if File_Header.Depth > 0 then
pragma Assert (File_Header.Height > 0);
end if;
-- Set dimensions of a single texture
Result.Width := GL.Types.Size (File_Header.Width);
Result.Height := GL.Types.Size (File_Header.Height);
Result.Depth := GL.Types.Size (File_Header.Depth);
-- Set texture kind based on faces, array elements, and dimensions
if File_Header.Faces = 6 then
pragma Assert (File_Header.Width = File_Header.Height);
pragma Assert (File_Header.Depth = 0);
if File_Header.Array_Elements > 0 then
Result.Kind := Texture_Cube_Map_Array;
Result.Depth := GL.Types.Size (File_Header.Array_Elements * File_Header.Faces);
else
Result.Kind := Texture_Cube_Map;
end if;
else
if File_Header.Array_Elements > 0 then
if File_Header.Depth > 0 then
raise Constraint_Error with "OpenGL does not support 3D texture arrays";
elsif File_Header.Height > 0 then
Result.Kind := Texture_2D_Array;
Result.Depth := GL.Types.Size (File_Header.Array_Elements);
else
Result.Kind := Texture_1D_Array;
Result.Height := GL.Types.Size (File_Header.Array_Elements);
end if;
else
if File_Header.Depth > 0 then
Result.Kind := Texture_3D;
elsif File_Header.Height > 0 then
Result.Kind := Texture_2D;
else
Result.Kind := Texture_1D;
end if;
end if;
end if;
Result.Array_Elements := GL.Types.Size (File_Header.Array_Elements);
Result.Mipmap_Levels := GL.Types.Size (File_Header.Mipmap_Levels);
-- If mipmap levels is 0, then client should generate full
-- mipmap pyramid
Result.Bytes_Key_Value := GL.Types.Size (File_Header.Bytes_Key_Value_Data);
if Compressed then
pragma Assert (File_Header.Format = 0);
pragma Assert (File_Header.Type_Size = 1);
pragma Assert (File_Header.Mipmap_Levels > 0);
-- Format / Internal format
begin
Result.Compressed_Format
:= Convert_To_Compressed_Format (File_Header.Internal_Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid internal format (" & File_Header.Internal_Format'Image & ")";
end;
else
-- Data type
begin
Result.Data_Type := Convert_To_Data_Type (File_Header.Data_Type);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid data type (" & File_Header.Data_Type'Image & ")";
end;
-- Format
begin
Result.Format := Convert_To_Format (File_Header.Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid format (" & File_Header.Format'Image & ")";
end;
-- Internal format
begin
Result.Internal_Format
:= Convert_To_Internal_Format (File_Header.Internal_Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid internal format (" & File_Header.Internal_Format'Image & ")";
end;
end if;
end return;
end Get_Header;
function Get_Key_Value_Map
(Bytes : Bytes_Reference;
Length : GL.Types.Size) return KTX.String_Maps.Map
is
Result : KTX.String_Maps.Map;
Non_Header_Index : constant Stream_Element_Offset
:= Bytes.Value'First + Identifier'Length + Header_Array'Length;
Data_Index : constant Stream_Element_Offset
:= Non_Header_Index + Stream_Element_Offset (Length);
pragma Assert (Data_Index <= Bytes.Value'Last);
Bytes_Remaining : Natural := Natural (Length);
Pair_Index : Stream_Element_Offset := Non_Header_Index;
begin
while Bytes_Remaining > 0 loop
declare
Size_Bytes : constant Four_Bytes_Array := Four_Bytes_Array
(Bytes (Pair_Index .. Pair_Index + 4 - 1));
Key_Value_Size : constant Natural := Natural (Convert_Size (Size_Bytes));
Padding_Size : constant Natural := 3 - ((Key_Value_Size + 3) mod 4);
Pair_Size : constant Natural := 4 + Key_Value_Size + Padding_Size;
type Key_Value_Array is array (Positive range 1 .. Key_Value_Size) of Stream_Element
with Pack;
type Character_Array is array (Positive range 1 .. Key_Value_Size) of Character
with Pack;
function Convert_Pair is new Ada.Unchecked_Conversion
(Source => Key_Value_Array, Target => Character_Array);
Key_Value_Pair : constant Key_Value_Array := Key_Value_Array (Bytes
(Pair_Index + 4 .. Pair_Index + 4 + Stream_Element_Offset (Key_Value_Size) - 1));
Key_Value : constant String := String (Convert_Pair (Key_Value_Pair));
Position_NUL : constant Natural := Ada.Strings.Fixed.Index
(Key_Value, Ada.Strings.Maps.To_Set (Ada.Characters.Latin_1.NUL));
pragma Assert (Position_NUL > 0);
begin
-- Extract key and value here
declare
Key : constant String := Key_Value (1 .. Position_NUL - 1);
Value : constant String := Key_Value (Position_NUL + 1 .. Key_Value'Last);
begin
Result.Insert (Key, Value);
end;
Bytes_Remaining := Bytes_Remaining - Pair_Size;
Pair_Index := Pair_Index + Stream_Element_Offset (Pair_Size);
end;
end loop;
pragma Assert (Pair_Index = Data_Index);
return Result;
end Get_Key_Value_Map;
function Get_Length
(Bytes : Bytes_Reference;
Offset : Stream_Element_Offset) return Natural
is
Size_Bytes : constant Four_Bytes_Array := Four_Bytes_Array
(Bytes (Offset .. Offset + 4 - 1));
begin
return Natural (Convert_Size (Size_Bytes));
end Get_Length;
function Get_Data_Offset
(Bytes : Bytes_Reference;
Bytes_Key_Value : GL.Types.Size) return Stream_Element_Offset
is (Bytes.Value'First + Identifier'Length + Header_Array'Length
+ Stream_Element_Offset (Bytes_Key_Value));
function Create_KTX_Bytes
(KTX_Header : Header;
Data : Bytes_Reference) return Resources.Byte_Array_Pointers.Pointer
is
pragma Assert (KTX_Header.Mipmap_Levels = 1);
-- TODO Data is 1 pointer to a Byte_Array, so only supporting 1 mipmap
-- level at the moment
function Convert is new Ada.Unchecked_Conversion
(Source => Internal_Header, Target => Header_Array);
function Convert is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => Four_Bytes_Array);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Data_Type, Target => ICE.Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Format, Target => ICE.Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Internal_Format, Target => ICE.Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Compressed_Format, Target => ICE.Unsigned_32);
package PE renames GL.Pixels.Extensions;
use type ICE.Unsigned_32;
Compressed : Boolean renames KTX_Header.Compressed;
pragma Assert (if not Compressed then Data.Value'Length mod 4 = 0);
-- Data must be a multiple of 4 bytes because of the requirement
-- of GL.Pixels.Unpack_Alignment = Words (= 4)
-- Note: assertion is not precise because length of a row might
-- not be a multiple of 4 bytes
-- Note: Cube padding and mipmap padding can be assumed to be 0
Type_Size : constant GL.Types.Size
:= (if Compressed then 1 else PE.Bytes (KTX_Header.Data_Type));
Faces : constant ICE.Unsigned_32
:= (if KTX_Header.Kind in Texture_Cube_Map | Texture_Cube_Map_Array then 6 else 1);
File_Header : constant Internal_Header
:= (Endianness => Endianness_Reference,
Data_Type => (if Compressed then 0 else Convert (KTX_Header.Data_Type)),
Type_Size => ICE.Unsigned_32 (if Compressed then 1 else Type_Size),
Format => (if Compressed then 0 else Convert (KTX_Header.Format)),
Internal_Format =>
(if Compressed then
Convert (KTX_Header.Compressed_Format)
else
Convert (KTX_Header.Internal_Format)),
Base_Internal_Format =>
(if Compressed then
Convert (KTX_Header.Compressed_Format)
else
Convert (KTX_Header.Format)),
Width => ICE.Unsigned_32 (KTX_Header.Width),
Height => ICE.Unsigned_32 (KTX_Header.Height),
Depth => ICE.Unsigned_32 (if Faces = 6 then 0 else KTX_Header.Depth),
Array_Elements => ICE.Unsigned_32 (KTX_Header.Array_Elements),
Faces => Faces,
Mipmap_Levels => ICE.Unsigned_32 (KTX_Header.Mipmap_Levels),
Bytes_Key_Value_Data => 0);
-- TODO Support key value map?
Pointer : Resources.Byte_Array_Pointers.Pointer;
Result : constant not null Resources.Byte_Array_Access := new Resources.Byte_Array
(1 .. Identifier'Length + Header_Array'Length + 4 + Data.Value'Length);
-- TODO Supports just 1 level at the moment
Image_Size : constant ICE.Unsigned_32
:= (if KTX_Header.Kind = Texture_Cube_Map then
Data.Value'Length / 6
else
Data.Value'Length);
Header_Offset : constant Stream_Element_Offset := Result'First + Identifier'Length;
Size_Offset : constant Stream_Element_Offset := Header_Offset + Header_Array'Length;
Data_Offset : constant Stream_Element_Offset := Size_Offset + 4;
begin
Result (Result'First .. Header_Offset - 1) := Identifier;
Result (Header_Offset .. Size_Offset - 1) := Stream_Element_Array (Convert (File_Header));
Result (Size_Offset .. Data_Offset - 1) := Stream_Element_Array (Convert (Image_Size));
Result (Data_Offset .. Result'Last) := Data;
Pointer.Set (Result);
return Pointer;
end Create_KTX_Bytes;
end Orka.KTX;
|
-- 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 Interfaces.C.Extensions;
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with Ada.Unchecked_Conversion;
with GL.Pixels.Extensions;
package body Orka.KTX is
package ICE renames Interfaces.C.Extensions;
use Ada.Streams;
type Four_Bytes_Array is array (Positive range 1 .. 4) of Stream_Element
with Size => 32, Pack;
function Convert_Size is new Ada.Unchecked_Conversion
(Source => Four_Bytes_Array, Target => ICE.Unsigned_32);
type Header_Array is array (Positive range 1 .. 13 * 4) of Stream_Element
with Size => 32 * 13, Pack;
type Internal_Header is record
Endianness : ICE.Unsigned_32;
Data_Type : ICE.Unsigned_32;
Type_Size : ICE.Unsigned_32;
Format : ICE.Unsigned_32;
Internal_Format : ICE.Unsigned_32;
Base_Internal_Format : ICE.Unsigned_32;
Width : ICE.Unsigned_32;
Height : ICE.Unsigned_32;
Depth : ICE.Unsigned_32;
Array_Elements : ICE.Unsigned_32;
Faces : ICE.Unsigned_32;
Mipmap_Levels : ICE.Unsigned_32;
Bytes_Key_Value_Data : ICE.Unsigned_32;
end record
with Size => 32 * 13, Pack;
Identifier : constant Resources.Byte_Array
:= (16#AB#, 16#4B#, 16#54#, 16#58#, 16#20#, 16#31#,
16#31#, 16#BB#, 16#0D#, 16#0A#, 16#1A#, 16#0A#);
Endianness_Reference : constant := 16#04030201#;
function Valid_Identifier (Bytes : Bytes_Reference) return Boolean is
(Identifier = Bytes (Bytes.Value'First .. Bytes.Value'First + Identifier'Length - 1));
function Get_Header (Bytes : Bytes_Reference) return Header is
use type ICE.Unsigned_32;
function Convert is new Ada.Unchecked_Conversion
(Source => Header_Array, Target => Internal_Header);
function Convert_To_Data_Type is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => GL.Pixels.Data_Type);
function Convert_To_Format is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => GL.Pixels.Format);
function Convert_To_Internal_Format is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => GL.Pixels.Internal_Format);
function Convert_To_Compressed_Format is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => GL.Pixels.Compressed_Format);
Offset : constant Stream_Element_Offset := Bytes.Value'First + Identifier'Length;
File_Header : constant Internal_Header := Convert (Header_Array
(Bytes (Offset .. Offset + Header_Array'Length - 1)));
Compressed : constant Boolean := File_Header.Data_Type = 0;
begin
pragma Assert (File_Header.Endianness = Endianness_Reference);
pragma Assert (File_Header.Type_Size in 1 | 2 | 4);
return Result : Header (Compressed) do
pragma Assert (File_Header.Width > 0);
if File_Header.Depth > 0 then
pragma Assert (File_Header.Height > 0);
end if;
-- Set dimensions of a single texture
Result.Width := GL.Types.Size (File_Header.Width);
Result.Height := GL.Types.Size (File_Header.Height);
Result.Depth := GL.Types.Size (File_Header.Depth);
-- Set texture kind based on faces, array elements, and dimensions
if File_Header.Faces = 6 then
pragma Assert (File_Header.Width = File_Header.Height);
pragma Assert (File_Header.Depth = 0);
if File_Header.Array_Elements > 0 then
Result.Kind := Texture_Cube_Map_Array;
else
Result.Kind := Texture_Cube_Map;
end if;
else
if File_Header.Array_Elements > 0 then
if File_Header.Depth > 0 then
raise Constraint_Error with "OpenGL does not support 3D texture arrays";
elsif File_Header.Height > 0 then
Result.Kind := Texture_2D_Array;
else
Result.Kind := Texture_1D_Array;
end if;
else
if File_Header.Depth > 0 then
Result.Kind := Texture_3D;
elsif File_Header.Height > 0 then
Result.Kind := Texture_2D;
else
Result.Kind := Texture_1D;
end if;
end if;
end if;
Result.Array_Elements := GL.Types.Size (File_Header.Array_Elements);
Result.Mipmap_Levels := GL.Types.Size (File_Header.Mipmap_Levels);
-- If mipmap levels is 0, then client should generate full
-- mipmap pyramid
Result.Bytes_Key_Value := GL.Types.Size (File_Header.Bytes_Key_Value_Data);
if Compressed then
pragma Assert (File_Header.Format = 0);
pragma Assert (File_Header.Type_Size = 1);
pragma Assert (File_Header.Mipmap_Levels > 0);
-- Format / Internal format
begin
Result.Compressed_Format
:= Convert_To_Compressed_Format (File_Header.Internal_Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid internal format (" & File_Header.Internal_Format'Image & ")";
end;
else
-- Data type
begin
Result.Data_Type := Convert_To_Data_Type (File_Header.Data_Type);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid data type (" & File_Header.Data_Type'Image & ")";
end;
-- Format
begin
Result.Format := Convert_To_Format (File_Header.Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid format (" & File_Header.Format'Image & ")";
end;
-- Internal format
begin
Result.Internal_Format
:= Convert_To_Internal_Format (File_Header.Internal_Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid internal format (" & File_Header.Internal_Format'Image & ")";
end;
end if;
end return;
end Get_Header;
function Get_Key_Value_Map
(Bytes : Bytes_Reference;
Length : GL.Types.Size) return KTX.String_Maps.Map
is
Result : KTX.String_Maps.Map;
Non_Header_Index : constant Stream_Element_Offset
:= Bytes.Value'First + Identifier'Length + Header_Array'Length;
Data_Index : constant Stream_Element_Offset
:= Non_Header_Index + Stream_Element_Offset (Length);
pragma Assert (Data_Index <= Bytes.Value'Last);
Bytes_Remaining : Natural := Natural (Length);
Pair_Index : Stream_Element_Offset := Non_Header_Index;
begin
while Bytes_Remaining > 0 loop
declare
Size_Bytes : constant Four_Bytes_Array := Four_Bytes_Array
(Bytes (Pair_Index .. Pair_Index + 4 - 1));
Key_Value_Size : constant Natural := Natural (Convert_Size (Size_Bytes));
Padding_Size : constant Natural := 3 - ((Key_Value_Size + 3) mod 4);
Pair_Size : constant Natural := 4 + Key_Value_Size + Padding_Size;
type Key_Value_Array is array (Positive range 1 .. Key_Value_Size) of Stream_Element
with Pack;
type Character_Array is array (Positive range 1 .. Key_Value_Size) of Character
with Pack;
function Convert_Pair is new Ada.Unchecked_Conversion
(Source => Key_Value_Array, Target => Character_Array);
Key_Value_Pair : constant Key_Value_Array := Key_Value_Array (Bytes
(Pair_Index + 4 .. Pair_Index + 4 + Stream_Element_Offset (Key_Value_Size) - 1));
Key_Value : constant String := String (Convert_Pair (Key_Value_Pair));
Position_NUL : constant Natural := Ada.Strings.Fixed.Index
(Key_Value, Ada.Strings.Maps.To_Set (Ada.Characters.Latin_1.NUL));
pragma Assert (Position_NUL > 0);
begin
-- Extract key and value here
declare
Key : constant String := Key_Value (1 .. Position_NUL - 1);
Value : constant String := Key_Value (Position_NUL + 1 .. Key_Value'Last);
begin
Result.Insert (Key, Value);
end;
Bytes_Remaining := Bytes_Remaining - Pair_Size;
Pair_Index := Pair_Index + Stream_Element_Offset (Pair_Size);
end;
end loop;
pragma Assert (Pair_Index = Data_Index);
return Result;
end Get_Key_Value_Map;
function Get_Length
(Bytes : Bytes_Reference;
Offset : Stream_Element_Offset) return Natural
is
Size_Bytes : constant Four_Bytes_Array := Four_Bytes_Array
(Bytes (Offset .. Offset + 4 - 1));
begin
return Natural (Convert_Size (Size_Bytes));
end Get_Length;
function Get_Data_Offset
(Bytes : Bytes_Reference;
Bytes_Key_Value : GL.Types.Size) return Stream_Element_Offset
is (Bytes.Value'First + Identifier'Length + Header_Array'Length
+ Stream_Element_Offset (Bytes_Key_Value));
function Create_KTX_Bytes
(KTX_Header : Header;
Data : Bytes_Reference) return Resources.Byte_Array_Pointers.Pointer
is
pragma Assert (KTX_Header.Mipmap_Levels = 1);
-- TODO Data is 1 pointer to a Byte_Array, so only supporting 1 mipmap
-- level at the moment
function Convert is new Ada.Unchecked_Conversion
(Source => Internal_Header, Target => Header_Array);
function Convert is new Ada.Unchecked_Conversion
(Source => ICE.Unsigned_32, Target => Four_Bytes_Array);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Data_Type, Target => ICE.Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Format, Target => ICE.Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Internal_Format, Target => ICE.Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Compressed_Format, Target => ICE.Unsigned_32);
package PE renames GL.Pixels.Extensions;
use type ICE.Unsigned_32;
Compressed : Boolean renames KTX_Header.Compressed;
pragma Assert (if not Compressed then Data.Value'Length mod 4 = 0);
-- Data must be a multiple of 4 bytes because of the requirement
-- of GL.Pixels.Unpack_Alignment = Words (= 4)
-- Note: assertion is not precise because length of a row might
-- not be a multiple of 4 bytes
-- Note: Cube padding and mipmap padding can be assumed to be 0
Type_Size : constant GL.Types.Size
:= (if Compressed then 1 else PE.Bytes (KTX_Header.Data_Type));
Faces : constant ICE.Unsigned_32
:= (if KTX_Header.Kind in Texture_Cube_Map | Texture_Cube_Map_Array then 6 else 1);
File_Header : constant Internal_Header
:= (Endianness => Endianness_Reference,
Data_Type => (if Compressed then 0 else Convert (KTX_Header.Data_Type)),
Type_Size => ICE.Unsigned_32 (if Compressed then 1 else Type_Size),
Format => (if Compressed then 0 else Convert (KTX_Header.Format)),
Internal_Format =>
(if Compressed then
Convert (KTX_Header.Compressed_Format)
else
Convert (KTX_Header.Internal_Format)),
Base_Internal_Format =>
(if Compressed then
Convert (KTX_Header.Compressed_Format)
else
Convert (KTX_Header.Format)),
Width => ICE.Unsigned_32 (KTX_Header.Width),
Height => ICE.Unsigned_32 (KTX_Header.Height),
Depth => ICE.Unsigned_32 (if Faces = 6 then 0 else KTX_Header.Depth),
Array_Elements => ICE.Unsigned_32 (KTX_Header.Array_Elements),
Faces => Faces,
Mipmap_Levels => ICE.Unsigned_32 (KTX_Header.Mipmap_Levels),
Bytes_Key_Value_Data => 0);
-- TODO Support key value map?
Pointer : Resources.Byte_Array_Pointers.Pointer;
Result : constant not null Resources.Byte_Array_Access := new Resources.Byte_Array
(1 .. Identifier'Length + Header_Array'Length + 4 + Data.Value'Length);
-- TODO Supports just 1 level at the moment
Image_Size : constant ICE.Unsigned_32
:= (if KTX_Header.Kind = Texture_Cube_Map then
Data.Value'Length / 6
else
Data.Value'Length);
Header_Offset : constant Stream_Element_Offset := Result'First + Identifier'Length;
Size_Offset : constant Stream_Element_Offset := Header_Offset + Header_Array'Length;
Data_Offset : constant Stream_Element_Offset := Size_Offset + 4;
begin
Result (Result'First .. Header_Offset - 1) := Identifier;
Result (Header_Offset .. Size_Offset - 1) := Stream_Element_Array (Convert (File_Header));
Result (Size_Offset .. Data_Offset - 1) := Stream_Element_Array (Convert (Image_Size));
Result (Data_Offset .. Result'Last) := Data;
Pointer.Set (Result);
return Pointer;
end Create_KTX_Bytes;
end Orka.KTX;
|
Fix incorrectly overriding component Depth of KTX header
|
orka: Fix incorrectly overriding component Depth of KTX header
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
dfad3941802ee873f4e67cb4bc57ce3321601dba
|
matp/src/mat-commands.ads
|
matp/src/mat-commands.ads
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- Initialize the process targets by loading the MAT files.
procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class);
-- Symbol command.
-- Load the symbols from the binary file.
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Threads command.
-- Collect statistics about the threads and their allocation.
procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Events command.
-- Print the probe events.
procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Event command.
-- Print the probe event with the stack frame.
procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
end MAT.Commands;
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- 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 MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- Initialize the process targets by loading the MAT files.
procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class);
-- Symbol command.
-- Load the symbols from the binary file.
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Threads command.
-- Collect statistics about the threads and their allocation.
procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Events command.
-- Print the probe events.
procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Event command.
-- Print the probe event with the stack frame.
procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Info command to print symmary information about the program.
procedure Info_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
end MAT.Commands;
|
Declare the Info_Command procedure
|
Declare the Info_Command procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
2343260c5d50c808b0167ec5238a00da9f25b988
|
src/security-policies.ads
|
src/security-policies.ads
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
limited with Security.Controllers;
limited with Security.Contexts;
package Security.Policies is
type Policy is new Ada.Finalization.Limited_Controlled with null record;
type Policy_Access is access all Policy'Class;
procedure Set_Reader_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Get the policy name.
function Get_Name (From : in Policy) return String;
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access;
-- 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 Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager is new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- 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 Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
use Util.Strings;
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Manager is new Ada.Finalization.Limited_Controlled with record
-- Cache : Rules_Ref_Access;
-- Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
limited with Security.Controllers;
limited with Security.Contexts;
package Security.Policies is
type Policy is new Ada.Finalization.Limited_Controlled with null record;
type Policy_Access is access all Policy'Class;
procedure Set_Reader_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is null;
-- Get the policy name.
function Get_Name (From : in Policy) return String;
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access;
-- 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 Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Policy_Manager is new Ada.Finalization.Limited_Controlled with private;
type Policy_Manager_Access is access all Policy_Manager'Class;
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access);
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access);
-- 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 Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager);
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Policy_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Policy_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
private
use Util.Strings;
subtype Permission_Index is Permissions.Permission_Index;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Policy_Manager is new Ada.Finalization.Limited_Controlled with record
-- Cache : Rules_Ref_Access;
-- Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
end Security.Policies;
|
Document Add_Permission
|
Document Add_Permission
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
8d4418c96a7313d8358370fe6a8b38024640cb7c
|
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.Log.Loggers;
with Util.Nullables;
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;
-- Write the attribute with a null value.
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String) 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 Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_String);
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_Time);
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_Boolean);
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_Integer);
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_Long);
-- Write an entity with a null value.
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String) is abstract;
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;
Logger : in out Util.Log.Logging'Class) 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;
Logger : in out Util.Log.Logging'Class) is abstract;
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is abstract;
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) 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;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is abstract;
type Parser is abstract new Util.Log.Logging 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.Log.Logging 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;
|
-----------------------------------------------------------------------
-- 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.Log.Loggers;
with Util.Nullables;
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;
-- Write the attribute with a null value.
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String) 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 Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_String);
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_Time);
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_Boolean);
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_Integer);
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Util.Nullables.Nullable_Long);
-- Write an entity with a null value.
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String) is abstract;
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;
Logger : in out Util.Log.Logging'Class) 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;
Logger : in out Util.Log.Logging'Class) is abstract;
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is abstract;
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) 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;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is abstract;
type Parser is abstract new Util.Log.Logging with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Input_Buffer_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.Log.Logging 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;
|
Use the Input_Buffer_Stream instead of Buffered_Stream
|
Use the Input_Buffer_Stream instead of Buffered_Stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
68ea834a61ba6825be2cdd448adc33a738381e42
|
src/wiki-parsers-html.adb
|
src/wiki-parsers-html.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package body Wiki.Parsers.Html is
use Ada.Strings.Wide_Wide_Unbounded;
procedure Collect_Attributes (P : in out Parser);
function Is_Space (C : in Wide_Wide_Character) return Boolean;
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return C = ' ' or C = LF or C = CR;
end Is_Space;
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
procedure Skip_Spaces (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if not Is_Space (C) then
Put_Back (P, C);
return;
end if;
end loop;
end Skip_Spaces;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Quote : in Wide_Wide_Character;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = Quote;
Append (Value, C);
end loop;
end Collect_Attribute_Value;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
Token : Wide_Wide_Character;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
begin
Peek (P, C);
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Name);
else
Collect_Attributes (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Name, P.Attributes);
end if;
end Parse_Element;
end Wiki.Parsers.Html;
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package body Wiki.Parsers.Html is
use Ada.Strings.Wide_Wide_Unbounded;
procedure Collect_Attributes (P : in out Parser);
function Is_Space (C : in Wide_Wide_Character) return Boolean;
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return C = ' ' or C = LF or C = CR;
end Is_Space;
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
procedure Skip_Spaces (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if not Is_Space (C) then
Put_Back (P, C);
return;
end if;
end loop;
end Skip_Spaces;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Quote : in Wide_Wide_Character;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = Quote;
Append (Value, C);
end loop;
end Collect_Attribute_Value;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
Token : Wide_Wide_Character;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
begin
Peek (P, C);
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Name);
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Name, P.Attributes);
End_Element (P, Name);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Name, P.Attributes);
end if;
end Parse_Element;
end Wiki.Parsers.Html;
|
Add support for HTML close entities
|
Add support for HTML close entities
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
02150b73b29efd9d375344bc90a1ae0cdac30f07
|
samples/select_user.adb
|
samples/select_user.adb
|
-----------------------------------------------------------------------
-- select_user - Show usage of query statements
-- 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 ADO;
with ADO.Drivers;
with ADO.Configs;
with ADO.Sessions;
with ADO.Sessions.Factory;
with ADO.Statements;
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Exceptions;
with Util.Log.Loggers;
procedure Select_User is
Factory : ADO.Sessions.Factory.Session_Factory;
begin
if Ada.Command_Line.Argument_Count < 1 then
Ada.Text_IO.Put_Line ("Usage: select_user user-name ...");
Ada.Text_IO.Put_Line ("Example: select_user joe");
Ada.Command_Line.Set_Exit_Status (2);
return;
end if;
Util.Log.Loggers.Initialize ("samples.properties");
-- Initialize the database drivers.
ADO.Drivers.Initialize ("samples.properties");
-- Initialize the session factory to connect to the
-- database defined by 'ado.database' property.
Factory.Create (ADO.Drivers.Get_Config ("ado.database"));
declare
DB : constant ADO.Sessions.Session := Factory.Get_Session;
Stmt : ADO.Statements.Query_Statement
:= DB.Create_Statement ("SELECT "
& "id, name, email, date, description, status "
& "FROM user WHERE name = :name");
begin
for I in 1 .. Ada.Command_Line.Argument_Count loop
Stmt.Bind_Param (Name => "name",
Value => Ada.Command_Line.Argument (I));
Stmt.Execute;
while Stmt.Has_Elements loop
Ada.Text_IO.Put_Line (" Id : " & Stmt.Get_String (0));
Ada.Text_IO.Put_Line (" User : " & Stmt.Get_String (1));
Ada.Text_IO.Put_Line (" Email : " & Stmt.Get_String (2));
Stmt.Next;
end loop;
end loop;
end;
exception
when E : ADO.Drivers.Database_Error | ADO.Configs.Connection_Error =>
Ada.Text_IO.Put_Line ("Cannot connect to database: "
& Ada.Exceptions.Exception_Message (E));
end Select_User;
|
-----------------------------------------------------------------------
-- select_user - Show usage of query statements
-- 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 ADO.Drivers;
with ADO.Sessions;
with ADO.Sessions.Factory;
with ADO.Statements;
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Exceptions;
with Util.Log.Loggers;
procedure Select_User is
Factory : ADO.Sessions.Factory.Session_Factory;
begin
if Ada.Command_Line.Argument_Count < 1 then
Ada.Text_IO.Put_Line ("Usage: select_user user-name ...");
Ada.Text_IO.Put_Line ("Example: select_user joe");
Ada.Command_Line.Set_Exit_Status (2);
return;
end if;
Util.Log.Loggers.Initialize ("samples.properties");
-- Initialize the database drivers.
ADO.Drivers.Initialize ("samples.properties");
-- Initialize the session factory to connect to the
-- database defined by 'ado.database' property.
Factory.Create (ADO.Drivers.Get_Config ("ado.database"));
declare
DB : constant ADO.Sessions.Session := Factory.Get_Session;
Stmt : ADO.Statements.Query_Statement
:= DB.Create_Statement ("SELECT "
& "id, name, email, date, description, status "
& "FROM user WHERE name = :name");
begin
for I in 1 .. Ada.Command_Line.Argument_Count loop
Stmt.Bind_Param (Name => "name",
Value => Ada.Command_Line.Argument (I));
Stmt.Execute;
while Stmt.Has_Elements loop
Ada.Text_IO.Put_Line (" Id : " & Stmt.Get_String (0));
Ada.Text_IO.Put_Line (" User : " & Stmt.Get_String (1));
Ada.Text_IO.Put_Line (" Email : " & Stmt.Get_String (2));
Stmt.Next;
end loop;
end loop;
end;
exception
when E : ADO.Drivers.Database_Error | ADO.Sessions.Connection_Error =>
Ada.Text_IO.Put_Line ("Cannot connect to database: "
& Ada.Exceptions.Exception_Message (E));
end Select_User;
|
Simplify the select_user example
|
Simplify the select_user example
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
906a1d9d564d7b170c718e74409b0e22f16e6d80
|
src/orka/implementation/orka-ktx.adb
|
src/orka/implementation/orka-ktx.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with Ada.Unchecked_Conversion;
with GL.Pixels.Extensions;
package body Orka.KTX is
use Ada.Streams;
type Unsigned_32 is mod 2 ** 32
with Size => 32;
type Four_Bytes_Array is array (Positive range 1 .. 4) of Stream_Element
with Size => 32, Pack;
function Convert_Size is new Ada.Unchecked_Conversion
(Source => Four_Bytes_Array, Target => Unsigned_32);
type Header_Array is array (Positive range 1 .. 13 * 4) of Stream_Element
with Size => 32 * 13, Pack;
type Internal_Header is record
Endianness : Unsigned_32;
Data_Type : Unsigned_32;
Type_Size : Unsigned_32;
Format : Unsigned_32;
Internal_Format : Unsigned_32;
Base_Internal_Format : Unsigned_32;
Width : Unsigned_32;
Height : Unsigned_32;
Depth : Unsigned_32;
Array_Elements : Unsigned_32;
Faces : Unsigned_32;
Mipmap_Levels : Unsigned_32;
Bytes_Key_Value_Data : Unsigned_32;
end record
with Size => 32 * 13, Pack;
Identifier : constant Resources.Byte_Array
:= (16#AB#, 16#4B#, 16#54#, 16#58#, 16#20#, 16#31#,
16#31#, 16#BB#, 16#0D#, 16#0A#, 16#1A#, 16#0A#);
Endianness_Reference : constant := 16#04030201#;
function Valid_Identifier (Bytes : Bytes_Reference) return Boolean is
(Identifier = Bytes (Bytes.Value'First .. Bytes.Value'First + Identifier'Length - 1));
function Get_Header (Bytes : Bytes_Reference) return Header is
function Convert is new Ada.Unchecked_Conversion
(Source => Header_Array, Target => Internal_Header);
function Convert_To_Data_Type is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => GL.Pixels.Data_Type);
function Convert_To_Format is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => GL.Pixels.Format);
function Convert_To_Internal_Format is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => GL.Pixels.Internal_Format);
function Convert_To_Compressed_Format is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => GL.Pixels.Compressed_Format);
Offset : constant Stream_Element_Offset := Bytes.Value'First + Identifier'Length;
File_Header : constant Internal_Header := Convert (Header_Array
(Bytes (Offset .. Offset + Header_Array'Length - 1)));
Compressed : constant Boolean := File_Header.Data_Type = 0;
begin
pragma Assert (File_Header.Endianness = Endianness_Reference);
pragma Assert (File_Header.Type_Size in 1 | 2 | 4);
return Result : Header (Compressed) do
pragma Assert (File_Header.Width > 0);
if File_Header.Depth > 0 then
pragma Assert (File_Header.Height > 0);
end if;
-- Set dimensions of a single texture
Result.Width := GL.Types.Size (File_Header.Width);
Result.Height := GL.Types.Size (File_Header.Height);
Result.Depth := GL.Types.Size (File_Header.Depth);
-- Set texture kind based on faces, array elements, and dimensions
if File_Header.Faces = 6 then
pragma Assert (File_Header.Width = File_Header.Height);
pragma Assert (File_Header.Depth = 0);
if File_Header.Array_Elements > 0 then
Result.Kind := Texture_Cube_Map_Array;
else
Result.Kind := Texture_Cube_Map;
end if;
else
if File_Header.Array_Elements > 0 then
if File_Header.Depth > 0 then
raise Constraint_Error with "OpenGL does not support 3D texture arrays";
elsif File_Header.Height > 0 then
Result.Kind := Texture_2D_Array;
else
Result.Kind := Texture_1D_Array;
end if;
else
if File_Header.Depth > 0 then
Result.Kind := Texture_3D;
elsif File_Header.Height > 0 then
Result.Kind := Texture_2D;
else
Result.Kind := Texture_1D;
end if;
end if;
end if;
Result.Array_Elements := GL.Types.Size (File_Header.Array_Elements);
Result.Mipmap_Levels := GL.Types.Size (File_Header.Mipmap_Levels);
-- If mipmap levels is 0, then client should generate full
-- mipmap pyramid
Result.Bytes_Key_Value := GL.Types.Size (File_Header.Bytes_Key_Value_Data);
if Compressed then
pragma Assert (File_Header.Format = 0);
pragma Assert (File_Header.Type_Size = 1);
pragma Assert (File_Header.Mipmap_Levels > 0);
-- Format / Internal format
begin
Result.Compressed_Format
:= Convert_To_Compressed_Format (File_Header.Internal_Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid internal format (" & File_Header.Internal_Format'Image & ")";
end;
else
-- Data type
begin
Result.Data_Type := Convert_To_Data_Type (File_Header.Data_Type);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid data type (" & File_Header.Data_Type'Image & ")";
end;
-- Format
begin
Result.Format := Convert_To_Format (File_Header.Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid format (" & File_Header.Format'Image & ")";
end;
-- Internal format
begin
Result.Internal_Format
:= Convert_To_Internal_Format (File_Header.Internal_Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid internal format (" & File_Header.Internal_Format'Image & ")";
end;
end if;
end return;
end Get_Header;
function Get_Key_Value_Map
(Bytes : Bytes_Reference;
Length : GL.Types.Size) return KTX.String_Maps.Map
is
Result : KTX.String_Maps.Map;
Non_Header_Index : constant Stream_Element_Offset
:= Bytes.Value'First + Identifier'Length + Header_Array'Length;
Data_Index : constant Stream_Element_Offset
:= Non_Header_Index + Stream_Element_Offset (Length);
pragma Assert (Data_Index <= Bytes.Value'Last);
Bytes_Remaining : Natural := Natural (Length);
Pair_Index : Stream_Element_Offset := Non_Header_Index;
begin
while Bytes_Remaining > 0 loop
declare
Size_Bytes : constant Four_Bytes_Array := Four_Bytes_Array
(Bytes (Pair_Index .. Pair_Index + 4 - 1));
Key_Value_Size : constant Natural := Natural (Convert_Size (Size_Bytes));
Padding_Size : constant Natural := 3 - ((Key_Value_Size + 3) mod 4);
Pair_Size : constant Natural := 4 + Key_Value_Size + Padding_Size;
type Key_Value_Array is array (Positive range 1 .. Key_Value_Size) of Stream_Element
with Pack;
type Character_Array is array (Positive range 1 .. Key_Value_Size) of Character
with Pack;
function Convert_Pair is new Ada.Unchecked_Conversion
(Source => Key_Value_Array, Target => Character_Array);
Key_Value_Pair : constant Key_Value_Array := Key_Value_Array (Bytes
(Pair_Index + 4 .. Pair_Index + 4 + Stream_Element_Offset (Key_Value_Size) - 1));
Key_Value : constant String := String (Convert_Pair (Key_Value_Pair));
Position_NUL : constant Natural := Ada.Strings.Fixed.Index
(Key_Value, Ada.Strings.Maps.To_Set (Ada.Characters.Latin_1.NUL));
pragma Assert (Position_NUL > 0);
begin
-- Extract key and value here
declare
Key : constant String := Key_Value (1 .. Position_NUL - 1);
Value : constant String := Key_Value (Position_NUL + 1 .. Key_Value'Last);
begin
Result.Insert (Key, Value);
end;
Bytes_Remaining := Bytes_Remaining - Pair_Size;
Pair_Index := Pair_Index + Stream_Element_Offset (Pair_Size);
end;
end loop;
pragma Assert (Pair_Index = Data_Index);
return Result;
end Get_Key_Value_Map;
function Get_Length
(Bytes : Bytes_Reference;
Offset : Stream_Element_Offset) return Natural
is
Size_Bytes : constant Four_Bytes_Array := Four_Bytes_Array
(Bytes (Offset .. Offset + 4 - 1));
begin
return Natural (Convert_Size (Size_Bytes));
end Get_Length;
function Get_Data_Offset
(Bytes : Bytes_Reference;
Bytes_Key_Value : GL.Types.Size) return Stream_Element_Offset
is (Bytes.Value'First + Identifier'Length + Header_Array'Length
+ Stream_Element_Offset (Bytes_Key_Value));
function Create_KTX_Bytes
(KTX_Header : Header;
Get_Data : not null access function (Level : GL.Objects.Textures.Mipmap_Level)
return Resources.Byte_Array_Pointers.Pointer)
return Resources.Byte_Array_Pointers.Pointer
is
function Convert is new Ada.Unchecked_Conversion
(Source => Internal_Header, Target => Header_Array);
function Convert is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => Four_Bytes_Array);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Data_Type, Target => Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Format, Target => Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Internal_Format, Target => Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Compressed_Format, Target => Unsigned_32);
package PE renames GL.Pixels.Extensions;
Compressed : Boolean renames KTX_Header.Compressed;
Type_Size : constant GL.Types.Size
:= (if Compressed then 1 else PE.Bytes (KTX_Header.Data_Type));
Faces : constant Unsigned_32
:= (if KTX_Header.Kind in Texture_Cube_Map | Texture_Cube_Map_Array then 6 else 1);
File_Header : constant Internal_Header
:= (Endianness => Endianness_Reference,
Data_Type => (if Compressed then 0 else Convert (KTX_Header.Data_Type)),
Type_Size => Unsigned_32 (if Compressed then 1 else Type_Size),
Format => (if Compressed then 0 else Convert (KTX_Header.Format)),
Internal_Format =>
(if Compressed then
Convert (KTX_Header.Compressed_Format)
else
Convert (KTX_Header.Internal_Format)),
Base_Internal_Format =>
(if Compressed then
Convert (KTX_Header.Compressed_Format)
else
Convert (KTX_Header.Format)),
Width => Unsigned_32 (KTX_Header.Width),
Height => Unsigned_32 (KTX_Header.Height),
Depth => Unsigned_32 (if Faces = 6 then 0 else KTX_Header.Depth),
Array_Elements => Unsigned_32 (KTX_Header.Array_Elements),
Faces => Faces,
Mipmap_Levels => Unsigned_32 (KTX_Header.Mipmap_Levels),
Bytes_Key_Value_Data => 0);
-- TODO Support key value map?
Pointer : Resources.Byte_Array_Pointers.Pointer;
--------------------------------------------------------------------------
Data : array (0 .. KTX_Header.Mipmap_Levels - 1) of Resources.Byte_Array_Pointers.Pointer;
Total_Size : Stream_Element_Offset := 0;
begin
for Level in Data'Range loop
Data (Level) := Get_Data (Level);
Total_Size := Total_Size + Data (Level).Get.Value'Length;
end loop;
Total_Size := Total_Size + 4 * Data'Length;
pragma Assert (if not Compressed then
(for all Pointer of Data => Pointer.Get.Value'Length mod 4 = 0));
-- Data must be a multiple of 4 bytes because of the requirement
-- of GL.Pixels.Unpack_Alignment = Words (= 4)
-- Note: assertion is not precise because length of a row might
-- not be a multiple of 4 bytes
-- Note: Cube padding and mipmap padding can be assumed to be 0
declare
Result : constant not null Resources.Byte_Array_Access := new Resources.Byte_Array
(1 .. Identifier'Length + Header_Array'Length + Total_Size);
Header_Offset : constant Stream_Element_Offset := Result'First + Identifier'Length;
Size_Offset : Stream_Element_Offset := Header_Offset + Header_Array'Length;
begin
Result (Result'First .. Header_Offset - 1) := Identifier;
Result (Header_Offset .. Size_Offset - 1) := Stream_Element_Array (Convert (File_Header));
for Level_Data of Data loop
declare
Image_Size : constant Unsigned_32
:= (if KTX_Header.Kind = Texture_Cube_Map then
Level_Data.Get.Value'Length / 6
else
Level_Data.Get.Value'Length);
Data_Offset : constant Stream_Element_Offset := Size_Offset + 4;
Next_Offset : constant Stream_Element_Offset
:= Data_Offset + Level_Data.Get.Value'Length;
begin
Result (Size_Offset .. Data_Offset - 1)
:= Stream_Element_Array (Convert (Image_Size));
Result (Data_Offset .. Next_Offset - 1)
:= Level_Data.Get;
Size_Offset := Next_Offset;
end;
end loop;
Pointer.Set (Result);
return Pointer;
end;
end Create_KTX_Bytes;
end Orka.KTX;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with Ada.Unchecked_Conversion;
with GL.Pixels.Extensions;
package body Orka.KTX is
use Ada.Streams;
type Unsigned_32 is mod 2 ** 32
with Size => 32;
type Four_Bytes_Array is array (Positive range 1 .. 4) of Stream_Element
with Size => 32, Pack;
function Convert_Size is new Ada.Unchecked_Conversion
(Source => Four_Bytes_Array, Target => Unsigned_32);
type Header_Array is array (Positive range 1 .. 13 * 4) of Stream_Element
with Size => 32 * 13, Pack;
type Internal_Header is record
Endianness : Unsigned_32;
Data_Type : Unsigned_32;
Type_Size : Unsigned_32;
Format : Unsigned_32;
Internal_Format : Unsigned_32;
Base_Internal_Format : Unsigned_32;
Width : Unsigned_32;
Height : Unsigned_32;
Depth : Unsigned_32;
Array_Elements : Unsigned_32;
Faces : Unsigned_32;
Mipmap_Levels : Unsigned_32;
Bytes_Key_Value_Data : Unsigned_32;
end record
with Size => 32 * 13, Pack;
Identifier : constant Resources.Byte_Array
:= (16#AB#, 16#4B#, 16#54#, 16#58#, 16#20#, 16#31#,
16#31#, 16#BB#, 16#0D#, 16#0A#, 16#1A#, 16#0A#);
Endianness_Reference : constant := 16#04030201#;
function Valid_Identifier (Bytes : Bytes_Reference) return Boolean is
(Identifier = Bytes (Bytes.Value'First .. Bytes.Value'First + Identifier'Length - 1));
function Get_Header (Bytes : Bytes_Reference) return Header is
function Convert is new Ada.Unchecked_Conversion
(Source => Header_Array, Target => Internal_Header);
function Convert_To_Data_Type is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => GL.Pixels.Data_Type);
function Convert_To_Format is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => GL.Pixels.Format);
function Convert_To_Internal_Format is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => GL.Pixels.Internal_Format);
function Convert_To_Compressed_Format is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => GL.Pixels.Compressed_Format);
Offset : constant Stream_Element_Offset := Bytes.Value'First + Identifier'Length;
File_Header : constant Internal_Header := Convert (Header_Array
(Bytes (Offset .. Offset + Header_Array'Length - 1)));
Compressed : constant Boolean := File_Header.Data_Type = 0;
begin
pragma Assert (File_Header.Endianness = Endianness_Reference);
pragma Assert (File_Header.Type_Size in 1 | 2 | 4);
return Result : Header (Compressed) do
pragma Assert (File_Header.Width > 0);
if File_Header.Depth > 0 then
pragma Assert (File_Header.Height > 0);
end if;
-- Set dimensions of a single texture
Result.Width := GL.Types.Size (File_Header.Width);
Result.Height := GL.Types.Size (File_Header.Height);
Result.Depth := GL.Types.Size (File_Header.Depth);
-- Set texture kind based on faces, array elements, and dimensions
if File_Header.Faces = 6 then
pragma Assert (File_Header.Width = File_Header.Height);
pragma Assert (File_Header.Depth = 0);
if File_Header.Array_Elements > 0 then
Result.Kind := Texture_Cube_Map_Array;
else
Result.Kind := Texture_Cube_Map;
end if;
else
if File_Header.Array_Elements > 0 then
if File_Header.Depth > 0 then
raise Constraint_Error with "OpenGL does not support 3D texture arrays";
elsif File_Header.Height > 0 then
Result.Kind := Texture_2D_Array;
else
Result.Kind := Texture_1D_Array;
end if;
else
if File_Header.Depth > 0 then
Result.Kind := Texture_3D;
elsif File_Header.Height > 0 then
Result.Kind := Texture_2D;
else
Result.Kind := Texture_1D;
end if;
end if;
end if;
Result.Array_Elements := GL.Types.Size (File_Header.Array_Elements);
Result.Mipmap_Levels := GL.Types.Size (File_Header.Mipmap_Levels);
-- If mipmap levels is 0, then client should generate full
-- mipmap pyramid
Result.Bytes_Key_Value := GL.Types.Size (File_Header.Bytes_Key_Value_Data);
if Compressed then
pragma Assert (File_Header.Format = 0);
pragma Assert (File_Header.Type_Size = 1);
pragma Assert (File_Header.Mipmap_Levels > 0);
-- Format / Internal format
begin
Result.Compressed_Format
:= Convert_To_Compressed_Format (File_Header.Internal_Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid internal format (" & File_Header.Internal_Format'Image & ")";
end;
else
-- Data type
begin
Result.Data_Type := Convert_To_Data_Type (File_Header.Data_Type);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid data type (" & File_Header.Data_Type'Image & ")";
end;
-- Format
begin
Result.Format := Convert_To_Format (File_Header.Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid format (" & File_Header.Format'Image & ")";
end;
-- Internal format
begin
Result.Internal_Format
:= Convert_To_Internal_Format (File_Header.Internal_Format);
exception
when Constraint_Error =>
raise Invalid_Enum_Error with
"invalid internal format (" & File_Header.Internal_Format'Image & ")";
end;
end if;
end return;
end Get_Header;
function Get_Key_Value_Map
(Bytes : Bytes_Reference;
Length : GL.Types.Size) return KTX.String_Maps.Map
is
Result : KTX.String_Maps.Map;
Non_Header_Index : constant Stream_Element_Offset := Get_Data_Offset (Bytes, 0);
Data_Index : constant Stream_Element_Offset
:= Non_Header_Index + Stream_Element_Offset (Length);
pragma Assert (Data_Index <= Bytes.Value'Last);
Bytes_Remaining : Natural := Natural (Length);
Pair_Index : Stream_Element_Offset := Non_Header_Index;
begin
while Bytes_Remaining > 0 loop
declare
Key_Value_Size : constant Natural := Get_Length (Bytes, Pair_Index);
Padding_Size : constant Natural := 3 - ((Key_Value_Size + 3) mod 4);
Pair_Size : constant Natural := 4 + Key_Value_Size + Padding_Size;
pragma Assert (Pair_Size <= Bytes_Remaining);
type Key_Value_Array is array (Positive range 1 .. Key_Value_Size) of Stream_Element
with Pack;
type Character_Array is array (Positive range 1 .. Key_Value_Size) of Character
with Pack;
function Convert_Pair is new Ada.Unchecked_Conversion
(Source => Key_Value_Array, Target => Character_Array);
Key_Value_Pair : constant Key_Value_Array := Key_Value_Array (Bytes
(Pair_Index + 4 .. Pair_Index + 4 + Stream_Element_Offset (Key_Value_Size) - 1));
Key_Value : constant String := String (Convert_Pair (Key_Value_Pair));
Position_NUL : constant Natural := Ada.Strings.Fixed.Index
(Key_Value, Ada.Strings.Maps.To_Set (Ada.Characters.Latin_1.NUL));
pragma Assert (Position_NUL > 0);
begin
-- Extract key and value here
declare
Key : constant String := Key_Value (1 .. Position_NUL - 1);
Value : constant String := Key_Value (Position_NUL + 1 .. Key_Value'Last);
begin
Result.Insert (Key, Value);
end;
Bytes_Remaining := Bytes_Remaining - Pair_Size;
Pair_Index := Pair_Index + Stream_Element_Offset (Pair_Size);
end;
end loop;
pragma Assert (Pair_Index = Data_Index);
return Result;
end Get_Key_Value_Map;
function Get_Length
(Bytes : Bytes_Reference;
Offset : Stream_Element_Offset) return Natural
is
Size_Bytes : constant Four_Bytes_Array := Four_Bytes_Array
(Bytes (Offset .. Offset + 4 - 1));
begin
return Natural (Convert_Size (Size_Bytes));
end Get_Length;
function Get_Data_Offset
(Bytes : Bytes_Reference;
Bytes_Key_Value : GL.Types.Size) return Stream_Element_Offset
is (Bytes.Value'First + Identifier'Length + Header_Array'Length
+ Stream_Element_Offset (Bytes_Key_Value));
function Create_KTX_Bytes
(KTX_Header : Header;
Get_Data : not null access function (Level : GL.Objects.Textures.Mipmap_Level)
return Resources.Byte_Array_Pointers.Pointer)
return Resources.Byte_Array_Pointers.Pointer
is
function Convert is new Ada.Unchecked_Conversion
(Source => Internal_Header, Target => Header_Array);
function Convert is new Ada.Unchecked_Conversion
(Source => Unsigned_32, Target => Four_Bytes_Array);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Data_Type, Target => Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Format, Target => Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Internal_Format, Target => Unsigned_32);
function Convert is new Ada.Unchecked_Conversion
(Source => GL.Pixels.Compressed_Format, Target => Unsigned_32);
package PE renames GL.Pixels.Extensions;
Compressed : Boolean renames KTX_Header.Compressed;
Type_Size : constant GL.Types.Size
:= (if Compressed then 1 else PE.Bytes (KTX_Header.Data_Type));
Faces : constant Unsigned_32
:= (if KTX_Header.Kind in Texture_Cube_Map | Texture_Cube_Map_Array then 6 else 1);
File_Header : constant Internal_Header
:= (Endianness => Endianness_Reference,
Data_Type => (if Compressed then 0 else Convert (KTX_Header.Data_Type)),
Type_Size => Unsigned_32 (if Compressed then 1 else Type_Size),
Format => (if Compressed then 0 else Convert (KTX_Header.Format)),
Internal_Format =>
(if Compressed then
Convert (KTX_Header.Compressed_Format)
else
Convert (KTX_Header.Internal_Format)),
Base_Internal_Format =>
(if Compressed then
Convert (KTX_Header.Compressed_Format)
else
Convert (KTX_Header.Format)),
Width => Unsigned_32 (KTX_Header.Width),
Height => Unsigned_32 (KTX_Header.Height),
Depth => Unsigned_32 (if Faces = 6 then 0 else KTX_Header.Depth),
Array_Elements => Unsigned_32 (KTX_Header.Array_Elements),
Faces => Faces,
Mipmap_Levels => Unsigned_32 (KTX_Header.Mipmap_Levels),
Bytes_Key_Value_Data => 0);
-- TODO Support key value map?
Pointer : Resources.Byte_Array_Pointers.Pointer;
--------------------------------------------------------------------------
Data : array (0 .. KTX_Header.Mipmap_Levels - 1) of Resources.Byte_Array_Pointers.Pointer;
Total_Size : Stream_Element_Offset := 0;
begin
for Level in Data'Range loop
Data (Level) := Get_Data (Level);
Total_Size := Total_Size + Data (Level).Get.Value'Length;
end loop;
Total_Size := Total_Size + 4 * Data'Length;
pragma Assert (if not Compressed then
(for all Pointer of Data => Pointer.Get.Value'Length mod 4 = 0));
-- Data must be a multiple of 4 bytes because of the requirement
-- of GL.Pixels.Unpack_Alignment = Words (= 4)
-- Note: assertion is not precise because length of a row might
-- not be a multiple of 4 bytes
-- Note: Cube padding and mipmap padding can be assumed to be 0
declare
Result : constant not null Resources.Byte_Array_Access := new Resources.Byte_Array
(1 .. Identifier'Length + Header_Array'Length + Total_Size);
Header_Offset : constant Stream_Element_Offset := Result'First + Identifier'Length;
Size_Offset : Stream_Element_Offset := Header_Offset + Header_Array'Length;
begin
Result (Result'First .. Header_Offset - 1) := Identifier;
Result (Header_Offset .. Size_Offset - 1) := Stream_Element_Array (Convert (File_Header));
for Level_Data of Data loop
declare
Image_Size : constant Unsigned_32
:= (if KTX_Header.Kind = Texture_Cube_Map then
Level_Data.Get.Value'Length / 6
else
Level_Data.Get.Value'Length);
Data_Offset : constant Stream_Element_Offset := Size_Offset + 4;
Next_Offset : constant Stream_Element_Offset
:= Data_Offset + Level_Data.Get.Value'Length;
begin
Result (Size_Offset .. Data_Offset - 1)
:= Stream_Element_Array (Convert (Image_Size));
Result (Data_Offset .. Next_Offset - 1)
:= Level_Data.Get;
Size_Offset := Next_Offset;
end;
end loop;
Pointer.Set (Result);
return Pointer;
end;
end Create_KTX_Bytes;
end Orka.KTX;
|
Simplify function Get_Key_Value_Map in package Orka.KTX a bit
|
orka: Simplify function Get_Key_Value_Map in package Orka.KTX a bit
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
d5aee58a5b267b8747ce858fa6505057ed259125
|
src/sys/processes/util-processes.ads
|
src/sys/processes/util-processes.ads
|
-----------------------------------------------------------------------
-- util-processes -- Process creation and control
-- Copyright (C) 2011, 2012, 2016, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams;
with Util.Systems.Types;
with Ada.Finalization;
with Ada.Strings.Unbounded;
package Util.Processes is
Invalid_State : exception;
Process_Error : exception;
-- The optional process pipes:
-- <dl>
-- <dt>NONE</dt>
-- <dd>the process will inherit the standard input, output and error.</dd>
-- <dt>READ</dt>
-- <dd>a pipe is created to read the process standard output.</dd>
-- <dt>READ_ERROR</dt>
-- <dd>a pipe is created to read the process standard error. The output and input are
-- inherited.</dd>
-- <dt>READ_ALL</dt>
-- <dd>similar to READ the same pipe is used for the process standard error.</dd>
-- <dt>WRITE</dt>
-- <dd>a pipe is created to write on the process standard input.</dd>
-- <dt>READ_WRITE</dt>
-- <dd>Combines the <b>READ</b> and <b>WRITE</b> modes.</dd>
-- <dt>READ_WRITE_ALL</dt>
-- <dd>Combines the <b>READ_ALL</b> and <b>WRITE</b> modes.</dd>
-- </dl>
type Pipe_Mode is (NONE, READ, READ_ERROR, READ_ALL, WRITE, READ_WRITE, READ_WRITE_ALL);
subtype String_Access is Ada.Strings.Unbounded.String_Access;
subtype File_Type is Util.Systems.Types.File_Type;
type Argument_List is array (Positive range <>) of String_Access;
type Process_Identifier is new Integer;
-- ------------------------------
-- Process
-- ------------------------------
type Process is limited private;
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Input_Stream (Proc : in out Process;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Proc : in out Process;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Proc : in out Process;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Proc : in out Process;
Path : in String);
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Proc : in out Process;
Shell : in String);
-- Closes the given file descriptor in the child process before executing the command.
procedure Add_Close (Proc : in out Process;
Fd : in File_Type);
-- Append the argument to the current process argument list.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Append_Argument (Proc : in out Process;
Arg : in String);
-- Set the environment variable to be used by the process before its creation.
procedure Set_Environment (Proc : in out Process;
Name : in String;
Value : in String);
procedure Set_Environment (Proc : in out Process;
Iterate : not null access
procedure
(Process : not null access procedure
(Name : in String;
Value : in String)));
-- Spawn a new process with the given command and its arguments. The standard input, output
-- and error streams are either redirected to a file or to a stream object.
procedure Spawn (Proc : in out Process;
Command : in String;
Arguments : in Argument_List;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Command : in String;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Mode : in Pipe_Mode := NONE);
-- Wait for the process to terminate.
procedure Wait (Proc : in out Process);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
procedure Stop (Proc : in out Process;
Signal : in Positive := 15);
-- Get the process exit status.
function Get_Exit_Status (Proc : in Process) return Integer;
-- Get the process identifier.
function Get_Pid (Proc : in Process) return Process_Identifier;
-- Returns True if the process is running.
function Is_Running (Proc : in Process) return Boolean;
-- Get the process input stream allowing to write on the process standard input.
function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access;
-- Get the process output stream allowing to read the process standard output.
function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access;
-- Get the process error stream allowing to read the process standard output.
function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access;
private
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
-- The <b>System_Process</b> interface is specific to the system. On Unix, it holds the
-- process identifier. On Windows, more information is necessary, including the process
-- and thread handles. It's a little bit overkill to setup an interface for this but
-- it looks cleaner than having specific system fields here.
type System_Process is limited interface;
type System_Process_Access is access all System_Process'Class;
type Process is new Ada.Finalization.Limited_Controlled with record
Pid : Process_Identifier := -1;
Sys : System_Process_Access := null;
Exit_Value : Integer := -1;
Dir : Ada.Strings.Unbounded.Unbounded_String;
In_File : Ada.Strings.Unbounded.Unbounded_String;
Out_File : Ada.Strings.Unbounded.Unbounded_String;
Err_File : Ada.Strings.Unbounded.Unbounded_String;
Shell : Ada.Strings.Unbounded.Unbounded_String;
Out_Append : Boolean := False;
Err_Append : Boolean := False;
Output : Util.Streams.Input_Stream_Access := null;
Input : Util.Streams.Output_Stream_Access := null;
Error : Util.Streams.Input_Stream_Access := null;
To_Close : File_Type_Array_Access;
end record;
-- Initialize the process instance.
overriding
procedure Initialize (Proc : in out Process);
-- Deletes the process instance.
overriding
procedure Finalize (Proc : in out Process);
-- Wait for the process to exit.
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is abstract;
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is abstract;
-- Spawn a new process.
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is abstract;
-- Clear the program arguments.
procedure Clear_Arguments (Sys : in out System_Process) is abstract;
-- Append the argument to the process argument list.
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is abstract;
-- Set the environment variable to be used by the process before its creation.
procedure Set_Environment (Sys : in out System_Process;
Name : in String;
Value : in String) is abstract;
-- Set the process input, output and error streams to redirect and use specified files.
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access) is abstract;
-- Deletes the storage held by the system process.
procedure Finalize (Sys : in out System_Process) is abstract;
end Util.Processes;
|
-----------------------------------------------------------------------
-- util-processes -- Process creation and control
-- Copyright (C) 2011, 2012, 2016, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams;
with Util.Systems.Types;
with Util.Strings.Vectors;
with Ada.Finalization;
with Ada.Strings.Unbounded;
package Util.Processes is
Invalid_State : exception;
Process_Error : exception;
-- The optional process pipes:
-- <dl>
-- <dt>NONE</dt>
-- <dd>the process will inherit the standard input, output and error.</dd>
-- <dt>READ</dt>
-- <dd>a pipe is created to read the process standard output.</dd>
-- <dt>READ_ERROR</dt>
-- <dd>a pipe is created to read the process standard error. The output and input are
-- inherited.</dd>
-- <dt>READ_ALL</dt>
-- <dd>similar to READ the same pipe is used for the process standard error.</dd>
-- <dt>WRITE</dt>
-- <dd>a pipe is created to write on the process standard input.</dd>
-- <dt>READ_WRITE</dt>
-- <dd>Combines the <b>READ</b> and <b>WRITE</b> modes.</dd>
-- <dt>READ_WRITE_ALL</dt>
-- <dd>Combines the <b>READ_ALL</b> and <b>WRITE</b> modes.</dd>
-- </dl>
type Pipe_Mode is (NONE, READ, READ_ERROR, READ_ALL, WRITE, READ_WRITE, READ_WRITE_ALL);
subtype String_Access is Ada.Strings.Unbounded.String_Access;
subtype File_Type is Util.Systems.Types.File_Type;
type Argument_List is array (Positive range <>) of String_Access;
type Process_Identifier is new Integer;
-- ------------------------------
-- Process
-- ------------------------------
type Process is limited private;
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Input_Stream (Proc : in out Process;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Proc : in out Process;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Proc : in out Process;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Proc : in out Process;
Path : in String);
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Proc : in out Process;
Shell : in String);
-- Closes the given file descriptor in the child process before executing the command.
procedure Add_Close (Proc : in out Process;
Fd : in File_Type);
-- Append the argument to the current process argument list.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Append_Argument (Proc : in out Process;
Arg : in String);
-- Set the environment variable to be used by the process before its creation.
procedure Set_Environment (Proc : in out Process;
Name : in String;
Value : in String);
procedure Set_Environment (Proc : in out Process;
Iterate : not null access
procedure
(Process : not null access procedure
(Name : in String;
Value : in String)));
-- Spawn a new process with the given command and its arguments. The standard input, output
-- and error streams are either redirected to a file or to a stream object.
procedure Spawn (Proc : in out Process;
Command : in String;
Arguments : in Argument_List;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Arguments : in Util.Strings.Vectors.Vector;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Command : in String;
Mode : in Pipe_Mode := NONE);
procedure Spawn (Proc : in out Process;
Mode : in Pipe_Mode := NONE);
-- Wait for the process to terminate.
procedure Wait (Proc : in out Process);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
procedure Stop (Proc : in out Process;
Signal : in Positive := 15);
-- Get the process exit status.
function Get_Exit_Status (Proc : in Process) return Integer;
-- Get the process identifier.
function Get_Pid (Proc : in Process) return Process_Identifier;
-- Returns True if the process is running.
function Is_Running (Proc : in Process) return Boolean;
-- Get the process input stream allowing to write on the process standard input.
function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access;
-- Get the process output stream allowing to read the process standard output.
function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access;
-- Get the process error stream allowing to read the process standard output.
function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access;
private
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
-- The <b>System_Process</b> interface is specific to the system. On Unix, it holds the
-- process identifier. On Windows, more information is necessary, including the process
-- and thread handles. It's a little bit overkill to setup an interface for this but
-- it looks cleaner than having specific system fields here.
type System_Process is limited interface;
type System_Process_Access is access all System_Process'Class;
type Process is new Ada.Finalization.Limited_Controlled with record
Pid : Process_Identifier := -1;
Sys : System_Process_Access := null;
Exit_Value : Integer := -1;
Dir : Ada.Strings.Unbounded.Unbounded_String;
In_File : Ada.Strings.Unbounded.Unbounded_String;
Out_File : Ada.Strings.Unbounded.Unbounded_String;
Err_File : Ada.Strings.Unbounded.Unbounded_String;
Shell : Ada.Strings.Unbounded.Unbounded_String;
Out_Append : Boolean := False;
Err_Append : Boolean := False;
Output : Util.Streams.Input_Stream_Access := null;
Input : Util.Streams.Output_Stream_Access := null;
Error : Util.Streams.Input_Stream_Access := null;
To_Close : File_Type_Array_Access;
end record;
-- Initialize the process instance.
overriding
procedure Initialize (Proc : in out Process);
-- Deletes the process instance.
overriding
procedure Finalize (Proc : in out Process);
-- Wait for the process to exit.
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is abstract;
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is abstract;
-- Spawn a new process.
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is abstract;
-- Clear the program arguments.
procedure Clear_Arguments (Sys : in out System_Process) is abstract;
-- Append the argument to the process argument list.
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is abstract;
-- Set the environment variable to be used by the process before its creation.
procedure Set_Environment (Sys : in out System_Process;
Name : in String;
Value : in String) is abstract;
-- Set the process input, output and error streams to redirect and use specified files.
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access) is abstract;
-- Deletes the storage held by the system process.
procedure Finalize (Sys : in out System_Process) is abstract;
end Util.Processes;
|
Add a Spawn procedure that accepts a string Vector for the arguments
|
Add a Spawn procedure that accepts a string Vector for the arguments
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b5fbeb052e4dbe42ea28127fba3b0b631765d79d
|
awa/awaunit/awa-tests-helpers-users.adb
|
awa/awaunit/awa-tests-helpers-users.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Tests;
with Util.Log.Loggers;
with AWA.Applications;
with AWA.Tests;
with AWA.Users.Modules;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Tests.Helpers.Users is
use AWA.Users.Services;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users");
-- ------------------------------
-- Initialize the service context.
-- ------------------------------
procedure Initialize (Principal : in out Test_User) is
begin
if Principal.Manager = null then
Principal.Manager := AWA.Users.Modules.Get_User_Manager;
if Principal.Manager = null then
Log.Error ("There is no User_Manager in the application.");
end if;
end if;
-- Setup the service context.
Principal.Context.Set_Context (AWA.Tests.Get_Application, null);
end Initialize;
-- ------------------------------
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
-- ------------------------------
procedure Create_User (Principal : in out Test_User;
Email : in String) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the user
Query.Set_Join ("inner join email e on e.user_id = o.id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Principal.User.Find (DB, Query, Found);
if not Found then
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
else
Principal.Manager.Authenticate (Email => Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
end if;
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Create a test user for a new test and get an open session.
-- ------------------------------
procedure Create_User (Principal : in out Test_User) is
Key : AWA.Users.Models.Access_Key_Ref;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
begin
Initialize (Principal);
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Find the access key associated with a user (if any).
-- ------------------------------
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the access key
Query.Set_Join ("inner join email e on e.user_id = o.user_id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Key.Find (DB, Query, Found);
end Find_Access_Key;
-- ------------------------------
-- Login a user and create a session
-- ------------------------------
procedure Login (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Authenticate (Email => Principal.Email.Get_Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Login;
-- ------------------------------
-- Logout the user and closes the current session.
-- ------------------------------
procedure Logout (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Close_Session (Principal.Session.Get_Id, True);
end Logout;
-- Simulate a user login in the given service context.
procedure Login (Context : in out AWA.Services.Contexts.Service_Context;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String) is
User : Test_User;
Principal : AWA.Users.Principals.Principal_Access;
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Create_User (User, Email);
Principal := AWA.Users.Principals.Create (User.User, User.Session);
Context.Set_Context (App, Principal);
Sec_Context.Set_Context (Manager => App.Get_Permission_Manager,
Principal => Principal.all'Access);
end Login;
overriding
procedure Finalize (Principal : in out Test_User) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class,
Name => AWA.Users.Principals.Principal_Access);
begin
Free (Principal.Principal);
end Finalize;
end AWA.Tests.Helpers.Users;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Tests;
with Util.Log.Loggers;
with AWA.Applications;
with AWA.Tests;
with AWA.Users.Modules;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Tests.Helpers.Users is
use AWA.Users.Services;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users");
-- ------------------------------
-- Initialize the service context.
-- ------------------------------
procedure Initialize (Principal : in out Test_User) is
begin
-- Setup the service context.
Principal.Context.Set_Context (AWA.Tests.Get_Application, null);
if Principal.Manager = null then
Principal.Manager := AWA.Users.Modules.Get_User_Manager;
if Principal.Manager = null then
Log.Error ("There is no User_Manager in the application.");
end if;
end if;
end Initialize;
-- ------------------------------
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
-- ------------------------------
procedure Create_User (Principal : in out Test_User;
Email : in String) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the user
Query.Set_Join ("inner join email e on e.user_id = o.id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Principal.User.Find (DB, Query, Found);
if not Found then
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
else
Principal.Manager.Authenticate (Email => Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
end if;
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Create a test user for a new test and get an open session.
-- ------------------------------
procedure Create_User (Principal : in out Test_User) is
Key : AWA.Users.Models.Access_Key_Ref;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
begin
Initialize (Principal);
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Find the access key associated with a user (if any).
-- ------------------------------
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the access key
Query.Set_Join ("inner join email e on e.user_id = o.user_id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Key.Find (DB, Query, Found);
if not Found then
Log.Error ("Cannot find access key for email {0}", Email);
end if;
end Find_Access_Key;
-- ------------------------------
-- Login a user and create a session
-- ------------------------------
procedure Login (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Authenticate (Email => Principal.Email.Get_Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Login;
-- ------------------------------
-- Logout the user and closes the current session.
-- ------------------------------
procedure Logout (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Close_Session (Principal.Session.Get_Id, True);
end Logout;
-- Simulate a user login in the given service context.
procedure Login (Context : in out AWA.Services.Contexts.Service_Context;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String) is
User : Test_User;
Principal : AWA.Users.Principals.Principal_Access;
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Create_User (User, Email);
Principal := AWA.Users.Principals.Create (User.User, User.Session);
Context.Set_Context (App, Principal);
Sec_Context.Set_Context (Manager => App.Get_Permission_Manager,
Principal => Principal.all'Access);
end Login;
overriding
procedure Finalize (Principal : in out Test_User) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class,
Name => AWA.Users.Principals.Principal_Access);
begin
Free (Principal.Principal);
end Finalize;
end AWA.Tests.Helpers.Users;
|
Set the application context first to make sure it is ready for other operations (the application context is setup by the AWA service filter in real life, but this is not available for unit tests)
|
Set the application context first to make sure it is ready for other operations
(the application context is setup by the AWA service filter in real
life, but this is not available for unit tests)
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
52ed7086c1d585935f8bb3126669081f014d3294
|
src/gen-commands-page.adb
|
src/gen-commands-page.adb
|
-----------------------------------------------------------------------
-- gen-commands-page -- Page creation command for dynamo
-- 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.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with Util.Strings.Transforms;
package body Gen.Commands.Page is
-- ------------------------------
-- 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;
use Ada.Strings.Unbounded;
function Get_Layout return String;
Name : constant String := Get_Argument;
Dir : constant String := Generator.Get_Result_Directory & "web/";
function Get_Layout return String is
Layout : constant String := Get_Argument;
begin
if Layout'Length = 0 then
return "layout";
end if;
if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then
return Layout;
end if;
Generator.Error ("Layout file {0} not found. Using 'layout' instead.", Layout);
return "layout";
end Get_Layout;
Layout : constant String := Get_Layout;
begin
if Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Dir);
Generator.Set_Global ("pageName", Name);
Generator.Set_Global ("layout", Layout);
Generator.Set_Global ("projectCode", Util.Strings.Transforms.To_Upper_Case (Name));
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Text_IO;
use Ada.Directories;
Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts";
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Put_Line ("add-page: Add a new web page to the application");
Put_Line ("Usage: add-page NAME [LAYOUT]");
New_Line;
Put_Line (" The new web page can be configured to use the given layout.");
Put_Line (" The layout file must exist to be used. The default layout is 'layout'.");
Put_Line (" You can create a new layout with 'add-layout' command.");
Put_Line (" You can also write your layout by adding an XHTML file in the directory:");
Put_Line (" " & Path);
if Exists (Path) then
New_Line;
Put_Line (" Available layouts:");
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Layout : constant String := Base_Name (Name);
begin
Put_Line (" " & Layout);
end;
end loop;
end if;
end Help;
end Gen.Commands.Page;
|
-----------------------------------------------------------------------
-- gen-commands-page -- Page creation command for dynamo
-- 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.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
package body Gen.Commands.Page is
-- ------------------------------
-- 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;
use Ada.Strings.Unbounded;
function Get_Layout return String;
Name : constant String := Get_Argument;
Dir : constant String := Generator.Get_Result_Directory & "web/";
function Get_Layout return String is
Layout : constant String := Get_Argument;
begin
if Layout'Length = 0 then
return "layout";
end if;
if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then
return Layout;
end if;
Generator.Error ("Layout file {0} not found. Using 'layout' instead.", Layout);
return "layout";
end Get_Layout;
Layout : constant String := Get_Layout;
begin
if Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Dir);
Generator.Set_Global ("pageName", Name);
Generator.Set_Global ("layout", Layout);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Text_IO;
use Ada.Directories;
Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts";
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Put_Line ("add-page: Add a new web page to the application");
Put_Line ("Usage: add-page NAME [LAYOUT]");
New_Line;
Put_Line (" The new web page can be configured to use the given layout.");
Put_Line (" The layout file must exist to be used. The default layout is 'layout'.");
Put_Line (" You can create a new layout with 'add-layout' command.");
Put_Line (" You can also write your layout by adding an XHTML file in the directory:");
Put_Line (" " & Path);
if Exists (Path) then
New_Line;
Put_Line (" Available layouts:");
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Layout : constant String := Base_Name (Name);
begin
Put_Line (" " & Layout);
end;
end loop;
end if;
end Help;
end Gen.Commands.Page;
|
Remove projectCode global
|
Remove projectCode global
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
c2c0bd3e1f098bb26a1cdc2351445fd64de35e42
|
tools/druss-commands.ads
|
tools/druss-commands.ads
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- 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.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_WAN_IP,
F_INTERNET,
F_VOIP,
F_WIFI,
F_WIFI5,
F_ACCESS_CONTROL,
F_DYNDNS,
F_DEVICES,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type);
procedure Initialize;
-- Print the bbox API status.
procedure Print_Status (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a ON/OFF status.
procedure Print_On_Off (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
end Druss.Commands;
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- 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.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_BBOX_IP_ADDR,
F_WAN_IP,
F_ETHERNET,
F_INTERNET,
F_VOIP,
F_HOSTNAME,
F_CONNECTION,
F_DEVTYPE,
F_ACTIVE,
F_LINK,
F_WIFI,
F_WIFI5,
F_ACCESS_CONTROL,
F_DYNDNS,
F_DEVICES,
F_UPTIME,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_USAGE,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type);
procedure Initialize;
-- Print the bbox API status.
procedure Print_Status (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a ON/OFF status.
procedure Print_On_Off (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a uptime.
procedure Print_Uptime (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
end Druss.Commands;
|
Declare Print_Uptime procedure and add several fields
|
Declare Print_Uptime procedure and add several fields
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
334d9a9484841abf26d290d3853fbb5b6a9432c4
|
mat/src/mat-targets.adb
|
mat/src/mat-targets.adb
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with GNAT.Command_Line;
with Readline;
with Util.Strings;
with Util.Log.Loggers;
with MAT.Commands;
with MAT.Targets.Readers;
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Set the console instance.
-- ------------------------------
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access) is
begin
Target.Console := Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Targets.Readers.Initialize (Target => Target,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access) is
Path_String : constant String := Ada.Strings.Unbounded.To_String (Path);
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Process.Path := Path;
Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create;
Target.Processes.Insert (Pid, Process);
Target.Console.Notice (MAT.Consoles.N_PID_INFO,
"Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created");
Target.Console.Notice (MAT.Consoles.N_PATH_INFO,
"Path " & Path_String);
end if;
if Target.Current = null then
Target.Current := Process;
end if;
if Target.Options.Load_Symbols then
MAT.Commands.Symbol_Command (Target, Path_String);
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
-- ------------------------------
-- 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)) is
Iter : Process_Cursor := Target.Processes.First;
begin
while Process_Maps.Has_Element (Iter) loop
Process (Process_Maps.Element (Iter).all);
Process_Maps.Next (Iter);
end loop;
end Iterator;
-- ------------------------------
-- 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 is
Pos : constant Natural := Util.Strings.Index (Param, ':');
Result : GNAT.Sockets.Sock_Addr_Type;
begin
if Pos > 0 then
Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last));
Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1));
else
Result.Port := GNAT.Sockets.Port_Type'Value (Param);
Result.Addr := GNAT.Sockets.Any_Inet_Addr;
end if;
return Result;
end To_Sock_Addr_Type;
-- ------------------------------
-- Print the application usage.
-- ------------------------------
procedure Usage is
use Ada.Text_IO;
begin
Put_Line ("Usage: mat [-i] [-nw] [-ns] [-b [ip:]port] [file.mat]");
Put_Line ("-i Enable the interactive mode");
Put_Line ("-nw Disable the graphical mode");
Put_Line ("-b [ip:]port Define the port and local address to bind");
Put_Line ("-ns Disable the automatic symbols loading");
Ada.Command_Line.Set_Exit_Status (2);
raise Usage_Error;
end Usage;
-- ------------------------------
-- Parse the command line arguments and configure the target instance.
-- ------------------------------
procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is
begin
Util.Log.Loggers.Initialize ("matp.properties");
GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True,
Section_Delimiters => "targs");
loop
case GNAT.Command_Line.Getopt ("i nw ns b:") is
when ASCII.NUL =>
exit;
when 'i' =>
Target.Options.Interactive := True;
when 'b' =>
Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter);
when 'n' =>
if GNAT.Command_Line.Full_Switch = "nw" then
Target.Options.Graphical := False;
else
Target.Options.Load_Symbols := False;
end if;
when '*' =>
exit;
when others =>
Usage;
end case;
end loop;
exception
when Usage_Error =>
raise;
when others =>
Usage;
end Initialize_Options;
-- ------------------------------
-- 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) is
begin
loop
declare
Line : constant String := Readline.Get_Line ("matp>");
begin
MAT.Commands.Execute (Target, Line);
exception
when MAT.Commands.Stop_Interp =>
exit;
end;
end loop;
end Interactive;
-- ------------------------------
-- Start the server to listen to MAT event socket streams.
-- ------------------------------
procedure Start (Target : in out Target_Type) is
begin
Target.Server.Start (Target'Unchecked_Access, Target.Options.Address);
end Start;
-- ------------------------------
-- Stop the server thread.
-- ------------------------------
procedure Stop (Target : in out Target_Type) is
begin
Target.Server.Stop;
end Stop;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Command_Line;
with GNAT.Command_Line;
with Readline;
with Util.Strings;
with Util.Log.Loggers;
with MAT.Commands;
with MAT.Targets.Readers;
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Set the console instance.
-- ------------------------------
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access) is
begin
Target.Console := Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Targets.Readers.Initialize (Target => Target,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access) is
Path_String : constant String := Ada.Strings.Unbounded.To_String (Path);
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Process.Path := Path;
Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create;
Target.Processes.Insert (Pid, Process);
Target.Console.Notice (MAT.Consoles.N_PID_INFO,
"Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created");
Target.Console.Notice (MAT.Consoles.N_PATH_INFO,
"Path " & Path_String);
end if;
if Target.Current = null then
Target.Current := Process;
end if;
if Target.Options.Load_Symbols then
MAT.Commands.Symbol_Command (Target, Path_String);
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
-- ------------------------------
-- 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)) is
Iter : Process_Cursor := Target.Processes.First;
begin
while Process_Maps.Has_Element (Iter) loop
Process (Process_Maps.Element (Iter).all);
Process_Maps.Next (Iter);
end loop;
end Iterator;
-- ------------------------------
-- 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 is
Pos : constant Natural := Util.Strings.Index (Param, ':');
Result : GNAT.Sockets.Sock_Addr_Type;
begin
if Pos > 0 then
Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last));
Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1));
else
Result.Port := GNAT.Sockets.Port_Type'Value (Param);
Result.Addr := GNAT.Sockets.Any_Inet_Addr;
end if;
return Result;
end To_Sock_Addr_Type;
-- ------------------------------
-- Print the application usage.
-- ------------------------------
procedure Usage is
use Ada.Text_IO;
begin
Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [file.mat]");
Put_Line ("-i Enable the interactive mode");
Put_Line ("-e Print the probe events as they are received");
Put_Line ("-nw Disable the graphical mode");
Put_Line ("-b [ip:]port Define the port and local address to bind");
Put_Line ("-ns Disable the automatic symbols loading");
Ada.Command_Line.Set_Exit_Status (2);
raise Usage_Error;
end Usage;
-- ------------------------------
-- Parse the command line arguments and configure the target instance.
-- ------------------------------
procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is
begin
Util.Log.Loggers.Initialize ("matp.properties");
GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True,
Section_Delimiters => "targs");
loop
case GNAT.Command_Line.Getopt ("i e nw ns b:") is
when ASCII.NUL =>
exit;
when 'i' =>
Target.Options.Interactive := True;
when 'e' =>
Target.Options.Print_Events := True;
when 'b' =>
Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter);
when 'n' =>
if GNAT.Command_Line.Full_Switch = "nw" then
Target.Options.Graphical := False;
else
Target.Options.Load_Symbols := False;
end if;
when '*' =>
exit;
when others =>
Usage;
end case;
end loop;
exception
when Usage_Error =>
raise;
when others =>
Usage;
end Initialize_Options;
-- ------------------------------
-- 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) is
begin
loop
declare
Line : constant String := Readline.Get_Line ("matp>");
begin
MAT.Commands.Execute (Target, Line);
exception
when MAT.Commands.Stop_Interp =>
exit;
end;
end loop;
end Interactive;
-- ------------------------------
-- Start the server to listen to MAT event socket streams.
-- ------------------------------
procedure Start (Target : in out Target_Type) is
begin
Target.Server.Start (Target'Unchecked_Access, Target.Options.Address);
end Start;
-- ------------------------------
-- Stop the server thread.
-- ------------------------------
procedure Stop (Target : in out Target_Type) is
begin
Target.Server.Stop;
end Stop;
end MAT.Targets;
|
Add new option -e and set the Print_Events flag
|
Add new option -e and set the Print_Events flag
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
b5fe3b286770d5e489f003224fa14095fff65b78
|
src/ado-datasets.adb
|
src/ado-datasets.adb
|
-----------------------------------------------------------------------
-- ado-datasets -- Datasets
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects.Time;
with ADO.Schemas;
with ADO.Statements;
package body ADO.Datasets is
-- ------------------------------
-- Execute the SQL query on the database session and populate the dataset.
-- The column names are used to setup the dataset row bean definition.
-- ------------------------------
procedure List (Into : in out Dataset;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.Queries.Context'Class) is
procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array);
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array) is
use ADO.Schemas;
begin
for I in Data'Range loop
case Stmt.Get_Column_Type (I - 1) is
-- Boolean column
when T_BOOLEAN =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Boolean (I - 1));
when T_TINYINT | T_SMALLINT | T_INTEGER | T_LONG_INTEGER | T_YEAR =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Integer (I - 1));
when T_FLOAT | T_DOUBLE | T_DECIMAL =>
Data (I) := Util.Beans.Objects.Null_Object;
when T_ENUM =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1));
when T_TIME | T_DATE | T_DATE_TIME | T_TIMESTAMP =>
Data (I) := Util.Beans.Objects.Time.To_Object (Stmt.Get_Time (I - 1));
when T_CHAR | T_VARCHAR =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1));
when T_BLOB =>
Data (I) := Util.Beans.Objects.Null_Object;
when T_SET | T_UNKNOWN | T_NULL =>
Data (I) := Util.Beans.Objects.Null_Object;
end case;
end loop;
end Fill;
begin
Stmt.Execute;
Into.Clear;
if Stmt.Has_Elements then
for I in 1 .. Stmt.Get_Column_Count loop
Into.Add_Column (Stmt.Get_Column_Name (I - 1));
end loop;
while Stmt.Has_Elements loop
Into.Append (Fill'Access);
Stmt.Next;
end loop;
end if;
end List;
end ADO.Datasets;
|
-----------------------------------------------------------------------
-- ado-datasets -- Datasets
-- Copyright (C) 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects.Time;
with ADO.Schemas;
with ADO.Statements;
package body ADO.Datasets is
-- ------------------------------
-- Execute the SQL query on the database session and populate the dataset.
-- The column names are used to setup the dataset row bean definition.
-- ------------------------------
procedure List (Into : in out Dataset;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.Queries.Context'Class) is
procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array);
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array) is
use ADO.Schemas;
begin
for I in Data'Range loop
case Stmt.Get_Column_Type (I - 1) is
-- Boolean column
when T_BOOLEAN =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Boolean (I - 1));
when T_TINYINT | T_SMALLINT | T_INTEGER | T_LONG_INTEGER | T_YEAR =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Integer (I - 1));
when T_FLOAT | T_DOUBLE | T_DECIMAL =>
Data (I) := Util.Beans.Objects.Null_Object;
when T_ENUM =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1));
when T_TIME | T_DATE | T_DATE_TIME | T_TIMESTAMP =>
Data (I) := Util.Beans.Objects.Time.To_Object (Stmt.Get_Time (I - 1));
when T_CHAR | T_VARCHAR =>
Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1));
when T_BLOB =>
Data (I) := Util.Beans.Objects.Null_Object;
when T_SET | T_UNKNOWN | T_NULL =>
Data (I) := Util.Beans.Objects.Null_Object;
end case;
end loop;
end Fill;
begin
Stmt.Execute;
Into.Clear;
if Stmt.Has_Elements then
for I in 1 .. Stmt.Get_Column_Count loop
Into.Add_Column (Stmt.Get_Column_Name (I - 1));
end loop;
while Stmt.Has_Elements loop
Into.Append (Fill'Access);
Stmt.Next;
end loop;
end if;
end List;
-- ------------------------------
-- Get the number of items in a list by executing an SQL query.
-- ------------------------------
function Get_Count (Session : in ADO.Sessions.Session'Class;
Query : in ADO.Queries.Context'Class) return Natural is
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
return Stmt.Get_Result_Integer;
end Get_Count;
end ADO.Datasets;
|
Implement the Get_Count function
|
Implement the Get_Count function
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
2cd388fb7930a51e277a920c6e01e91a8f62a932
|
src/ado-sessions.adb
|
src/ado-sessions.adb
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ADO.Drivers;
with ADO.Sequences;
with ADO.Statements.Create;
package body ADO.Sessions is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions");
procedure Check_Session (Database : in Session'Class;
Message : in String := "") is
begin
if Database.Impl = null then
Log.Error ("Session is closed or not initialized");
raise Session_Error;
end if;
if Message'Length > 0 then
Log.Info (Message, Database.Impl.Database.Value.Ident);
end if;
end Check_Session;
-- ---------
-- Session
-- ---------
-- ------------------------------
-- Get the session status.
-- ------------------------------
function Get_Status (Database : in Session) return Connection_Status is
begin
if Database.Impl = null or else Database.Impl.Database.Is_Null then
return CLOSED;
else
return OPEN;
end if;
end Get_Status;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is
begin
if Database.Impl = null or else Database.Impl.Database.Is_Null then
return null;
else
return Database.Impl.Database.Value.Get_Driver;
end if;
end Get_Driver;
-- ------------------------------
-- Close the session.
-- ------------------------------
procedure Close (Database : in out Session) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
Is_Zero : Boolean;
begin
Log.Info ("Closing session");
if Database.Impl /= null then
ADO.Objects.Release_Proxy (Database.Impl.Proxy);
Database.Impl.Database.Value.Close;
Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero);
if Is_Zero then
Free (Database.Impl);
end if;
Database.Impl := null;
end if;
end Close;
-- ------------------------------
-- Insert a new cache in the manager. The cache is identified by the given name.
-- ------------------------------
procedure Add_Cache (Database : in out Session;
Name : in String;
Cache : in ADO.Caches.Cache_Type_Access) is
begin
Check_Session (Database);
Database.Impl.Values.Add_Cache (Name, Cache);
end Add_Cache;
-- ------------------------------
-- Attach the object to the session.
-- ------------------------------
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class) is
pragma Unreferenced (Object);
begin
Check_Session (Database);
end Attach;
-- ------------------------------
-- Check if the session contains the object identified by the given key.
-- ------------------------------
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean is
begin
Check_Session (Database);
return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item);
end Contains;
-- ------------------------------
-- Remove the object from the session cache.
-- ------------------------------
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key) is
begin
Check_Session (Database);
ADO.Objects.Cache.Remove (Database.Impl.Cache, Item);
end Evict;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Query : constant Query_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Query_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Query);
begin
return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all);
Stmt : Query_Statement := Database.Create_Statement (SQL);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement and initialize the SQL statement with the query definition.
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False);
begin
return Database.Create_Statement (SQL);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Stmt : Query_Statement := Database.Create_Statement (Table);
begin
if Query in ADO.Queries.Context'Class then
declare
SQL : constant String
:= ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all);
begin
ADO.SQL.Append (Stmt.Get_Query.SQL, SQL);
end;
end if;
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition) is
begin
Check_Session (Database, "Loading schema {0}");
Database.Impl.Database.Value.Load_Schema (Schema);
end Load_Schema;
-- ---------
-- Master Session
-- ---------
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Session) is
begin
Check_Session (Database, "Begin transaction {0}");
Database.Impl.Database.Value.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Session) is
begin
Check_Session (Database, "Commit transaction {0}");
Database.Impl.Database.Value.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Session) is
begin
Check_Session (Database, "Rollback transaction {0}");
Database.Impl.Database.Value.Rollback;
end Rollback;
-- ------------------------------
-- Allocate an identifier for the table.
-- ------------------------------
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class) is
begin
Check_Session (Database);
ADO.Sequences.Allocate (Database.Sequences.all, Id);
end Allocate;
-- ------------------------------
-- Flush the objects that were modified.
-- ------------------------------
procedure Flush (Database : in out Master_Session) is
begin
Check_Session (Database);
end Flush;
overriding
procedure Adjust (Object : in out Session) is
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Increment (Object.Impl.Counter);
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Session) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
Is_Zero : Boolean;
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero);
if Is_Zero then
ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True);
if not Object.Impl.Database.Is_Null then
Object.Impl.Database.Value.Close;
end if;
Free (Object.Impl);
end if;
Object.Impl := null;
end if;
end Finalize;
-- ------------------------------
-- Create a delete statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Delete_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access,
Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an update statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Update_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access,
Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an insert statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Insert_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access,
Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
-- ------------------------------
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is
use type ADO.Objects.Session_Proxy_Access;
begin
Check_Session (Database);
if Database.Impl.Proxy = null then
Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl);
end if;
return Database.Impl.Proxy;
end Get_Session_Proxy;
end ADO.Sessions;
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ADO.Drivers;
with ADO.Sequences;
with ADO.Statements.Create;
package body ADO.Sessions is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions");
procedure Check_Session (Database : in Session'Class;
Message : in String := "") is
begin
if Database.Impl = null then
Log.Error ("Session is closed or not initialized");
raise Session_Error;
end if;
if Message'Length > 0 then
Log.Info (Message, Database.Impl.Database.Value.Ident);
end if;
end Check_Session;
-- ---------
-- Session
-- ---------
-- ------------------------------
-- Get the session status.
-- ------------------------------
function Get_Status (Database : in Session) return Connection_Status is
begin
if Database.Impl = null or else Database.Impl.Database.Is_Null then
return CLOSED;
else
return OPEN;
end if;
end Get_Status;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is
begin
if Database.Impl = null or else Database.Impl.Database.Is_Null then
return null;
else
return Database.Impl.Database.Value.Get_Driver;
end if;
end Get_Driver;
-- ------------------------------
-- Close the session.
-- ------------------------------
procedure Close (Database : in out Session) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
Is_Zero : Boolean;
begin
Log.Info ("Closing session");
if Database.Impl /= null then
ADO.Objects.Release_Proxy (Database.Impl.Proxy);
Database.Impl.Database.Value.Close;
Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero);
if Is_Zero then
Free (Database.Impl);
end if;
Database.Impl := null;
end if;
end Close;
-- ------------------------------
-- Insert a new cache in the manager. The cache is identified by the given name.
-- ------------------------------
procedure Add_Cache (Database : in out Session;
Name : in String;
Cache : in ADO.Caches.Cache_Type_Access) is
begin
Check_Session (Database);
Database.Impl.Values.Add_Cache (Name, Cache);
end Add_Cache;
-- ------------------------------
-- Attach the object to the session.
-- ------------------------------
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class) is
pragma Unreferenced (Object);
begin
Check_Session (Database);
end Attach;
-- ------------------------------
-- Check if the session contains the object identified by the given key.
-- ------------------------------
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean is
begin
Check_Session (Database);
return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item);
end Contains;
-- ------------------------------
-- Remove the object from the session cache.
-- ------------------------------
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key) is
begin
Check_Session (Database);
ADO.Objects.Cache.Remove (Database.Impl.Cache, Item);
end Evict;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Query : constant Query_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Query_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Query);
begin
return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all);
Stmt : Query_Statement := Database.Create_Statement (SQL);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement and initialize the SQL statement with the query definition.
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False);
begin
return Database.Create_Statement (SQL);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Stmt : Query_Statement := Database.Create_Statement (Table);
begin
if Query in ADO.Queries.Context'Class then
declare
SQL : constant String
:= ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all);
begin
ADO.SQL.Append (Stmt.Get_Query.SQL, SQL);
end;
end if;
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition) is
begin
Check_Session (Database, "Loading schema {0}");
Database.Impl.Database.Value.Load_Schema (Schema);
end Load_Schema;
-- ---------
-- Master Session
-- ---------
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Session) is
begin
Check_Session (Database, "Begin transaction {0}");
Database.Impl.Database.Value.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Session) is
begin
Check_Session (Database, "Commit transaction {0}");
Database.Impl.Database.Value.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Session) is
begin
Check_Session (Database, "Rollback transaction {0}");
Database.Impl.Database.Value.Rollback;
end Rollback;
-- ------------------------------
-- Allocate an identifier for the table.
-- ------------------------------
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class) is
begin
Check_Session (Database);
ADO.Sequences.Allocate (Database.Sequences.all, Id);
end Allocate;
-- ------------------------------
-- Flush the objects that were modified.
-- ------------------------------
procedure Flush (Database : in out Master_Session) is
begin
Check_Session (Database);
end Flush;
overriding
procedure Adjust (Object : in out Session) is
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Increment (Object.Impl.Counter);
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Session) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
Is_Zero : Boolean;
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero);
if Is_Zero then
ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True);
if not Object.Impl.Database.Is_Null then
Object.Impl.Database.Value.Close;
end if;
Free (Object.Impl);
end if;
Object.Impl := null;
end if;
end Finalize;
-- ------------------------------
-- Create a delete statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Delete_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access,
Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an update statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Update_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access,
Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an insert statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Insert_Statement_Access
:= Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access,
Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Internal operation to get access to the database connection.
-- ------------------------------
procedure Access_Connection (Database : in out Master_Session;
Process : not null access
procedure (Connection : in out Database_Connection'Class)) is
begin
Check_Session (Database);
Process (Database.Impl.Database.Value.all);
end Access_Connection;
-- ------------------------------
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
-- ------------------------------
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is
use type ADO.Objects.Session_Proxy_Access;
begin
Check_Session (Database);
if Database.Impl.Proxy = null then
Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl);
end if;
return Database.Impl.Proxy;
end Get_Session_Proxy;
end ADO.Sessions;
|
Implement the Access_Connection procedure
|
Implement the Access_Connection procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
b7f481b5f928018382d48fff02e5d66df0b912eb
|
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 AWA.Modules;
package Awa.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
-- ------------------------------
-- 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;
private
type Wiki_Module is new AWA.Modules.Module with null record;
end Awa.Wikis.Modules;
|
-----------------------------------------------------------------------
-- 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 Security.Permissions;
with AWA.Modules;
package AWA.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
-- 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");
-- ------------------------------
-- 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;
private
type Wiki_Module is new AWA.Modules.Module with null record;
end AWA.Wikis.Modules;
|
Declare the permissions to create/update/delete a wiki space
|
Declare the permissions to create/update/delete a wiki space
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
aced740a69a983db610970966db2ecffb3237485
|
src/gen-artifacts-docs.ads
|
src/gen-artifacts-docs.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-docs -- Artifact for documentation
-- Copyright (C) 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 Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Gen.Model.Packages;
private with Util.Strings.Maps;
-- with Asis;
-- with Asis.Text;
-- with Asis.Elements;
-- with Asis.Exceptions;
-- with Asis.Errors;
-- with Asis.Implementation;
-- with Asis.Elements;
-- with Asis.Declarations;
-- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of
-- application documentation. Its purpose is to scan the project source files
-- and extract some interesting information for a developer's guide. The artifact
-- scans the Ada source files, the XML configuration files, the XHTML files.
--
-- The generated documentation is intended to be published on a web site.
-- The Google Wiki style is generated by default.
--
-- 1/ In the first step, the project files are scanned and the useful
-- documentation is extracted.
--
-- 2/ In the second step, the documentation is merged and reconciled. Links to
-- documentation pages and references are setup and the final pages are generated.
--
-- Ada
-- ---
-- The documentation starts at the first '== TITLE ==' marker and finishes before the
-- package specification.
--
-- XHTML
-- -----
-- Same as Ada.
--
-- XML Files
-- ----------
-- The documentation is part of the XML and the <b>documentation</b> or <b>description</b>
-- tags are extracted.
package Gen.Artifacts.Docs is
-- Tag marker (same as Java).
TAG_CHAR : constant Character := '@';
-- Specific tags recognized when analyzing the documentation.
TAG_AUTHOR : constant String := "author";
TAG_TITLE : constant String := "title";
TAG_INCLUDE : constant String := "include";
TAG_INCLUDE_CONFIG : constant String := "include-config";
TAG_INCLUDE_BEAN : constant String := "include-bean";
TAG_INCLUDE_QUERY : constant String := "include-query";
TAG_INCLUDE_PERM : constant String := "include-permission";
TAG_SEE : constant String := "see";
type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE);
-- ------------------------------
-- Documentation artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Set the output document format to generate.
procedure Set_Format (Handler : in out Artifact;
Format : in Doc_Format;
Footer : in Boolean);
-- Load from the file a list of link definitions which can be injected in the generated doc.
-- This allows to avoid polluting the Ada code with external links.
procedure Read_Links (Handler : in out Artifact;
Path : in String);
private
type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_INCLUDE_CONFIG,
L_INCLUDE_BEAN, L_INCLUDE_PERMISSION, L_INCLUDE_QUERY,
L_START_CODE, L_END_CODE,
L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4);
subtype Line_Include_Kind is Line_Kind range L_INCLUDE .. L_INCLUDE_QUERY;
type Line_Type (Len : Natural) is record
Kind : Line_Kind := L_TEXT;
Content : String (1 .. Len);
end record;
package Line_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Line_Type);
type Line_Group_Vector is array (Line_Include_Kind) of Line_Vectors.Vector;
type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST);
type Document_Formatter is abstract tagged record
Links : Util.Strings.Maps.Map;
end record;
type Document_Formatter_Access is access all Document_Formatter'Class;
type File_Document is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
State : Doc_State := IN_PARA;
Line_Number : Natural := 0;
Lines : Line_Group_Vector;
Was_Included : Boolean := False;
Print_Footer : Boolean := True;
Formatter : Document_Formatter_Access;
end record;
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is abstract;
-- Start a new document.
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is abstract;
-- Write a line in the target document formatting the line if necessary.
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is abstract;
-- Finish the document.
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is abstract;
package Doc_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => File_Document,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Include the document extract represented by <b>Name</b> into the document <b>Into</b>.
-- The included document is marked so that it will not be generated.
procedure Include (Docs : in out Doc_Maps.Map;
Into : in out File_Document;
Name : in String;
Mode : in Line_Include_Kind;
Position : in Natural);
-- Generate the project documentation that was collected in <b>Docs</b>.
-- The documentation is merged so that the @include tags are replaced by the matching
-- document extracts.
procedure Generate (Docs : in out Doc_Maps.Map;
Dir : in String);
-- Returns True if the line indicates a bullet or numbered list.
function Is_List (Line : in String) return Boolean;
-- Returns True if the line indicates a code sample.
function Is_Code (Line : in String) return Boolean;
-- Append a raw text line to the document.
procedure Append_Line (Doc : in out File_Document;
Line : in String);
-- Look and analyze the tag defined on the line.
procedure Append_Tag (Doc : in out File_Document;
Tag : in String);
-- Analyse the documentation line and collect the documentation text.
procedure Append (Doc : in out File_Document;
Line : in String);
-- After having collected the documentation, terminate the document by making sure
-- the opened elements are closed.
procedure Finish (Doc : in out File_Document);
-- Set the name associated with the document extract.
procedure Set_Name (Doc : in out File_Document;
Name : in String);
-- Set the title associated with the document extract.
procedure Set_Title (Doc : in out File_Document;
Title : in String);
-- Scan the files in the directory refered to by <b>Path</b> and collect the documentation
-- in the <b>Docs</b> hashed map.
procedure Scan_Files (Handler : in out Artifact;
Path : in String;
Docs : in out Doc_Maps.Map);
-- Read the Ada specification file and collect the useful documentation.
-- To keep the implementation simple, we don't use the ASIS packages to scan and extract
-- the documentation. We don't need to look at the Ada specification itself. Instead,
-- we assume that the Ada source follows some Ada style guidelines.
procedure Read_Ada_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
procedure Read_Xml_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
type Artifact is new Gen.Artifacts.Artifact with record
Xslt_Command : Ada.Strings.Unbounded.Unbounded_String;
Format : Doc_Format := DOC_WIKI_GOOGLE;
Print_Footer : Boolean := True;
Formatter : Document_Formatter_Access;
end record;
end Gen.Artifacts.Docs;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs -- Artifact for documentation
-- Copyright (C) 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 Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Gen.Model.Packages;
private with Util.Strings.Maps;
-- with Asis;
-- with Asis.Text;
-- with Asis.Elements;
-- with Asis.Exceptions;
-- with Asis.Errors;
-- with Asis.Implementation;
-- with Asis.Elements;
-- with Asis.Declarations;
-- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of
-- application documentation. Its purpose is to scan the project source files
-- and extract some interesting information for a developer's guide. The artifact
-- scans the Ada source files, the XML configuration files, the XHTML files.
--
-- The generated documentation is intended to be published on a web site.
-- The Google Wiki style is generated by default.
--
-- 1/ In the first step, the project files are scanned and the useful
-- documentation is extracted.
--
-- 2/ In the second step, the documentation is merged and reconciled. Links to
-- documentation pages and references are setup and the final pages are generated.
--
-- Ada
-- ---
-- The documentation starts at the first '== TITLE ==' marker and finishes before the
-- package specification.
--
-- XHTML
-- -----
-- Same as Ada.
--
-- XML Files
-- ----------
-- The documentation is part of the XML and the <b>documentation</b> or <b>description</b>
-- tags are extracted.
package Gen.Artifacts.Docs is
-- Tag marker (same as Java).
TAG_CHAR : constant Character := '@';
-- Specific tags recognized when analyzing the documentation.
TAG_AUTHOR : constant String := "author";
TAG_TITLE : constant String := "title";
TAG_INCLUDE : constant String := "include";
TAG_INCLUDE_CONFIG : constant String := "include-config";
TAG_INCLUDE_BEAN : constant String := "include-bean";
TAG_INCLUDE_QUERY : constant String := "include-query";
TAG_INCLUDE_PERM : constant String := "include-permission";
TAG_SEE : constant String := "see";
Unknown_Tag : exception;
type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE);
-- ------------------------------
-- Documentation artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Set the output document format to generate.
procedure Set_Format (Handler : in out Artifact;
Format : in Doc_Format;
Footer : in Boolean);
-- Load from the file a list of link definitions which can be injected in the generated doc.
-- This allows to avoid polluting the Ada code with external links.
procedure Read_Links (Handler : in out Artifact;
Path : in String);
private
type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_INCLUDE_CONFIG,
L_INCLUDE_BEAN, L_INCLUDE_PERMISSION, L_INCLUDE_QUERY,
L_START_CODE, L_END_CODE,
L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4);
subtype Line_Include_Kind is Line_Kind range L_INCLUDE .. L_INCLUDE_QUERY;
type Line_Type (Len : Natural) is record
Kind : Line_Kind := L_TEXT;
Content : String (1 .. Len);
end record;
package Line_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Line_Type);
type Line_Group_Vector is array (Line_Include_Kind) of Line_Vectors.Vector;
type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST);
type Document_Formatter is abstract tagged record
Links : Util.Strings.Maps.Map;
end record;
type Document_Formatter_Access is access all Document_Formatter'Class;
type File_Document is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
State : Doc_State := IN_PARA;
Line_Number : Natural := 0;
Lines : Line_Group_Vector;
Was_Included : Boolean := False;
Print_Footer : Boolean := True;
Formatter : Document_Formatter_Access;
end record;
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is abstract;
-- Start a new document.
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is abstract;
-- Write a line in the target document formatting the line if necessary.
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is abstract;
-- Finish the document.
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is abstract;
package Doc_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => File_Document,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Include the document extract represented by <b>Name</b> into the document <b>Into</b>.
-- The included document is marked so that it will not be generated.
procedure Include (Docs : in out Doc_Maps.Map;
Into : in out File_Document;
Name : in String;
Mode : in Line_Include_Kind;
Position : in Natural);
-- Generate the project documentation that was collected in <b>Docs</b>.
-- The documentation is merged so that the @include tags are replaced by the matching
-- document extracts.
procedure Generate (Docs : in out Doc_Maps.Map;
Dir : in String);
-- Returns True if the line indicates a bullet or numbered list.
function Is_List (Line : in String) return Boolean;
-- Returns True if the line indicates a code sample.
function Is_Code (Line : in String) return Boolean;
-- Append a raw text line to the document.
procedure Append_Line (Doc : in out File_Document;
Line : in String);
-- Look and analyze the tag defined on the line.
procedure Append_Tag (Doc : in out File_Document;
Tag : in String);
-- Analyse the documentation line and collect the documentation text.
procedure Append (Doc : in out File_Document;
Line : in String);
-- After having collected the documentation, terminate the document by making sure
-- the opened elements are closed.
procedure Finish (Doc : in out File_Document);
-- Set the name associated with the document extract.
procedure Set_Name (Doc : in out File_Document;
Name : in String);
-- Set the title associated with the document extract.
procedure Set_Title (Doc : in out File_Document;
Title : in String);
-- Scan the files in the directory refered to by <b>Path</b> and collect the documentation
-- in the <b>Docs</b> hashed map.
procedure Scan_Files (Handler : in out Artifact;
Path : in String;
Docs : in out Doc_Maps.Map);
-- Read the Ada specification file and collect the useful documentation.
-- To keep the implementation simple, we don't use the ASIS packages to scan and extract
-- the documentation. We don't need to look at the Ada specification itself. Instead,
-- we assume that the Ada source follows some Ada style guidelines.
procedure Read_Ada_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
procedure Read_Xml_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
type Artifact is new Gen.Artifacts.Artifact with record
Xslt_Command : Ada.Strings.Unbounded.Unbounded_String;
Format : Doc_Format := DOC_WIKI_GOOGLE;
Print_Footer : Boolean := True;
Formatter : Document_Formatter_Access;
end record;
end Gen.Artifacts.Docs;
|
Declare the Unkown_Tag exception to report when a @tag is not recognized
|
Declare the Unkown_Tag exception to report when a @tag is not recognized
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
394d44a78f9a4e56dddf460b55cd115a5df5de69
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
-- === Wiki Parsers ===
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt>
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- <tt>Set_Syntax</tt> procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki <tt>Document</tt> 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 <tt>Parse</tt> procedure is then used to parse either a string content or some stream
-- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure
-- completes, the <tt>Document</tt> instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
-- 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.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Parser_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 : Wiki.Plugins.Plugin_Context;
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Syntax : Wiki_Syntax;
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;
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;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wiki.Strings.WChar);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Boolean;
-- 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;
-- Extract a list of parameters separated by the given separator (ex: '|').
procedure Parse_Parameters (P : in out Parser;
Separator : in Wiki.Strings.WChar;
Terminator : in Wiki.Strings.WChar;
Names : in String_Array);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Parse_Token (P : in out Parser);
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
-- === Wiki Parsers ===
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt>
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- <tt>Set_Syntax</tt> procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki <tt>Document</tt> 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 <tt>Parse</tt> procedure is then used to parse either a string content or some stream
-- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure
-- completes, the <tt>Document</tt> instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
-- 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.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type 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 : Wiki.Plugins.Plugin_Context;
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Syntax : Wiki_Syntax;
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;
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;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wiki.Strings.WChar);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Boolean;
-- 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;
-- Extract a list of parameters separated by the given separator (ex: '|').
procedure Parse_Parameters (P : in out Parser;
Separator : in Wiki.Strings.WChar;
Terminator : in Wiki.Strings.WChar;
Names : in String_Array);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Parse_Token (P : in out Parser);
end Wiki.Parsers;
|
Declare the Parse procedure with a Wiki.Strings.UString
|
Declare the Parse procedure with a Wiki.Strings.UString
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
b4046938cf1f572a76e11f9c404bc951fb28e918
|
src/util-properties.ads
|
src/util-properties.ads
|
-----------------------------------------------------------------------
-- util-properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
-- = Property Files =
-- The `Util.Properties` package and children implements support to read, write and use
-- property files either in the Java property file format or the Windows INI configuration file.
-- Each property is assigned a key and a value. The list of properties are stored in the
-- `Util.Properties.Manager` tagged record and they are indexed by the key name. A property
-- is therefore unique in the list. Properties can be grouped together in sub-properties so
-- that a key can represent another list of properties.
--
-- == File formats ==
-- The property file consists of a simple name and value pair separated by the `=` sign.
-- Thanks to the Windows INI file format, list of properties can be grouped together
-- in sections by using the `[section-name]` notation.
--
-- test.count=20
-- test.repeat=5
-- [FileTest]
-- test.count=5
-- test.repeat=2
--
-- == Using property files ==
-- An instance of the `Util.Properties.Manager` tagged record must be declared and it provides
-- various operations that can be used. When created, the property manager is empty. One way
-- to fill it is by using the `Load_Properties` procedure to read the property file. Another
-- way is by using the `Set` procedure to insert or change a property by giving its name
-- and its value.
--
-- In this example, the property file `test.properties` is loaded and assuming that it contains
-- the above configuration example, the `Get ("test.count")` will return the string `"20"`.
-- The property `test.repeat` is then modified to have the value `"23"` and the properties are
-- then saved in the file.
--
-- with Util.Properties;
-- ...
-- Props : Util.Properties.Manager;
-- ...
-- Props.Load_Properties (Path => "test.properties");
-- Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count");
-- Props.Set ("test.repeat", "23");
-- Props.Save_Properties (Path => "test.properties");
--
-- To be able to access a section from the property manager, it is necessary to retrieve it
-- by using the `Get` function and giving the section name. For example, to retrieve the
-- `test.count` property of the `FileTest` section, the following code is used:
--
-- FileTest : Util.Properties.Manager := Props.Get ("FileTest");
-- ...
-- Ada.Text_IO.Put_Line ("[FileTest] Count: "
-- & FileTest.Get ("test.count");
--
-- When getting or removing a property, the `NO_PROPERTY` exception is raised if the property
-- name was not found in the map. To avoid that exception, it is possible to check whether
-- the name is known by using the `Exists` function.
--
-- if Props.Exists ("test.old_count") then
-- ... -- Property exist
-- end if;
--
-- @include util-properties-json.ads
-- @include util-properties-bundles.ads
--
-- == Advance usage of properties ==
-- The property manager holds the name and value pairs by using an Ada Bean object.
--
-- It is possible to iterate over the properties by using the `Iterate` procedure that
-- accepts as parameter a `Process` procedure that gets the property name as well as the
-- property value. The value itself is passed as an `Util.Beans.Objects.Object` type.
--
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
function Get (Self : in Manager'Class;
Name : in String) return Manager;
-- Create a property manager and associated it with the given name.
function Create (Self : in out Manager'Class;
Name : in String) return Manager;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
-- Get the property manager represented by the item value.
-- Raise the Conversion_Error exception if the value is not a property manager.
function To_Manager (Item : in Value) return Manager;
-- Returns True if the item value represents a property manager.
function Is_Manager (Item : in Value) return Boolean;
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
Shared : Boolean := False;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-----------------------------------------------------------------------
-- util-properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
-- = Property Files =
-- The `Util.Properties` package and children implements support to read, write and use
-- property files either in the Java property file format or the Windows INI configuration file.
-- Each property is assigned a key and a value. The list of properties are stored in the
-- `Util.Properties.Manager` tagged record and they are indexed by the key name. A property
-- is therefore unique in the list. Properties can be grouped together in sub-properties so
-- that a key can represent another list of properties.
--
-- == File formats ==
-- The property file consists of a simple name and value pair separated by the `=` sign.
-- Thanks to the Windows INI file format, list of properties can be grouped together
-- in sections by using the `[section-name]` notation.
--
-- test.count=20
-- test.repeat=5
-- [FileTest]
-- test.count=5
-- test.repeat=2
--
-- == Using property files ==
-- An instance of the `Util.Properties.Manager` tagged record must be declared and it provides
-- various operations that can be used. When created, the property manager is empty. One way
-- to fill it is by using the `Load_Properties` procedure to read the property file. Another
-- way is by using the `Set` procedure to insert or change a property by giving its name
-- and its value.
--
-- In this example, the property file `test.properties` is loaded and assuming that it contains
-- the above configuration example, the `Get ("test.count")` will return the string `"20"`.
-- The property `test.repeat` is then modified to have the value `"23"` and the properties are
-- then saved in the file.
--
-- with Util.Properties;
-- ...
-- Props : Util.Properties.Manager;
-- ...
-- Props.Load_Properties (Path => "test.properties");
-- Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count");
-- Props.Set ("test.repeat", "23");
-- Props.Save_Properties (Path => "test.properties");
--
-- To be able to access a section from the property manager, it is necessary to retrieve it
-- by using the `Get` function and giving the section name. For example, to retrieve the
-- `test.count` property of the `FileTest` section, the following code is used:
--
-- FileTest : Util.Properties.Manager := Props.Get ("FileTest");
-- ...
-- Ada.Text_IO.Put_Line ("[FileTest] Count: "
-- & FileTest.Get ("test.count");
--
-- When getting or removing a property, the `NO_PROPERTY` exception is raised if the property
-- name was not found in the map. To avoid that exception, it is possible to check whether
-- the name is known by using the `Exists` function.
--
-- if Props.Exists ("test.old_count") then
-- ... -- Property exist
-- end if;
--
-- @include util-properties-json.ads
-- @include util-properties-bundles.ads
--
-- == Advance usage of properties ==
-- The property manager holds the name and value pairs by using an Ada Bean object.
--
-- It is possible to iterate over the properties by using the `Iterate` procedure that
-- accepts as parameter a `Process` procedure that gets the property name as well as the
-- property value. The value itself is passed as an `Util.Beans.Objects.Object` type.
--
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property manager is empty.
function Is_Empty (Self : in Manager'Class) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
function Get (Self : in Manager'Class;
Name : in String) return Manager;
-- Create a property manager and associated it with the given name.
function Create (Self : in out Manager'Class;
Name : in String) return Manager;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
-- Get the property manager represented by the item value.
-- Raise the Conversion_Error exception if the value is not a property manager.
function To_Manager (Item : in Value) return Manager;
-- Returns True if the item value represents a property manager.
function Is_Manager (Item : in Value) return Boolean;
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
Shared : Boolean := False;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
Declare the Is_Empty function to check if the property manager is empty
|
Declare the Is_Empty function to check if the property manager is empty
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a22b8f66fb8404bbae27499d2e7c23ba6f08f646
|
src/wiki-parsers-html.adb
|
src/wiki-parsers-html.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Wiki.Parsers.Html.Entities;
package body Wiki.Parsers.Html is
-- Parse a HTML/XML comment to strip it.
procedure Parse_Comment (P : in out Parser);
-- Parse a simple DOCTYPE declaration and ignore it.
procedure Parse_Doctype (P : in out Parser);
procedure Collect_Attributes (P : in out Parser);
function Is_Space (C : in Wide_Wide_Character) return Boolean;
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return C = ' ' or C = LF or C = CR;
end Is_Space;
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
procedure Skip_Spaces (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if not Is_Space (C) then
Put_Back (P, C);
return;
end if;
end loop;
end Skip_Spaces;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
Token : Wide_Wide_Character;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML/XML comment to strip it.
-- ------------------------------
procedure Parse_Comment (P : in out Parser) is
C : Wide_Wide_Character;
begin
Peek (P, C);
while not P.Is_Eof loop
Peek (P, C);
if C = '-' then
declare
Count : Natural := 1;
begin
Peek (P, C);
while not P.Is_Eof and C = '-' loop
Peek (P, C);
Count := Count + 1;
end loop;
exit when C = '>' and Count >= 2;
end;
end if;
end loop;
end Parse_Comment;
-- ------------------------------
-- Parse a simple DOCTYPE declaration and ignore it.
-- ------------------------------
procedure Parse_Doctype (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = '>';
end loop;
end Parse_Doctype;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
begin
Peek (P, C);
if C = '!' then
Peek (P, C);
if C = '-' then
Parse_Comment (P);
else
Parse_Doctype (P);
end if;
return;
end if;
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Name);
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Name, P.Attributes);
End_Element (P, Name);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Name, P.Attributes);
end if;
end Parse_Element;
-- ------------------------------
-- Parse an HTML entity such as and replace it with the corresponding code.
-- ------------------------------
procedure Parse_Entity (P : in out Parser;
Token : in Wide_Wide_Character) is
Name : String (1 .. 10);
Len : Natural := 0;
High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last;
Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First;
Pos : Natural;
C : Wide_Wide_Character;
begin
loop
Peek (P, C);
exit when C = ';';
if Len < Name'Last then
Len := Len + 1;
end if;
Name (Len) := Ada.Characters.Conversions.To_Character (C);
end loop;
while Low <= High loop
Pos := (Low + High) / 2;
if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then
Parse_Text (P, Entities.Mapping (Pos));
return;
elsif Entities.Keywords (Pos).all < Name (1 .. Len) then
Low := Pos + 1;
else
High := Pos - 1;
end if;
end loop;
end Parse_Entity;
end Wiki.Parsers.Html;
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Wiki.Parsers.Html.Entities;
package body Wiki.Parsers.Html is
-- Parse a HTML/XML comment to strip it.
procedure Parse_Comment (P : in out Parser);
-- Parse a simple DOCTYPE declaration and ignore it.
procedure Parse_Doctype (P : in out Parser);
procedure Collect_Attributes (P : in out Parser);
function Is_Space (C : in Wide_Wide_Character) return Boolean;
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return C = ' ' or C = LF or C = CR;
end Is_Space;
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
procedure Skip_Spaces (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if not Is_Space (C) then
Put_Back (P, C);
return;
end if;
end loop;
end Skip_Spaces;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
Token : Wide_Wide_Character;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML/XML comment to strip it.
-- ------------------------------
procedure Parse_Comment (P : in out Parser) is
C : Wide_Wide_Character;
begin
Peek (P, C);
while not P.Is_Eof loop
Peek (P, C);
if C = '-' then
declare
Count : Natural := 1;
begin
Peek (P, C);
while not P.Is_Eof and C = '-' loop
Peek (P, C);
Count := Count + 1;
end loop;
exit when C = '>' and Count >= 2;
end;
end if;
end loop;
end Parse_Comment;
-- ------------------------------
-- Parse a simple DOCTYPE declaration and ignore it.
-- ------------------------------
procedure Parse_Doctype (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = '>';
end loop;
end Parse_Doctype;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
begin
Peek (P, C);
if C = '!' then
Peek (P, C);
if C = '-' then
Parse_Comment (P);
else
Parse_Doctype (P);
end if;
return;
end if;
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Name);
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Name, P.Attributes);
End_Element (P, Name);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Name, P.Attributes);
end if;
end Parse_Element;
-- ------------------------------
-- Parse an HTML entity such as and replace it with the corresponding code.
-- ------------------------------
procedure Parse_Entity (P : in out Parser;
Token : in Wide_Wide_Character) is
Name : String (1 .. 10);
Len : Natural := 0;
High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last;
Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First;
Pos : Natural;
C : Wide_Wide_Character;
begin
while Len < Name'Last loop
Peek (P, C);
exit when C = ';' or else P.Is_Eof;
Len := Len + 1;
Name (Len) := Ada.Characters.Conversions.To_Character (C);
end loop;
while Low <= High loop
Pos := (Low + High) / 2;
if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then
Parse_Text (P, Entities.Mapping (Pos));
return;
elsif Entities.Keywords (Pos).all < Name (1 .. Len) then
Low := Pos + 1;
else
High := Pos - 1;
end if;
end loop;
-- The HTML entity is not recognized: we must treat it as plain wiki text.
Parse_Text (P, '&');
for I in 1 .. Len loop
Parse_Text (P, Ada.Characters.Conversions.To_Wide_Wide_Character (Name (I)));
end loop;
end Parse_Entity;
end Wiki.Parsers.Html;
|
Fix infinite loop when parsing invalid HTML entities. Treat these invalid entities as plain wiki text so that & character can be printed easily in Mediawiki wiki content
|
Fix infinite loop when parsing invalid HTML entities. Treat these
invalid entities as plain wiki text so that & character can be printed
easily in Mediawiki wiki content
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
9793e460ad011c6be528aab6833b4b7de9c49df3
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Module : AWA.Questions.Modules.Question_Module_Access := null;
Count : Natural := 0;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Module : AWA.Questions.Modules.Question_Module_Access := null;
Count : Natural := 0;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the question.
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Questions.Beans;
|
Document the bean operations
|
Document the bean operations
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
095e8ecd08eda89426b16391b61bd84d5b41d195
|
awa/plugins/awa-settings/src/awa-settings-modules.adb
|
awa/plugins/awa-settings/src/awa-settings-modules.adb
|
-----------------------------------------------------------------------
-- awa-awa-settings-modules -- Module awa-settings
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with AWA.Services.Contexts;
with AWA.Modules.Get;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
package body AWA.Settings.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Awa-settings.Module");
package ASC renames AWA.Services.Contexts;
-- Set the user setting with the given name in the setting manager cache
-- and in the database.
procedure Set (Manager : in out Setting_Manager;
Name : in String;
Value : in String) is
begin
Manager.Data.Set (Name, Value);
end Set;
-- Get the user setting with the given name from the setting manager cache.
-- Load the user setting from the database if necessary.
procedure Get (Manager : in out Setting_Manager;
Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Manager.Data.Get (Name, Default, Value);
end Get;
function Current return Setting_Manager_Access is
Ctx : ASC.Service_Context_Access := ASC.Current;
Obj : Util.Beans.Objects.Object := Ctx.Get_Session_Attribute ("AWA.Settings");
Bean : access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Obj);
begin
if Bean = null or else not (Bean.all in Setting_Manager'Class) then
declare
Mgr : Setting_Manager_Access := new Setting_Manager;
begin
Obj := Util.Beans.Objects.To_Object (Mgr.all'Access);
Ctx.Set_Session_Attribute ("AWA.Settings", Obj);
return Mgr;
end;
else
return Setting_Manager'Class (Bean.all)'Access;
end if;
end Current;
-- ------------------------------
-- Initialize the awa-settings module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Setting_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the awa-settings module");
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the awa-settings module.
-- ------------------------------
function Get_Setting_Module return Setting_Module_Access is
function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME);
begin
return Get;
end Get_Setting_Module;
procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data,
Name => Setting_Data_Access);
use Ada.Strings.Unbounded;
protected body Settings is
procedure Get (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
Value := Item.Value;
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
First := Item;
end if;
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
Value := Ada.Strings.Unbounded.To_Unbounded_String (Default);
end Get;
procedure Set (Name : in String;
Value : in String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
First := Item;
end if;
if Item.Value = Value then
return;
end if;
Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value);
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
end Set;
procedure Clear is
begin
while First /= null loop
declare
Item : Setting_Data_Access := First;
begin
First := Item.Next_Setting;
Free (Item);
end;
end loop;
end Clear;
end Settings;
end AWA.Settings.Modules;
|
-----------------------------------------------------------------------
-- awa-awa-settings-modules -- Module awa-settings
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with AWA.Services.Contexts;
with AWA.Modules.Get;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
package body AWA.Settings.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Awa-settings.Module");
package ASC renames AWA.Services.Contexts;
-- Set the user setting with the given name in the setting manager cache
-- and in the database.
procedure Set (Manager : in out Setting_Manager;
Name : in String;
Value : in String) is
begin
Manager.Data.Set (Name, Value);
end Set;
-- Get the user setting with the given name from the setting manager cache.
-- Load the user setting from the database if necessary.
procedure Get (Manager : in out Setting_Manager;
Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Manager.Data.Get (Name, Default, Value);
end Get;
function Current return Setting_Manager_Access is
Ctx : ASC.Service_Context_Access := ASC.Current;
Obj : Util.Beans.Objects.Object := Ctx.Get_Session_Attribute ("AWA.Settings");
Bean : access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Obj);
begin
if Bean = null or else not (Bean.all in Setting_Manager'Class) then
declare
Mgr : Setting_Manager_Access := new Setting_Manager;
begin
Obj := Util.Beans.Objects.To_Object (Mgr.all'Access);
Ctx.Set_Session_Attribute ("AWA.Settings", Obj);
return Mgr;
end;
else
return Setting_Manager'Class (Bean.all)'Access;
end if;
end Current;
-- ------------------------------
-- Initialize the awa-settings module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Setting_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the awa-settings module");
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the awa-settings module.
-- ------------------------------
function Get_Setting_Module return Setting_Module_Access is
function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME);
begin
return Get;
end Get_Setting_Module;
procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data,
Name => Setting_Data_Access);
use Ada.Strings.Unbounded;
protected body Settings is
procedure Get (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
Value := Item.Value;
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
First := Item;
end if;
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
Value := Ada.Strings.Unbounded.To_Unbounded_String (Default);
end Get;
procedure Set (Name : in String;
Value : in String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
First := Item;
end if;
if Item.Value = Value then
return;
end if;
Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value);
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
Item := new Setting_Data;
Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value);
Item.Next_Setting := First;
First := Item;
end Set;
procedure Clear is
begin
while First /= null loop
declare
Item : Setting_Data_Access := First;
begin
First := Item.Next_Setting;
Free (Item);
end;
end loop;
end Clear;
end Settings;
end AWA.Settings.Modules;
|
Create the user setting if it does not exist
|
Create the user setting if it does not exist
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
cd25974f4ffb7efdd37a79b0815b67bd04e27dd4
|
src/asf-components-ajax-factory.adb
|
src/asf-components-ajax-factory.adb
|
-----------------------------------------------------------------------
-- components-ajax-factory -- Factory for AJAX Components
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Base;
with ASF.Views.Nodes;
with ASF.Components.Ajax.Includes;
package body ASF.Components.Ajax.Factory is
function Create_Include return Base.UIComponent_Access;
-- ------------------------------
-- Create an UIInclude component
-- ------------------------------
function Create_Include return Base.UIComponent_Access is
begin
return new ASF.Components.Ajax.Includes.UIInclude;
end Create_Include;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/ajax";
INCLUDE_TAG : aliased constant String := "include";
Ajax_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => INCLUDE_TAG'Access,
Component => Create_Include'Access,
Tag => Create_Component_Node'Access)
);
Ajax_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Ajax_Bindings'Access);
-- ------------------------------
-- Get the Ajax component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Ajax_Factory'Access;
end Definition;
end ASF.Components.Ajax.Factory;
|
-----------------------------------------------------------------------
-- components-ajax-factory -- Factory for AJAX Components
-- Copyright (C) 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 ASF.Components.Base;
with ASF.Views.Nodes;
with ASF.Components.Ajax.Includes;
package body ASF.Components.Ajax.Factory is
function Create_Include return Base.UIComponent_Access;
-- ------------------------------
-- Create an UIInclude component
-- ------------------------------
function Create_Include return Base.UIComponent_Access is
begin
return new ASF.Components.Ajax.Includes.UIInclude;
end Create_Include;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/ajax";
INCLUDE_TAG : aliased constant String := "include";
-- ------------------------------
-- Register the Ajax component factory.
-- ------------------------------
procedure Register (Factory : in out ASF.Factory.Component_Factory) is
begin
null;
ASF.Factory.Register (Factory,
URI => URI'Access,
Name => INCLUDE_TAG'Access,
Tag => Create_Component_Node'Access,
Create => Create_Include'Access);
end Register;
end ASF.Components.Ajax.Factory;
|
Change the Definition function into a Register procedure
|
Change the Definition function into a Register procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
bbdf99816d7c00464d983d0386d47638cdcd53fa
|
mat/src/events/mat-events-targets.adb
|
mat/src/events/mat-events-targets.adb
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id + 1, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos = Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
end loop;
end Iterate;
end Event_Collector;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
begin
Target.Events.Iterate (Start, Finish, Process);
end Iterate;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id + 1, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos = Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
end loop;
end Iterate;
end Event_Collector;
end MAT.Events.Targets;
|
Implement the Iterate procedure
|
Implement the Iterate procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
b44b0569e014f34b83c0011929eb5661f08cc881
|
awa/plugins/awa-tags/src/awa-tags-beans.adb
|
awa/plugins/awa-tags/src/awa-tags-beans.adb
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
package body AWA.Tags.Beans is
-- ------------------------------
-- Compare two tags on their count and name.
-- ------------------------------
function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
if Left.Count = Right.Count then
return Left.Tag < Right.Tag;
else
return Left.Count < Right.Count;
end if;
end "<";
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a tag on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the tags associated with the given database identifier.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Set the list of tags to add.
-- ------------------------------
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Added := Tags;
end Set_Added;
-- ------------------------------
-- Set the list of tags to remove.
-- ------------------------------
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Deleted := Tags;
end Set_Deleted;
-- ------------------------------
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
-- ------------------------------
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier) is
use type AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type);
Service : AWA.Tags.Modules.Tag_Module_Access := From.Module;
begin
if Service = null then
Service := AWA.Tags.Modules.Get_Tag_Module;
end if;
Service.Update_Tags (Id => For_Entity_Id,
Entity_Type => Entity_Type,
Permission => Ada.Strings.Unbounded.To_String (From.Permission),
Added => From.Added,
Deleted => From.Deleted);
end Update_Tags;
-- ------------------------------
-- Create the tag list bean instance.
-- ------------------------------
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_List_Bean_Access := new Tag_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Search the tags that match the search string.
-- ------------------------------
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_Search);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("search", Search & "%");
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Search_Tags;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "search" then
declare
Session : constant ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Search_Tags (Session, Util.Beans.Objects.To_String (Value));
end;
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Create the tag search bean instance.
-- ------------------------------
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Search_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
declare
Session : ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Load_Tags (Session);
end;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of tags.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All);
Query.Bind_Param ("entity_type", Kind);
AWA.Tags.Models.List (Into, Session, Query);
end Load_Tags;
-- ------------------------------
-- Create the tag info list bean instance.
-- ------------------------------
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Info_List_Bean;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Entity_Tag_Maps.Element (Pos);
else
return null;
end if;
end Get_Tags;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Util.Beans.Objects.To_Object (Value => Entity_Tag_Maps.Element (Pos).all'Access,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Tags;
-- ------------------------------
-- Load the list of tags associated with a list of entities.
-- ------------------------------
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector) is
Query : ADO.Queries.Context;
Kind : ADO.Entity_Type;
begin
Into.Clear;
if List.Is_Empty then
return;
end if;
Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type);
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_For_Entities);
Query.Bind_Param ("entity_id_list", List);
Query.Bind_Param ("entity_type", Kind);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Id : ADO.Identifier;
List : Util.Beans.Lists.Strings.List_Bean_Access;
Pos : Entity_Tag_Maps.Cursor;
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Id := Stmt.Get_Identifier (0);
Pos := Into.Tags.Find (Id);
if not Entity_Tag_Maps.Has_Element (Pos) then
List := new Util.Beans.Lists.Strings.List_Bean;
Into.Tags.Insert (Id, List);
else
List := Entity_Tag_Maps.Element (Pos);
end if;
List.List.Append (Stmt.Get_String (1));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
procedure Clear (List : in out Entity_Tag_Map) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class,
Name => Util.Beans.Lists.Strings.List_Bean_Access);
Pos : Entity_Tag_Maps.Cursor;
Tags : Util.Beans.Lists.Strings.List_Bean_Access;
begin
loop
Pos := List.Tags.First;
exit when not Entity_Tag_Maps.Has_Element (Pos);
Tags := Entity_Tag_Maps.Element (Pos);
List.Tags.Delete (Pos);
Free (Tags);
end loop;
end Clear;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
overriding
procedure Finalize (List : in out Entity_Tag_Map) is
begin
List.Clear;
end Finalize;
end AWA.Tags.Beans;
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
package body AWA.Tags.Beans is
-- ------------------------------
-- Compare two tags on their count and name.
-- ------------------------------
function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
if Left.Count = Right.Count then
return Left.Tag < Right.Tag;
else
return Left.Count > Right.Count;
end if;
end "<";
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a tag on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the tags associated with the given database identifier.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Set the list of tags to add.
-- ------------------------------
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Added := Tags;
end Set_Added;
-- ------------------------------
-- Set the list of tags to remove.
-- ------------------------------
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Deleted := Tags;
end Set_Deleted;
-- ------------------------------
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
-- ------------------------------
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier) is
use type AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type);
Service : AWA.Tags.Modules.Tag_Module_Access := From.Module;
begin
if Service = null then
Service := AWA.Tags.Modules.Get_Tag_Module;
end if;
Service.Update_Tags (Id => For_Entity_Id,
Entity_Type => Entity_Type,
Permission => Ada.Strings.Unbounded.To_String (From.Permission),
Added => From.Added,
Deleted => From.Deleted);
end Update_Tags;
-- ------------------------------
-- Create the tag list bean instance.
-- ------------------------------
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_List_Bean_Access := new Tag_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Search the tags that match the search string.
-- ------------------------------
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_Search);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("search", Search & "%");
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Search_Tags;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "search" then
declare
Session : constant ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Search_Tags (Session, Util.Beans.Objects.To_String (Value));
end;
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Create the tag search bean instance.
-- ------------------------------
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Search_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
declare
Session : ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Load_Tags (Session);
end;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of tags.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All);
Query.Bind_Param ("entity_type", Kind);
AWA.Tags.Models.List (Into, Session, Query);
end Load_Tags;
-- ------------------------------
-- Create the tag info list bean instance.
-- ------------------------------
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Info_List_Bean;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Entity_Tag_Maps.Element (Pos);
else
return null;
end if;
end Get_Tags;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Util.Beans.Objects.To_Object (Value => Entity_Tag_Maps.Element (Pos).all'Access,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Tags;
-- ------------------------------
-- Load the list of tags associated with a list of entities.
-- ------------------------------
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector) is
Query : ADO.Queries.Context;
Kind : ADO.Entity_Type;
begin
Into.Clear;
if List.Is_Empty then
return;
end if;
Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type);
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_For_Entities);
Query.Bind_Param ("entity_id_list", List);
Query.Bind_Param ("entity_type", Kind);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Id : ADO.Identifier;
List : Util.Beans.Lists.Strings.List_Bean_Access;
Pos : Entity_Tag_Maps.Cursor;
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Id := Stmt.Get_Identifier (0);
Pos := Into.Tags.Find (Id);
if not Entity_Tag_Maps.Has_Element (Pos) then
List := new Util.Beans.Lists.Strings.List_Bean;
Into.Tags.Insert (Id, List);
else
List := Entity_Tag_Maps.Element (Pos);
end if;
List.List.Append (Stmt.Get_String (1));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
procedure Clear (List : in out Entity_Tag_Map) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class,
Name => Util.Beans.Lists.Strings.List_Bean_Access);
Pos : Entity_Tag_Maps.Cursor;
Tags : Util.Beans.Lists.Strings.List_Bean_Access;
begin
loop
Pos := List.Tags.First;
exit when not Entity_Tag_Maps.Has_Element (Pos);
Tags := Entity_Tag_Maps.Element (Pos);
List.Tags.Delete (Pos);
Free (Tags);
end loop;
end Clear;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
overriding
procedure Finalize (List : in out Entity_Tag_Map) is
begin
List.Clear;
end Finalize;
end AWA.Tags.Beans;
|
Fix sorting the tags to get the most used tags first
|
Fix sorting the tags to get the most used tags first
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
4e4601190a676ae19cd7afcafae97cdc49743be5
|
awa/plugins/awa-wikis/src/awa-wikis-previews.ads
|
awa/plugins/awa-wikis/src/awa-wikis-previews.ads
|
-----------------------------------------------------------------------
-- awa-wikis-previews -- Wiki preview management
-- 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 AWA.Modules;
with AWA.Jobs.Services;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
-- == Wiki Preview Module ==
-- The <tt>AWA.Wikis.Previews</tt> package implements a preview image generation for a wiki page.
-- This module is optional, it is possible to use the wikis without preview support. When the
-- module is registered, it listens to wiki page lifecycle events. When a new wiki content is
-- changed, it triggers a job to make the preview. The preview job uses the
-- <tt>wkhtmotoimage</tt> external program to make the preview image.
package AWA.Wikis.Previews is
-- The name under which the module is registered.
NAME : constant String := "wiki-previews";
-- The worker procedure that performs the preview job.
procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class);
-- Preview job definition.
package Preview_Job_Definition is new AWA.Jobs.Services.Work_Definition (Preview_Worker'Access);
-- ------------------------------
-- Preview wiki module
-- ------------------------------
type Preview_Module is new AWA.Modules.Module
and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with private;
type Preview_Module_Access is access all Preview_Module'Class;
-- Initialize the preview wiki module.
overriding
procedure Initialize (Plugin : in out Preview_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page.
overriding
procedure On_Create (Instance : in Preview_Module;
Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page.
overriding
procedure On_Update (Instance : in Preview_Module;
Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page.
overriding
procedure On_Delete (Instance : in Preview_Module;
Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
private
type Preview_Module is new AWA.Modules.Module
and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with null record;
end AWA.Wikis.Previews;
|
-----------------------------------------------------------------------
-- awa-wikis-previews -- Wiki preview management
-- 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 AWA.Modules;
with AWA.Jobs.Services;
with AWA.Jobs.Modules;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
-- == Wiki Preview Module ==
-- The <tt>AWA.Wikis.Previews</tt> package implements a preview image generation for a wiki page.
-- This module is optional, it is possible to use the wikis without preview support. When the
-- module is registered, it listens to wiki page lifecycle events. When a new wiki content is
-- changed, it triggers a job to make the preview. The preview job uses the
-- <tt>wkhtmotoimage</tt> external program to make the preview image.
package AWA.Wikis.Previews is
-- The name under which the module is registered.
NAME : constant String := "wiki-previews";
-- The worker procedure that performs the preview job.
procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class);
-- Preview job definition.
package Preview_Job_Definition is new AWA.Jobs.Services.Work_Definition (Preview_Worker'Access);
-- ------------------------------
-- Preview wiki module
-- ------------------------------
type Preview_Module is new AWA.Modules.Module
and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with private;
type Preview_Module_Access is access all Preview_Module'Class;
-- Initialize the preview wiki module.
overriding
procedure Initialize (Plugin : in out Preview_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page.
overriding
procedure On_Create (Instance : in Preview_Module;
Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page.
overriding
procedure On_Update (Instance : in Preview_Module;
Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page.
overriding
procedure On_Delete (Instance : in Preview_Module;
Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Create a preview job and schedule the job to generate a new thumbnail preview for the page.
procedure Make_Preview_Job (Plugin : in Preview_Module;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
private
type Preview_Module is new AWA.Modules.Module
and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with record
Job_Module : AWA.Jobs.Modules.Job_Module_Access;
end record;
end AWA.Wikis.Previews;
|
Declare the Make_Preview_Job procedure
|
Declare the Make_Preview_Job procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
fe73b5be45c60a9b21271a5fe8919d9202cebab5
|
src/sys/encoders/util-encoders-hmac-sha1.ads
|
src/sys/encoders/util-encoders-hmac-sha1.ads
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code
-- Copyright (C) 2011, 2012, 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.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Util.Encoders.SHA1;
-- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package Util.Encoders.HMAC.SHA1 is
pragma Preelaborate;
-- Sign the data string with the key and return the HMAC-SHA1 code in binary.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Hash_Array;
-- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Digest;
-- Sign the data array with the key and return the HMAC-SHA256 code in the result.
procedure Sign (Key : in Ada.Streams.Stream_Element_Array;
Data : in Ada.Streams.Stream_Element_Array;
Result : out Util.Encoders.SHA1.Hash_Array);
-- Sign the data string with the key and return the HMAC-SHA1 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest;
-- ------------------------------
-- HMAC-SHA1 Context
-- ------------------------------
type Context is limited private;
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in String);
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Hash_Array);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Digest);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA1.Base64_Digest;
URL : in Boolean := False);
private
type Encoder is new Util.Encoders.Transformer with null record;
type Context is new Ada.Finalization.Limited_Controlled with record
SHA : Util.Encoders.SHA1.Context;
Key : Ada.Streams.Stream_Element_Array (0 .. 63);
Key_Len : Ada.Streams.Stream_Element_Offset;
end record;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context);
end Util.Encoders.HMAC.SHA1;
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code
-- Copyright (C) 2011, 2012, 2017, 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.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Util.Encoders.SHA1;
-- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package Util.Encoders.HMAC.SHA1 is
pragma Preelaborate;
-- Sign the data string with the key and return the HMAC-SHA1 code in binary.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Hash_Array;
-- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Digest;
-- Sign the data array with the key and return the HMAC-SHA256 code in the result.
procedure Sign (Key : in Ada.Streams.Stream_Element_Array;
Data : in Ada.Streams.Stream_Element_Array;
Result : out Util.Encoders.SHA1.Hash_Array);
-- Sign the data string with the key and return the HMAC-SHA1 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest;
-- ------------------------------
-- HMAC-SHA1 Context
-- ------------------------------
type Context is limited private;
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in String);
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Hash_Array);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Digest);
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA1.Base64_Digest;
URL : in Boolean := False);
private
type Context is new Ada.Finalization.Limited_Controlled with record
SHA : Util.Encoders.SHA1.Context;
Key : Ada.Streams.Stream_Element_Array (0 .. 63);
Key_Len : Ada.Streams.Stream_Element_Offset;
end record;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context);
end Util.Encoders.HMAC.SHA1;
|
Remove private type Encoder definition
|
Remove private type Encoder definition
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8669f21b849e5bcc0adc0876026bc4f55f817645
|
awa/awaunit/awa-tests.adb
|
awa/awaunit/awa-tests.adb
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with ASF.Server.Web;
with ASF.Converters.Dates;
with ASF.Tests;
with AWA.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
-- with AWA.Applications;
with AWA.Applications.Factory;
with AWA.Services.Filters;
with AWA.Services.Contexts;
package body AWA.Tests is
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new AWA.Applications.Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
if Add_Modules then
declare
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Tests.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
end AWA.Tests;
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with ASF.Server.Web;
with ASF.Tests;
-- with AWA.Applications;
with AWA.Applications.Factory;
with AWA.Services.Filters;
with AWA.Services.Contexts;
package body AWA.Tests is
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new AWA.Applications.Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
end AWA.Tests;
|
Remove dependencies to AWA modules
|
Remove dependencies to AWA modules
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
dbfd0245f54a741967fc03993450eea3c72a751d
|
awa/awaunit/awa-tests.adb
|
awa/awaunit/awa-tests.adb
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
with AWA.Tests.Helpers.Users;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
-- ------------------------------
-- Cleanup after the test execution.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
pragma Unreferenced (T);
begin
AWA.Tests.Helpers.Users.Tear_Down;
end Tear_Down;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Application.Close;
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
pragma Unreferenced (Add_Modules);
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
Application.Start;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access);
end Initialize_Filters;
end AWA.Tests;
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
with AWA.Tests.Helpers.Users;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
-- ------------------------------
-- Cleanup after the test execution.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
pragma Unreferenced (T);
begin
AWA.Tests.Helpers.Users.Tear_Down;
end Tear_Down;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Application.Close;
Free (Application);
end if;
ASF.Tests.Finish (Status);
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
pragma Unreferenced (Add_Modules);
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
Application.Start;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access);
end Initialize_Filters;
end AWA.Tests;
|
Call ASF.Tests.Finish (Status) to avoid memory leak in the unit test
|
Call ASF.Tests.Finish (Status) to avoid memory leak in the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
c6985bd37f1167d99be6f7eebe3a8fd1d87b5c6c
|
src/asf-views.ads
|
src/asf-views.ads
|
-----------------------------------------------------------------------
-- asf-views -- Views
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Views</b> package defines the abstractions to represent
-- an XHTML view that can be instantiated to create the JSF component
-- tree. The <b>ASF.Views</b> are read only once and they are shared
-- by the JSF component trees that are instantiated from it.
--
-- The XHTML view is read using a SAX parser which creates nodes
-- and attributes to represent the view.
--
-- The <b>ASF.Views</b> is composed of nodes represented by <b>Tag_Node</b>
-- and attributes represented by <b>Tag_Attribute</b>. In a sense, this
-- is very close to an XML DOM tree.
package ASF.Views is
-- ------------------------------
-- Source line information
-- ------------------------------
type File_Info (<>) is limited private;
type File_Info_Access is access all File_Info;
-- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b>
-- and whose relative path portion starts at <b>Relative_Position</b>.
function Create_File_Info (Path : in String;
Relative_Position : in Natural) return File_Info_Access;
-- Get the relative path name
function Relative_Path (File : in File_Info) return String;
type Line_Info is private;
-- Get the line number
function Line (Info : in Line_Info) return Natural;
pragma Inline (Line);
-- Get the source file
function File (Info : in Line_Info) return String;
pragma Inline (File);
private
type File_Info (Length : Natural) is limited record
Path : String (1 .. Length);
Relative_Pos : Natural;
end record;
NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0);
type Line_Info is record
Line : Natural := 0;
Column : Natural := 0;
File : File_Info_Access := NO_FILE'Access;
end record;
end ASF.Views;
|
-----------------------------------------------------------------------
-- asf-views -- Views
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Views</b> package defines the abstractions to represent
-- an XHTML view that can be instantiated to create the JSF component
-- tree. The <b>ASF.Views</b> are read only once and they are shared
-- by the JSF component trees that are instantiated from it.
--
-- The XHTML view is read using a SAX parser which creates nodes
-- and attributes to represent the view.
--
-- The <b>ASF.Views</b> is composed of nodes represented by <b>Tag_Node</b>
-- and attributes represented by <b>Tag_Attribute</b>. In a sense, this
-- is very close to an XML DOM tree.
package ASF.Views is
-- ------------------------------
-- Source line information
-- ------------------------------
type File_Info (<>) is limited private;
type File_Info_Access is access all File_Info;
-- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b>
-- and whose relative path portion starts at <b>Relative_Position</b>.
function Create_File_Info (Path : in String;
Relative_Position : in Natural) return File_Info_Access;
-- Get the relative path name
function Relative_Path (File : in File_Info) return String;
type Line_Info is private;
-- Get the line number
function Line (Info : in Line_Info) return Natural;
pragma Inline (Line);
-- Get the source file
function File (Info : in Line_Info) return String;
pragma Inline (File);
private
type File_Info (Length : Natural) is limited record
Relative_Pos : Natural;
Path : String (1 .. Length);
end record;
NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0);
type Line_Info is record
Line : Natural := 0;
Column : Natural := 0;
File : File_Info_Access := NO_FILE'Access;
end record;
end ASF.Views;
|
Reorder the File_Info record
|
Reorder the File_Info record
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
8ff0d1b0f7e78a9c6df2b9f8e14ab94f7b0ae5a3
|
mat/src/mat-readers.adb
|
mat/src/mat-readers.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Events;
with MAT.Types;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Manager_Base) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
end Initialize;
-- ------------------------------
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Message_Handler;
begin
Handler.For_Servant := Reader;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Manager_Base)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Manager_Base;
Msg : in out Message) is
use type Interfaces.Unsigned_64;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : access MAT.Events.Frame_Info := Client.Frame;
begin
Frame.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_THREAD_ID =>
Frame.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Natural (Count) loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32);
Frame.Time := Frame.Time or Interfaces.Unsigned_64 (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Client.Events.Insert (Event, Client.Frame.all);
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access,
Client.Frame.all, Msg);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
Frame : Message_Handler;
procedure Add_Handler (Key : in String;
Element : in out Message_Handler) is
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Message_Handler) is
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
-- ------------------------------
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
-- ------------------------------
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
begin
Client.Read_Event_Definitions (Msg);
Client.Frame := new MAT.Events.Frame_Info (512);
exception
when E : others =>
Log.Error ("Exception while reading headers ", E);
end Read_Headers;
end MAT.Readers;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
procedure Read_Probe (Client : in out Manager_Base;
Msg : in out Message);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Manager_Base) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
end Initialize;
-- ------------------------------
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Message_Handler;
begin
Handler.For_Servant := Reader;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Manager_Base)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Manager_Base;
Msg : in out Message) is
use type Interfaces.Unsigned_64;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Frame.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_THREAD_ID =>
Frame.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind);
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32);
Frame.Time := Frame.Time or Interfaces.Unsigned_64 (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Client.Events.Insert (Event, Client.Frame.all);
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access,
Client.Frame.all, Msg);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
Frame : Message_Handler;
procedure Add_Handler (Key : in String;
Element : in out Message_Handler);
procedure Add_Handler (Key : in String;
Element : in out Message_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Message_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Message_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
-- ------------------------------
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
-- ------------------------------
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
begin
Client.Read_Event_Definitions (Msg);
Client.Frame := new MAT.Events.Frame_Info (512);
exception
when E : others =>
Log.Error ("Exception while reading headers ", E);
end Read_Headers;
end MAT.Readers;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
18ced939f333722e0420809a723547855caba0b4
|
mat/src/mat-readers.ads
|
mat/src/mat-readers.ads
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Finalization;
with System;
with Util.Streams.Buffered;
with MAT.Types;
with MAT.Events;
with MAT.Events.Targets;
package MAT.Readers is
type Buffer_Type is private;
type Buffer_Ptr is access all Buffer_Type;
type Message_Type is record
Kind : MAT.Events.Event_Type;
Size : Natural;
Buffer : Buffer_Ptr;
end record;
subtype Message is Message_Type;
type Reader_List_Type is limited interface;
type Reader_List_Type_Access is access all Reader_List_Type'Class;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (List : in out Reader_List_Type;
Reader : in out Manager_Base'Class) is abstract;
private
type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN);
type Buffer_Type is record
Current : System.Address;
Start : System.Address;
Last : System.Address;
Buffer : Util.Streams.Buffered.Buffer_Access;
Size : Natural;
Total : Natural;
Endian : Endian_Type := LITTLE_ENDIAN;
end record;
end MAT.Readers;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Finalization;
with System;
with Util.Streams.Buffered;
with MAT.Types;
with MAT.Events;
package MAT.Readers is
type Buffer_Type is private;
type Buffer_Ptr is access all Buffer_Type;
type Message_Type is record
Kind : MAT.Events.Event_Type;
Size : Natural;
Buffer : Buffer_Ptr;
end record;
subtype Message is Message_Type;
private
type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN);
type Buffer_Type is record
Current : System.Address;
Start : System.Address;
Last : System.Address;
Buffer : Util.Streams.Buffered.Buffer_Access;
Size : Natural;
Total : Natural;
Endian : Endian_Type := LITTLE_ENDIAN;
end record;
end MAT.Readers;
|
Remove the Reader_List_Type interface
|
Remove the Reader_List_Type interface
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f9a54f21d32c6b6cca2b18033a7b24c7911dd643
|
mat/src/mat-targets.ads
|
mat/src/mat-targets.ads
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers;
with MAT.Consoles;
package MAT.Targets is
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Memory : MAT.Memory.Targets.Target_Memory;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'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;
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;
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;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers;
with MAT.Consoles;
package MAT.Targets is
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Memory : MAT.Memory.Targets.Target_Memory;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is tagged limited 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;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Process : out Target_Process_Type_Access);
-- 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;
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 tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols;
Console : MAT.Consoles.Console_Access;
end record;
end MAT.Targets;
|
Change Target_Type to a private type and declare the Console function
|
Change Target_Type to a private type and declare the Console function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
474e990ff964b78f04459f0991916fd387673410
|
src/asf-applications-main-configs.adb
|
src/asf-applications-main-configs.adb
|
-----------------------------------------------------------------------
-- applications-main-configs -- Configuration support for ASF Applications
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Navigations;
with ASF.Navigations.Mappers;
with ASF.Servlets.Mappers;
with ASF.Beans.Mappers;
package body ASF.Applications.Main.Configs is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs");
-- ------------------------------
-- Save in the application config object the value associated with the given field.
-- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition
-- in the application.
-- ------------------------------
procedure Set_Member (N : in out Application_Config;
Field : in Application_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when TAG_MESSAGE_VAR =>
N.Name := Value;
when TAG_MESSAGE_BUNDLE =>
declare
Bundle : constant String := Util.Beans.Objects.To_String (Value);
Name : constant String := Util.Beans.Objects.To_String (N.Name);
begin
if Name'Length = 0 then
N.App.Register (Name => Bundle & "Msg",
Bundle => Bundle);
else
N.App.Register (Name => Name,
Bundle => Bundle);
end if;
end;
end case;
end Set_Member;
AMapper : aliased Application_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the managed bean definitions.
-- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings
-- to read the servlet, managed beans and navigation rules.
-- ------------------------------
package body Reader_Config is
-- Get the navigation handler for the Navigation_Config instantiation
-- GNAT crashes if the call is made in the instantation part.
Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler;
package Bean_Config is
new ASF.Beans.Mappers.Reader_Config (Reader, App.Factory'Access,
Context.all'Access);
package Navigation_Config is
new ASF.Navigations.Mappers.Reader_Config (Reader, Nav, Context.all'Access);
package Servlet_Config is
new ASF.Servlets.Mappers.Reader_Config (Reader, App.all'Access,
Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Navigation_Config);
pragma Warnings (Off, Servlet_Config);
Config : aliased Application_Config;
begin
-- Install the property context that gives access
-- to the application configuration properties
Prop_Context.Set_Properties (App.Conf);
Context.Set_Resolver (Prop_Context'Unchecked_Access);
Reader.Add_Mapping ("faces-config", AMapper'Access);
Reader.Add_Mapping ("module", AMapper'Access);
Reader.Add_Mapping ("web-app", AMapper'Access);
Config.App := App;
Application_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
-- ------------------------------
-- Read the configuration file associated with the application. This includes:
-- <ul>
-- <li>The servlet and filter mappings</li>
-- <li>The managed bean definitions</li>
-- <li>The navigation rules</li>
-- </ul>
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String) is
Reader : Util.Serialize.IO.XML.Parser;
Context : aliased EL.Contexts.Default.Default_Context;
-- Setup the <b>Reader</b> to parse and build the configuration for managed beans,
-- navigation rules, servlet rules. Each package instantiation creates a local variable
-- used while parsing the XML file.
package Config is
new Reader_Config (Reader, App'Unchecked_Access, Context'Unchecked_Access);
pragma Warnings (Off, Config);
begin
Log.Info ("Reading module configuration file {0}", File);
-- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end Read_Configuration;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access,
Default => PARAM_VALUE'Access);
-- ------------------------------
-- Returns the configuration parameter.
-- ------------------------------
function P return Config_Param is
begin
return Param;
end P;
end Parameter;
begin
AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR);
AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE);
end ASF.Applications.Main.Configs;
|
-----------------------------------------------------------------------
-- applications-main-configs -- Configuration support for ASF Applications
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Navigations;
with ASF.Navigations.Mappers;
with ASF.Servlets.Mappers;
with ASF.Beans.Mappers;
package body ASF.Applications.Main.Configs is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs");
-- ------------------------------
-- Save in the application config object the value associated with the given field.
-- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition
-- in the application.
-- ------------------------------
procedure Set_Member (N : in out Application_Config;
Field : in Application_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when TAG_MESSAGE_VAR =>
N.Name := Value;
when TAG_MESSAGE_BUNDLE =>
declare
Bundle : constant String := Util.Beans.Objects.To_String (Value);
begin
if Util.Beans.Objects.Is_Null (N.Name) then
N.App.Register (Name => Bundle & "Msg",
Bundle => Bundle);
else
N.App.Register (Name => Util.Beans.Objects.To_String (N.Name),
Bundle => Bundle);
end if;
N.Name := Util.Beans.Objects.Null_Object;
end;
end case;
end Set_Member;
AMapper : aliased Application_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the managed bean definitions.
-- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings
-- to read the servlet, managed beans and navigation rules.
-- ------------------------------
package body Reader_Config is
-- Get the navigation handler for the Navigation_Config instantiation
-- GNAT crashes if the call is made in the instantation part.
Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler;
package Bean_Config is
new ASF.Beans.Mappers.Reader_Config (Reader, App.Factory'Access,
Context.all'Access);
package Navigation_Config is
new ASF.Navigations.Mappers.Reader_Config (Reader, Nav, Context.all'Access);
package Servlet_Config is
new ASF.Servlets.Mappers.Reader_Config (Reader, App.all'Access,
Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Navigation_Config);
pragma Warnings (Off, Servlet_Config);
Config : aliased Application_Config;
begin
-- Install the property context that gives access
-- to the application configuration properties
Prop_Context.Set_Properties (App.Conf);
Context.Set_Resolver (Prop_Context'Unchecked_Access);
Reader.Add_Mapping ("faces-config", AMapper'Access);
Reader.Add_Mapping ("module", AMapper'Access);
Reader.Add_Mapping ("web-app", AMapper'Access);
Config.App := App;
Application_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
-- ------------------------------
-- Read the configuration file associated with the application. This includes:
-- <ul>
-- <li>The servlet and filter mappings</li>
-- <li>The managed bean definitions</li>
-- <li>The navigation rules</li>
-- </ul>
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String) is
Reader : Util.Serialize.IO.XML.Parser;
Context : aliased EL.Contexts.Default.Default_Context;
-- Setup the <b>Reader</b> to parse and build the configuration for managed beans,
-- navigation rules, servlet rules. Each package instantiation creates a local variable
-- used while parsing the XML file.
package Config is
new Reader_Config (Reader, App'Unchecked_Access, Context'Unchecked_Access);
pragma Warnings (Off, Config);
begin
Log.Info ("Reading module configuration file {0}", File);
-- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log);
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end Read_Configuration;
-- ------------------------------
-- Create the configuration parameter definition instance.
-- ------------------------------
package body Parameter is
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access,
Default => PARAM_VALUE'Access);
-- ------------------------------
-- Returns the configuration parameter.
-- ------------------------------
function P return Config_Param is
begin
return Param;
end P;
end Parameter;
begin
AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR);
AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE);
end ASF.Applications.Main.Configs;
|
Fix reading configuration and setup of application bundles
|
Fix reading configuration and setup of application bundles
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
2115947387e9fbad38896fb4c14462b2e8b636b6
|
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
|
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
|
-----------------------------------------------------------------------
-- 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 AWA.Services.Contexts;
with AWA.Helpers.Requests;
with AWA.Helpers.Selectors;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
package body AWA.Blogs.Beans is
use type ADO.Identifier;
use Ada.Strings.Unbounded;
BLOG_ID_PARAMETER : constant String := "blog_id";
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if not From.Is_Null then
return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name);
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 Blog_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 a new blog.
-- ------------------------------
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
Bean.Module.Create_Blog (Workspace_Id => 0,
Title => Bean.Get_Name,
Result => Result);
end Create;
-- ------------------------------
-- 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 is
Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER);
Object : constant Blog_Bean_Access := new Blog_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Object.Load (Session, Blog_Id);
end if;
Object.Module := Module;
return Object.all'Access;
end Create_Blog_Bean;
-- ------------------------------
-- Create or save the post.
-- ------------------------------
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
if not Bean.Is_Inserted then
Bean.Module.Create_Post (Blog_Id => Bean.Blog_Id,
Title => Bean.Get_Title,
URI => Bean.Get_Uri,
Text => Bean.Get_Text,
Status => Bean.Get_Status,
Result => Result);
else
Bean.Module.Update_Post (Post_Id => Bean.Get_Id,
Title => Bean.Get_Title,
Text => Bean.Get_Text,
Status => Bean.Get_Status);
end if;
end Save;
-- ------------------------------
-- Delete a post.
-- ------------------------------
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Post (Post_Id => Bean.Get_Id);
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = BLOG_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
elsif Name = POST_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Get_Id));
elsif Name = POST_USERNAME_ATTR then
return Util.Beans.Objects.To_Object (String '(From.Get_Author.Get_Name));
else
return AWA.Blogs.Models.Post_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = BLOG_ID_ATTR then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then
From.Load_Post (ADO.Utils.To_Identifier (Value));
elsif Name = POST_TEXT_ATTR then
From.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_TITLE_ATTR then
From.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_URI_ATTR then
From.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_STATUS_ATTR then
From.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value));
end if;
end Set_Value;
-- ------------------------------
-- Load the post.
-- ------------------------------
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Post.Module.Get_Session;
begin
Post.Load (Session, Id);
-- Post.Title := Post.Post.Get_Title;
-- Post.Text := Post.Post.Get_Text;
-- Post.URI := Post.Post.Get_Uri;
-- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of
-- objects does not work yet. Force loading the user here while the above
-- session is still open.
declare
A : constant String := String '(Post.Get_Author.Get_Name);
pragma Unreferenced (A);
begin
null;
end;
end Load_Post;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Post_Bean_Access := new Post_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Post_Bean;
-- ------------------------------
-- 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 is
use AWA.Blogs.Models;
Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List);
AWA.Blogs.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Post_List_Bean;
-- ------------------------------
-- Create the Blog_List_Bean bean instance.
-- ------------------------------
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Blog_Admin_Bean_Access := new Blog_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Post_List_Bean := Object.Post_List'Access;
Object.Blog_List_Bean := Object.Blog_List'Access;
return Object.all'Access;
end Create_Blog_Admin_Bean;
function Create_From_Status is
new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type,
"blog_status_");
-- ------------------------------
-- 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 is
pragma Unreferenced (Module);
use AWA.Helpers;
begin
return Selectors.Create_Selector_Bean (Bundle => "blogs",
Context => null,
Create => Create_From_Status'Access).all'Access;
end Create_Status_List;
-- ------------------------------
-- Load the list of blogs.
-- ------------------------------
procedure Load_Blogs (List : in Blog_Admin_Bean) is
use AWA.Blogs.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.Blogs.Models.Query_Blog_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Blog_List_Bean.all, Session, Query);
List.Flags (INIT_BLOG_LIST) := True;
end Load_Blogs;
-- ------------------------------
-- Get the blog identifier.
-- ------------------------------
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier is
begin
if List.Blog_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
if not List.Blog_List.List.Is_Empty then
return List.Blog_List.List.Element (0).Id;
end if;
end if;
return List.Blog_Id;
end Get_Blog_Id;
-- ------------------------------
-- Load the posts associated with the current blog.
-- ------------------------------
procedure Load_Posts (List : in Blog_Admin_Bean) is
use AWA.Blogs.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;
Blog_Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List);
Query.Bind_Param ("blog_id", Blog_Id);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Post_List_Bean.all, Session, Query);
List.Flags (INIT_POST_LIST) := True;
end if;
end Load_Posts;
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "blogs" then
if not List.Init_Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Blog_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "posts" then
if not List.Init_Flags (INIT_POST_LIST) then
Load_Posts (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Post_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
Id : constant ADO.Identifier := List.Get_Blog_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 Blog_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.Blog_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
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 AWA.Services.Contexts;
with AWA.Helpers.Requests;
with AWA.Helpers.Selectors;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
package body AWA.Blogs.Beans is
use type ADO.Identifier;
use Ada.Strings.Unbounded;
BLOG_ID_PARAMETER : constant String := "blog_id";
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if not From.Is_Null then
return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name);
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 Blog_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 a new blog.
-- ------------------------------
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
Bean.Module.Create_Blog (Workspace_Id => 0,
Title => Bean.Get_Name,
Result => Result);
end Create;
-- ------------------------------
-- 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 is
Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER);
Object : constant Blog_Bean_Access := new Blog_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Object.Load (Session, Blog_Id);
end if;
Object.Module := Module;
return Object.all'Access;
end Create_Blog_Bean;
-- ------------------------------
-- Create or save the post.
-- ------------------------------
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
if not Bean.Is_Inserted then
Bean.Module.Create_Post (Blog_Id => Bean.Blog_Id,
Title => Bean.Get_Title,
URI => Bean.Get_Uri,
Text => Bean.Get_Text,
Status => Bean.Get_Status,
Result => Result);
else
Bean.Module.Update_Post (Post_Id => Bean.Get_Id,
Title => Bean.Get_Title,
Text => Bean.Get_Text,
Status => Bean.Get_Status);
Result := Bean.Get_Id;
end if;
Bean.Tags.Update_Tags (Result);
end Save;
-- ------------------------------
-- Delete a post.
-- ------------------------------
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Post (Post_Id => Bean.Get_Id);
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = BLOG_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
elsif Name = POST_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Get_Id));
elsif Name = POST_USERNAME_ATTR then
return Util.Beans.Objects.To_Object (String '(From.Get_Author.Get_Name));
elsif Name = POST_TAG_ATTR then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
else
return AWA.Blogs.Models.Post_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = BLOG_ID_ATTR then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then
From.Load_Post (ADO.Utils.To_Identifier (Value));
elsif Name = POST_TEXT_ATTR then
From.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_TITLE_ATTR then
From.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_URI_ATTR then
From.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_STATUS_ATTR then
From.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value));
end if;
end Set_Value;
-- ------------------------------
-- Load the post.
-- ------------------------------
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Post.Module.Get_Session;
begin
Post.Load (Session, Id);
Post.Tags.Load_Tags (Session, Id);
-- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of
-- objects does not work yet. Force loading the user here while the above
-- session is still open.
declare
A : constant String := String '(Post.Get_Author.Get_Name);
pragma Unreferenced (A);
begin
null;
end;
end Load_Post;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Post_Bean_Access := new Post_Bean;
begin
Object.Module := Module;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Blogs.Models.POST_TABLE);
Object.Tags.Set_Permission ("blog-update-post");
return Object.all'Access;
end Create_Post_Bean;
-- ------------------------------
-- 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 is
use AWA.Blogs.Models;
Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List);
AWA.Blogs.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Post_List_Bean;
-- ------------------------------
-- Create the Blog_List_Bean bean instance.
-- ------------------------------
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Blog_Admin_Bean_Access := new Blog_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Post_List_Bean := Object.Post_List'Access;
Object.Blog_List_Bean := Object.Blog_List'Access;
return Object.all'Access;
end Create_Blog_Admin_Bean;
function Create_From_Status is
new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type,
"blog_status_");
-- ------------------------------
-- 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 is
pragma Unreferenced (Module);
use AWA.Helpers;
begin
return Selectors.Create_Selector_Bean (Bundle => "blogs",
Context => null,
Create => Create_From_Status'Access).all'Access;
end Create_Status_List;
-- ------------------------------
-- Load the list of blogs.
-- ------------------------------
procedure Load_Blogs (List : in Blog_Admin_Bean) is
use AWA.Blogs.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.Blogs.Models.Query_Blog_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Blog_List_Bean.all, Session, Query);
List.Flags (INIT_BLOG_LIST) := True;
end Load_Blogs;
-- ------------------------------
-- Get the blog identifier.
-- ------------------------------
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier is
begin
if List.Blog_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
if not List.Blog_List.List.Is_Empty then
return List.Blog_List.List.Element (0).Id;
end if;
end if;
return List.Blog_Id;
end Get_Blog_Id;
-- ------------------------------
-- Load the posts associated with the current blog.
-- ------------------------------
procedure Load_Posts (List : in Blog_Admin_Bean) is
use AWA.Blogs.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;
Blog_Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List);
Query.Bind_Param ("blog_id", Blog_Id);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Post_List_Bean.all, Session, Query);
List.Flags (INIT_POST_LIST) := True;
end if;
end Load_Posts;
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "blogs" then
if not List.Init_Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Blog_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "posts" then
if not List.Init_Flags (INIT_POST_LIST) then
Load_Posts (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Post_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
Id : constant ADO.Identifier := List.Get_Blog_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 Blog_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.Blog_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
end AWA.Blogs.Beans;
|
Update the tags associated with a post after the post is saved or created Load the tags associated with the post.
|
Update the tags associated with a post after the post is saved or created
Load the tags associated with the post.
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
02d4da57b4d12bb6448e740ae07e1918afc432cf
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes;
-- === Documents ===
-- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The <tt>Document</tt> holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the <tt>Wiki.Documents</tt> package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List);
-- Pop the HTML tag.
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag);
-- Returns True if the current node is the root document node.
function Is_Root_Node (Doc : in Document) return Boolean;
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Returns True if the document is empty.
function Is_Empty (Doc : in Document) return Boolean;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Node_List_Ref;
TOC : Wiki.Nodes.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
end record;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 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 Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes;
-- === Documents ===
-- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The <tt>Document</tt> holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the <tt>Wiki.Documents</tt> package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List);
-- Pop the HTML tag.
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag);
-- Returns True if the current node is the root document node.
function Is_Root_Node (Doc : in Document) return Boolean;
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Returns True if the document is empty.
function Is_Empty (Doc : in Document) return Boolean;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Returns True if the table of contents is visible and must be rendered.
function Is_Visible_TOC (Doc : in Document) return Boolean;
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Node_List_Ref;
TOC : Wiki.Nodes.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
Declare the Is_Visible_TOC function and add a Visible_TOC member to the document
|
Declare the Is_Visible_TOC function and add a Visible_TOC member to the document
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
f35cbe2da1cab821b729c9997f060e6eab8c4591
|
src/util-serialize-io-json.ads
|
src/util-serialize-io-json.ads
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Util.Streams.Texts;
with Util.Stacks;
with Util.Beans.Objects;
package Util.Serialize.IO.JSON is
-- ------------------------------
-- JSON Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a JSON output stream.
-- The stream object takes care of the JSON escape rules.
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private;
-- Set the target output stream.
procedure Initialize (Stream : in out Output_Stream;
Output : in Util.Streams.Texts.Print_Stream_Access);
-- Flush the buffer (if any) to the sink.
overriding
procedure Flush (Stream : in out Output_Stream);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Write a raw character on the stream.
procedure Write (Stream : in out Output_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Output_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Output_Stream;
Item : in String);
-- Start a JSON document. This operation writes the initial JSON marker ('{').
overriding
procedure Start_Document (Stream : in out Output_Stream);
-- Finish a JSON document by writing the final JSON marker ('}').
overriding
procedure End_Document (Stream : in out Output_Stream);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Start a new JSON object. If the name is not empty, write it as a string
-- followed by the ':' (colon). The JSON object starts with '{' (curly brace).
-- Example: "list": {
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current JSON object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a JSON name/value pair. The value is written according to its type
-- Example: "name": null
-- "name": false
-- "name": 12
-- "name": "value"
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Starts a JSON array.
-- Example: "list": [
overriding
procedure Start_Array (Stream : in out Output_Stream;
Name : in String);
-- Terminates a JSON array.
overriding
procedure End_Array (Stream : in out Output_Stream;
Name : in String);
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Read a JSON file and return an object.
function Read (Path : in String) return Util.Beans.Objects.Object;
private
type Node_Info is record
Is_Array : Boolean := False;
Is_Root : Boolean := False;
Has_Fields : Boolean := False;
end record;
type Node_Info_Access is access all Node_Info;
package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info,
Element_Type_Access => Node_Info_Access);
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record
Stack : Node_Info_Stack.Stack;
Stream : Util.Streams.Texts.Print_Stream_Access;
end record;
procedure Write_Field_Name (Stream : in out Output_Stream;
Name : in String);
type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET,
T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE,
T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL);
type Parser is new Util.Serialize.IO.Parser with record
Token : Ada.Strings.Unbounded.Unbounded_String;
Pending_Token : Token_Type := T_EOF;
Line_Number : Natural := 1;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
end record;
end Util.Serialize.IO.JSON;
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Util.Streams.Texts;
with Util.Stacks;
with Util.Beans.Objects;
with Util.Nullables;
package Util.Serialize.IO.JSON is
-- ------------------------------
-- JSON Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a JSON output stream.
-- The stream object takes care of the JSON escape rules.
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private;
-- Set the target output stream.
procedure Initialize (Stream : in out Output_Stream;
Output : in Util.Streams.Texts.Print_Stream_Access);
-- Flush the buffer (if any) to the sink.
overriding
procedure Flush (Stream : in out Output_Stream);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Write a raw character on the stream.
procedure Write (Stream : in out Output_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Output_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Output_Stream;
Item : in String);
-- Start a JSON document. This operation writes the initial JSON marker ('{').
overriding
procedure Start_Document (Stream : in out Output_Stream);
-- Finish a JSON document by writing the final JSON marker ('}').
overriding
procedure End_Document (Stream : in out Output_Stream);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Start a new JSON object. If the name is not empty, write it as a string
-- followed by the ':' (colon). The JSON object starts with '{' (curly brace).
-- Example: "list": {
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current JSON object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a JSON name/value pair. The value is written according to its type
-- Example: "name": null
-- "name": false
-- "name": 12
-- "name": "value"
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Starts a JSON array.
-- Example: "list": [
overriding
procedure Start_Array (Stream : in out Output_Stream;
Name : in String);
-- Terminates a JSON array.
overriding
procedure End_Array (Stream : in out Output_Stream;
Name : in String);
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Read a JSON file and return an object.
function Read (Path : in String) return Util.Beans.Objects.Object;
private
type Node_Info is record
Is_Array : Boolean := False;
Is_Root : Boolean := False;
Has_Fields : Boolean := False;
end record;
type Node_Info_Access is access all Node_Info;
package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info,
Element_Type_Access => Node_Info_Access);
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record
Stack : Node_Info_Stack.Stack;
Stream : Util.Streams.Texts.Print_Stream_Access;
end record;
procedure Write_Field_Name (Stream : in out Output_Stream;
Name : in String);
type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET,
T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE,
T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL);
type Parser is new Util.Serialize.IO.Parser with record
Token : Ada.Strings.Unbounded.Unbounded_String;
Pending_Token : Token_Type := T_EOF;
Line_Number : Natural := 1;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
end record;
end Util.Serialize.IO.JSON;
|
Declare Write_Attribute and Write_Entity for Nullable_String
|
Declare Write_Attribute and Write_Entity for Nullable_String
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1ff2b0ff6dd303f55dd3d35d8d364bdd8c5a8f3f
|
src/util-streams-buffered.ads
|
src/util-streams-buffered.ads
|
-----------------------------------------------------------------------
-- Util.Streams.Buffered -- Buffered streams Stream utilities
-- Copyright (C) 2010, 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.Strings.Wide_Wide_Unbounded;
with Ada.Finalization;
package Util.Streams.Buffered is
pragma Preelaborate;
-- -----------------------
-- Buffered stream
-- -----------------------
-- The <b>Buffered_Stream</b> is an output/input stream which uses
-- an intermediate buffer. It can be configured to read or write to
-- another stream that it will read or write using the buffer.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the buffered stream.
type Buffered_Stream is limited new Output_Stream and Input_Stream with private;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Buffered_Stream;
Output : in Output_Stream_Access;
Input : in Input_Stream_Access;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Buffered_Stream;
Size : in Positive);
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Buffered_Stream;
Content : in String);
-- Close the sink.
overriding
procedure Close (Stream : in out Buffered_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access;
-- Write a raw character on the stream.
procedure Write (Stream : in out Buffered_Stream;
Char : in Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Buffered_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Buffered_Stream);
-- Get the number of element in the stream.
function Get_Size (Stream : in Buffered_Stream) return Natural;
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Buffered_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Buffered_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Buffered_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Buffered_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Buffered_Stream) return Boolean;
private
use Ada.Streams;
type Buffered_Stream is new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : Output_Stream_Access := null;
-- The input stream to use to fill the buffer.
Input : Input_Stream_Access := null;
No_Flush : Boolean := False;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Buffered_Stream);
end Util.Streams.Buffered;
|
-----------------------------------------------------------------------
-- Util.Streams.Buffered -- Buffered streams 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.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Finalization;
package Util.Streams.Buffered is
pragma Preelaborate;
-- -----------------------
-- Buffered stream
-- -----------------------
-- The <b>Buffered_Stream</b> is an output/input stream which uses
-- an intermediate buffer. It can be configured to read or write to
-- another stream that it will read or write using the buffer.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the buffered stream.
type Buffered_Stream is limited new Output_Stream and Input_Stream with private;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Buffered_Stream;
Output : in Output_Stream_Access;
Input : in Input_Stream_Access;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Buffered_Stream;
Size : in Positive);
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Buffered_Stream;
Content : in String);
-- Close the sink.
overriding
procedure Close (Stream : in out Buffered_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access;
-- Write a raw character on the stream.
procedure Write (Stream : in out Buffered_Stream;
Char : in Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Buffered_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Buffered_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Buffered_Stream);
-- Get the number of element in the stream.
function Get_Size (Stream : in Buffered_Stream) return Natural;
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Buffered_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Buffered_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Buffered_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Buffered_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Buffered_Stream) return Boolean;
private
use Ada.Streams;
type Buffered_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : Output_Stream_Access := null;
-- The input stream to use to fill the buffer.
Input : Input_Stream_Access := null;
No_Flush : Boolean := False;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Buffered_Stream);
end Util.Streams.Buffered;
|
Fix compilation error with GNAT 2015
|
Fix compilation error with GNAT 2015
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b6ce366d55dd61b290a436dccb2b4d05268eeab6
|
src/util-refs.ads
|
src/util-refs.ads
|
-----------------------------------------------------------------------
-- util-refs -- Reference Counting
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Concurrent.Counters;
-- The <b>Util.Refs</b> package provides support to implement object reference counting.
--
-- The data type to share through reference counting has to inherit from <b>Ref_Entity</b>
-- and the generic package <b>References</b> has to be instantiated.
-- <pre>
-- type Data is new Util.Refs.Ref_Entity with record ... end record;
-- type Data_Access is access all Data;
--
-- package Data_Ref is new Utils.Refs.References (Data, Data_Access);
-- </pre>
--
-- The reference is used as follows:
--
-- <pre>
-- D : Data_Ref.Ref := Data_Ref.Create; -- Allocate and get a reference
-- D2 : Data_Ref.Ref := D; -- Share reference
-- D.Value.all.XXXX := 0; -- Set data member XXXX
-- </pre>
--
-- When a reference is shared in a multi-threaded environment, the reference has to
-- be protected by using the <b>References.Atomic_Ref</b> type.
--
-- R : Data_Ref.Atomic_Ref;
--
-- The reference is then obtained by the protected operation <b>Get</b>.
--
-- D : Data_Ref.Ref := R.Get;
--
package Util.Refs is
-- Root of referenced objects.
type Ref_Entity is abstract tagged limited private;
-- Finalize the referenced object. This is called before the object is freed.
procedure Finalize (Object : in out Ref_Entity) is null;
generic
type Element_Type (<>) is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package Indefinite_References is
type Ref is new Ada.Finalization.Controlled with private;
-- Create an element and return a reference to that element.
function Create (Value : in Element_Access) return Ref;
-- Get the element access value.
function Value (Object : in Ref'Class) return Element_Access;
pragma Inline_Always (Value);
-- Returns true if the reference does not contain any element.
function Is_Null (Object : in Ref'Class) return Boolean;
pragma Inline_Always (Is_Null);
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
protected type Atomic_Ref is
-- Get the reference
function Get return Ref;
-- Change the reference
procedure Set (Object : in Ref);
private
Value : Ref;
end Atomic_Ref;
private
type Ref is new Ada.Finalization.Controlled with record
Target : Element_Access := null;
end record;
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
overriding
procedure Finalize (Obj : in out Ref);
-- Update the reference counter after an assignment.
overriding
procedure Adjust (Obj : in out Ref);
end Indefinite_References;
generic
type Element_Type is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package References is
package IR is new Indefinite_References (Element_Type, Element_Access);
subtype Ref is IR.Ref;
-- Create an element and return a reference to that element.
function Create return Ref;
-- Get the element access value.
function Value (Object : in Ref'Class) return Element_Access
renames IR.Value;
-- Returns true if the reference does not contain any element.
function Is_Null (Object : in Ref'Class) return Boolean
renames IR.Is_Null;
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
subtype Atomic_Ref is IR.Atomic_Ref;
end References;
private
type Ref_Entity is abstract tagged limited record
Ref_Counter : Util.Concurrent.Counters.Counter;
end record;
end Util.Refs;
|
-----------------------------------------------------------------------
-- util-refs -- Reference Counting
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Concurrent.Counters;
-- The <b>Util.Refs</b> package provides support to implement object reference counting.
--
-- The data type to share through reference counting has to inherit from <b>Ref_Entity</b>
-- and the generic package <b>References</b> has to be instantiated.
-- <pre>
-- type Data is new Util.Refs.Ref_Entity with record ... end record;
-- type Data_Access is access all Data;
--
-- package Data_Ref is new Utils.Refs.References (Data, Data_Access);
-- </pre>
--
-- The reference is used as follows:
--
-- <pre>
-- D : Data_Ref.Ref := Data_Ref.Create; -- Allocate and get a reference
-- D2 : Data_Ref.Ref := D; -- Share reference
-- D.Value.all.XXXX := 0; -- Set data member XXXX
-- </pre>
--
-- When a reference is shared in a multi-threaded environment, the reference has to
-- be protected by using the <b>References.Atomic_Ref</b> type.
--
-- R : Data_Ref.Atomic_Ref;
--
-- The reference is then obtained by the protected operation <b>Get</b>.
--
-- D : Data_Ref.Ref := R.Get;
--
package Util.Refs is
-- Root of referenced objects.
type Ref_Entity is abstract tagged limited private;
-- Finalize the referenced object. This is called before the object is freed.
procedure Finalize (Object : in out Ref_Entity) is null;
generic
type Element_Type (<>) is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package Indefinite_References is
type Ref is new Ada.Finalization.Controlled with private;
-- Create an element and return a reference to that element.
function Create (Value : in Element_Access) return Ref;
-- Get the element access value.
function Value (Object : in Ref'Class) return Element_Access;
pragma Inline_Always (Value);
-- Returns true if the reference does not contain any element.
function Is_Null (Object : in Ref'Class) return Boolean;
pragma Inline_Always (Is_Null);
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
protected type Atomic_Ref is
-- Get the reference
function Get return Ref;
-- Change the reference
procedure Set (Object : in Ref);
private
Value : Ref;
end Atomic_Ref;
private
type Ref is new Ada.Finalization.Controlled with record
Target : Element_Access := null;
end record;
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
overriding
procedure Finalize (Obj : in out Ref);
-- Update the reference counter after an assignment.
overriding
procedure Adjust (Obj : in out Ref);
end Indefinite_References;
generic
type Element_Type is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package References is
package IR is new Indefinite_References (Element_Type, Element_Access);
subtype Ref is IR.Ref;
-- Create an element and return a reference to that element.
function Create return Ref;
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
subtype Atomic_Ref is IR.Atomic_Ref;
end References;
private
type Ref_Entity is abstract tagged limited record
Ref_Counter : Util.Concurrent.Counters.Counter;
end record;
end Util.Refs;
|
Remove some renames which are not necessary
|
Remove some renames which are not necessary
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.