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
|
---|---|---|---|---|---|---|---|---|---|
dbe15d862d2874d77aefac53a22b91b44f7109e9
|
src/gen-commands-layout.adb
|
src/gen-commands-layout.adb
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with Util.Strings;
with Util.Files;
package body Gen.Commands.Layout is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name);
use Ada.Strings.Unbounded;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory;
Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts");
function Get_Name return String is
Name : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
Page_Name : constant String := Get_Name;
begin
if Page_Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Layout_Dir);
Generator.Set_Global ("pageName", Page_Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("add-layout: Add a new layout page to the application");
Put_Line ("Usage: add-layout NAME");
New_Line;
Put_Line (" The layout page allows to give a common look to a set of pages.");
Put_Line (" You can create several layouts for your application.");
Put_Line (" Each layout can reference one or several building blocks that are defined");
Put_Line (" in the original page.");
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/WEB-INF/layouts/<name>.xhtml");
end Help;
end Gen.Commands.Layout;
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Gen.Artifacts;
with Util.Strings;
with Util.Files;
package body Gen.Commands.Layout is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name);
use Ada.Strings.Unbounded;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory;
Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts");
function Get_Name return String is
Name : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
Page_Name : constant String := Get_Name;
begin
if Page_Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Layout_Dir);
Generator.Set_Global ("pageName", Page_Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("add-layout: Add a new layout page to the application");
Put_Line ("Usage: add-layout NAME");
New_Line;
Put_Line (" The layout page allows to give a common look to a set of pages.");
Put_Line (" You can create several layouts for your application.");
Put_Line (" Each layout can reference one or several building blocks that are defined");
Put_Line (" in the original page.");
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/WEB-INF/layouts/<name>.xhtml");
end Help;
end Gen.Commands.Layout;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
953a01efd87aa3e64eae9ae0fdeb262ae07aa608
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Answer (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.ANSWER_TABLE,
Session => Session);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (From.Answer_List, Session, Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
Add the user_id and entity_type in the answer query to get the rating and user vote for each answer
|
Add the user_id and entity_type in the answer query to get the rating and user vote for each answer
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
29b3a08de0a9a940b5af54a8980510de92b32922
|
src/asf-components-html-lists.adb
|
src/asf-components-html-lists.adb
|
-----------------------------------------------------------------------
-- html.lists -- List of items
-- Copyright (C) 2009, 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 Util.Log.Loggers;
with Util.Beans.Basic;
with ASF.Components.Base;
package body ASF.Components.Html.Lists is
use Util.Log;
use type EL.Objects.Data_Type;
Log : constant Loggers.Logger := Loggers.Create ("ASF.Components.Html.Lists");
-- ------------------------------
-- Get the value to write on the output.
-- ------------------------------
function Get_Value (UI : in UIList) return EL.Objects.Object is
begin
return UI.Get_Attribute (UI.Get_Context.all, "value");
end Get_Value;
-- ------------------------------
-- Set the value to write on the output.
-- ------------------------------
procedure Set_Value (UI : in out UIList;
Value : in EL.Objects.Object) is
begin
null;
end Set_Value;
-- ------------------------------
-- Get the variable name
-- ------------------------------
function Get_Var (UI : in UIList) return String is
Var : constant EL.Objects.Object := UI.Get_Attribute (UI.Get_Context.all, "var");
begin
return EL.Objects.To_String (Var);
end Get_Var;
procedure Encode_Children (UI : in UIList;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Value : EL.Objects.Object := Get_Value (UI);
Kind : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value);
Name : constant String := UI.Get_Var;
Bean : access Util.Beans.Basic.Readonly_Bean'Class;
Is_Reverse : constant Boolean := UI.Get_Attribute ("reverse", Context, False);
List : Util.Beans.Basic.List_Bean_Access;
Count : Natural;
begin
-- Check that we have a List_Bean but do not complain if we have a null value.
if Kind /= EL.Objects.TYPE_BEAN then
if Kind /= EL.Objects.TYPE_NULL then
ASF.Components.Base.Log_Error (UI, "Invalid list bean (found a {0})",
EL.Objects.Get_Type_Name (Value));
end if;
return;
end if;
Bean := EL.Objects.To_Bean (Value);
if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then
ASF.Components.Base.Log_Error (UI, "Invalid list bean: "
& "it does not implement 'List_Bean' interface");
return;
end if;
List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access;
Count := List.Get_Count;
if Is_Reverse then
for I in reverse 1 .. Count loop
List.Set_Row_Index (I);
Value := List.Get_Row;
Context.Set_Attribute (Name, Value);
Log.Debug ("Set variable {0}", Name);
Base.UIComponent (UI).Encode_Children (Context);
end loop;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
Value := List.Get_Row;
Context.Set_Attribute (Name, Value);
Log.Debug ("Set variable {0}", Name);
Base.UIComponent (UI).Encode_Children (Context);
end loop;
end if;
end;
end Encode_Children;
end ASF.Components.Html.Lists;
|
-----------------------------------------------------------------------
-- html.lists -- List of items
-- Copyright (C) 2009, 2010, 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.Log.Loggers;
with Util.Beans.Basic;
with ASF.Components.Base;
package body ASF.Components.Html.Lists is
use type EL.Objects.Data_Type;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Components.Html.Lists");
function Get_Item_Layout (List_Layout : in String;
Item_Class : in String) return String;
-- ------------------------------
-- Get the list layout to use. The default is to use no layout or a div if some CSS style
-- is applied on the list or some specific list ID must be generated. Possible layout values
-- include:
-- "simple" : the list is rendered as is or as a div with each children as is,
-- "unorderedList" : the list is rendered as an HTML ul/li list,
-- "orderedList" : the list is rendered as an HTML ol/li list.
-- ------------------------------
function Get_Layout (UI : in UIList;
Class : in String;
Context : in Faces_Context'Class) return String is
Value : constant EL.Objects.Object := UI.Get_Attribute (Context, "layout");
Layout : constant String := EL.Objects.To_String (Value);
begin
if Layout = "orderedList" or Layout = "ordered" then
return "ol";
elsif Layout = "unorderedList" or Layout = "unordered" then
return "ul";
elsif Class'Length > 0 or else not UI.Is_Generated_Id then
return "div";
else
return "";
end if;
end Get_Layout;
-- ------------------------------
-- Get the item layout according to the list layout and the item class (if any).
-- ------------------------------
function Get_Item_Layout (List_Layout : in String;
Item_Class : in String) return String is
begin
if List_Layout'Length = 2 then
return "li";
elsif Item_Class'Length > 0 then
return "div";
else
return "";
end if;
end Get_Item_Layout;
-- ------------------------------
-- Get the value to write on the output.
-- ------------------------------
function Get_Value (UI : in UIList) return EL.Objects.Object is
begin
return UI.Get_Attribute (UI.Get_Context.all, "value");
end Get_Value;
-- ------------------------------
-- Set the value to write on the output.
-- ------------------------------
procedure Set_Value (UI : in out UIList;
Value : in EL.Objects.Object) is
begin
null;
end Set_Value;
-- ------------------------------
-- Get the variable name
-- ------------------------------
function Get_Var (UI : in UIList) return String is
Var : constant EL.Objects.Object := UI.Get_Attribute (UI.Get_Context.all, "var");
begin
return EL.Objects.To_String (Var);
end Get_Var;
-- ------------------------------
-- Encode an item of the list with the given item layout and item class.
-- ------------------------------
procedure Encode_Item (UI : in UIList;
Item_Layout : in String;
Item_Class : in String;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
if Item_Layout'Length > 0 then
Writer.Start_Element (Item_Layout);
end if;
if Item_Class'Length > 0 then
Writer.Write_Attribute ("class", Item_Class);
end if;
Base.UIComponent (UI).Encode_Children (Context);
if Item_Layout'Length > 0 then
Writer.End_Element (Item_Layout);
end if;
end Encode_Item;
procedure Encode_Children (UI : in UIList;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Value : EL.Objects.Object := Get_Value (UI);
Kind : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value);
Name : constant String := UI.Get_Var;
Bean : access Util.Beans.Basic.Readonly_Bean'Class;
Is_Reverse : constant Boolean := UI.Get_Attribute ("reverse", Context, False);
List : Util.Beans.Basic.List_Bean_Access;
Count : Natural;
begin
-- Check that we have a List_Bean but do not complain if we have a null value.
if Kind /= EL.Objects.TYPE_BEAN then
if Kind /= EL.Objects.TYPE_NULL then
ASF.Components.Base.Log_Error (UI, "Invalid list bean (found a {0})",
EL.Objects.Get_Type_Name (Value));
end if;
return;
end if;
Bean := EL.Objects.To_Bean (Value);
if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then
ASF.Components.Base.Log_Error (UI, "Invalid list bean: "
& "it does not implement 'List_Bean' interface");
return;
end if;
List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access;
Count := List.Get_Count;
if Count /= 0 then
declare
Class : constant String := UI.Get_Attribute (STYLE_CLASS_ATTR_NAME,
Context, "");
Item_Class : constant String := UI.Get_Attribute (ITEM_STYLE_CLASS_ATTR_NAME,
Context, "");
Layout : constant String := UI.Get_Layout (Class, Context);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Item_Layout : constant String := Get_Item_Layout (Layout, Item_Class);
begin
if Layout'Length > 0 then
Writer.Start_Element (Layout);
end if;
if not UI.Is_Generated_Id then
Writer.Write_Attribute ("id", UI.Get_Client_Id);
end if;
if Class'Length > 0 then
Writer.Write_Attribute ("class", Class);
end if;
if Is_Reverse then
for I in reverse 1 .. Count loop
List.Set_Row_Index (I);
Value := List.Get_Row;
Context.Set_Attribute (Name, Value);
Log.Debug ("Set variable {0}", Name);
UI.Encode_Item (Item_Layout, Item_Class, Context);
end loop;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
Value := List.Get_Row;
Context.Set_Attribute (Name, Value);
Log.Debug ("Set variable {0}", Name);
UI.Encode_Item (Item_Layout, Item_Class, Context);
end loop;
end if;
if Layout'Length > 0 then
Writer.End_Element (Layout);
end if;
end;
end if;
end;
end Encode_Children;
end ASF.Components.Html.Lists;
|
Add support to render ordered and unordered lists - Implement Get_Layout and Encode_Item - Allow to render a CSS class on the list as well as on each list item
|
Add support to render ordered and unordered lists
- Implement Get_Layout and Encode_Item
- Allow to render a CSS class on the list as well as on each list item
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
dec94eb8a6e19f625c39e19a424ca545c39f338a
|
src/gen-model-mappings.adb
|
src/gen-model-mappings.adb
|
-----------------------------------------------------------------------
-- gen-model-mappings -- Type mappings for Code Generator
-- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
-- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML
-- type into the Ada type.
package body Gen.Model.Mappings is
use Ada.Strings.Unbounded;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings");
Types : Mapping_Maps.Map;
Mapping_Name : Unbounded_String;
-- ------------------------------
-- 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 Mapping_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (From.Target);
elsif Name = "isBoolean" then
return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN);
elsif Name = "isInteger" then
return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER or From.Kind = T_ENTITY_TYPE);
elsif Name = "isString" then
return Util.Beans.Objects.To_Object (From.Kind = T_STRING);
elsif Name = "isIdentifier" then
return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER);
elsif Name = "isDate" then
return Util.Beans.Objects.To_Object (From.Kind = T_DATE);
elsif Name = "isBlob" then
return Util.Beans.Objects.To_Object (From.Kind = T_BLOB);
elsif Name = "isEnum" then
return Util.Beans.Objects.To_Object (From.Kind = T_ENUM);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Get the type name.
-- ------------------------------
function Get_Type_Name (From : Mapping_Definition) return String is
begin
case From.Kind is
when T_BOOLEAN =>
return "boolean";
when T_INTEGER =>
return "integer";
when T_DATE =>
return "date";
when T_IDENTIFIER =>
return "identifier";
when T_STRING =>
return "string";
when T_ENTITY_TYPE =>
return "entity_type";
when T_ENUM =>
return From.Get_Name;
when others =>
return From.Get_Name;
end case;
end Get_Type_Name;
-- ------------------------------
-- Find the mapping for the given type name.
-- ------------------------------
function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String;
Allow_Null : in Boolean)
return Mapping_Definition_Access is
Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name);
begin
if not Mapping_Maps.Has_Element (Pos) then
Log.Info ("Type '{0}' not found in mapping table '{1}'",
To_String (Name), To_String (Mapping_Name));
return null;
elsif Allow_Null then
if Mapping_Maps.Element (Pos).Allow_Null = null then
Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'",
To_String (Name), To_String (Mapping_Name));
return Mapping_Maps.Element (Pos);
end if;
return Mapping_Maps.Element (Pos).Allow_Null;
else
return Mapping_Maps.Element (Pos);
end if;
end Find_Type;
procedure Register_Type (Name : in String;
Mapping : in Mapping_Definition_Access;
Kind : in Basic_Type) is
N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name);
Pos : constant Mapping_Maps.Cursor := Types.Find (N);
begin
Log.Debug ("Register type '{0}'", Name);
if not Mapping_Maps.Has_Element (Pos) then
Mapping.Kind := Kind;
Types.Insert (N, Mapping);
end if;
end Register_Type;
-- ------------------------------
-- Register a type mapping <b>From</b> that is mapped to <b>Target</b>.
-- ------------------------------
procedure Register_Type (Target : in String;
From : in String;
Kind : in Basic_Type;
Allow_Null : in Boolean) is
Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From);
Pos : constant Mapping_Maps.Cursor := Types.Find (Name);
Mapping : Mapping_Definition_Access;
Found : Boolean;
begin
Log.Debug ("Register type '{0}' mapped to '{1}' type {2}",
From, Target, Basic_Type'Image (Kind));
Found := Mapping_Maps.Has_Element (Pos);
if Found then
Mapping := Mapping_Maps.Element (Pos);
else
Mapping := new Mapping_Definition;
Mapping.Set_Name (From);
Types.Insert (Name, Mapping);
end if;
if Allow_Null then
Mapping.Allow_Null := new Mapping_Definition;
Mapping.Allow_Null.Target := To_Unbounded_String (Target);
Mapping.Allow_Null.Kind := Kind;
Mapping.Allow_Null.Nullable := True;
if not Found then
Mapping.Target := To_Unbounded_String (Target);
Mapping.Kind := Kind;
end if;
else
Mapping.Target := To_Unbounded_String (Target);
Mapping.Kind := Kind;
end if;
end Register_Type;
-- ------------------------------
-- Setup the type mapping for the language identified by the given name.
-- ------------------------------
procedure Set_Mapping_Name (Name : in String) is
begin
Log.Info ("Using type mapping {0}", Name);
Mapping_Name := To_Unbounded_String (Name & ".");
end Set_Mapping_Name;
end Gen.Model.Mappings;
|
-----------------------------------------------------------------------
-- gen-model-mappings -- Type mappings for Code Generator
-- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
-- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML
-- type into the Ada type.
package body Gen.Model.Mappings is
use Ada.Strings.Unbounded;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings");
Types : Mapping_Maps.Map;
Mapping_Name : Unbounded_String;
-- ------------------------------
-- 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 Mapping_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (From.Target);
elsif Name = "isBoolean" then
return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN);
elsif Name = "isInteger" then
return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER or From.Kind = T_ENTITY_TYPE);
elsif Name = "isString" then
return Util.Beans.Objects.To_Object (From.Kind = T_STRING);
elsif Name = "isIdentifier" then
return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER);
elsif Name = "isDate" then
return Util.Beans.Objects.To_Object (From.Kind = T_DATE);
elsif Name = "isBlob" then
return Util.Beans.Objects.To_Object (From.Kind = T_BLOB);
elsif Name = "isEnum" then
return Util.Beans.Objects.To_Object (From.Kind = T_ENUM);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB);
elsif Name = "isNullable" then
return Util.Beans.Objects.To_Object (From.Nullable);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Get the type name.
-- ------------------------------
function Get_Type_Name (From : Mapping_Definition) return String is
begin
case From.Kind is
when T_BOOLEAN =>
return "boolean";
when T_INTEGER =>
return "integer";
when T_DATE =>
return "date";
when T_IDENTIFIER =>
return "identifier";
when T_STRING =>
return "string";
when T_ENTITY_TYPE =>
return "entity_type";
when T_ENUM =>
return From.Get_Name;
when others =>
return From.Get_Name;
end case;
end Get_Type_Name;
-- ------------------------------
-- Find the mapping for the given type name.
-- ------------------------------
function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String;
Allow_Null : in Boolean)
return Mapping_Definition_Access is
Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name);
begin
if not Mapping_Maps.Has_Element (Pos) then
Log.Info ("Type '{0}' not found in mapping table '{1}'",
To_String (Name), To_String (Mapping_Name));
return null;
elsif Allow_Null then
if Mapping_Maps.Element (Pos).Allow_Null = null then
Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'",
To_String (Name), To_String (Mapping_Name));
return Mapping_Maps.Element (Pos);
end if;
return Mapping_Maps.Element (Pos).Allow_Null;
else
return Mapping_Maps.Element (Pos);
end if;
end Find_Type;
procedure Register_Type (Name : in String;
Mapping : in Mapping_Definition_Access;
Kind : in Basic_Type) is
N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name);
Pos : constant Mapping_Maps.Cursor := Types.Find (N);
begin
Log.Debug ("Register type '{0}'", Name);
if not Mapping_Maps.Has_Element (Pos) then
Mapping.Kind := Kind;
Types.Insert (N, Mapping);
end if;
end Register_Type;
-- ------------------------------
-- Register a type mapping <b>From</b> that is mapped to <b>Target</b>.
-- ------------------------------
procedure Register_Type (Target : in String;
From : in String;
Kind : in Basic_Type;
Allow_Null : in Boolean) is
Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From);
Pos : constant Mapping_Maps.Cursor := Types.Find (Name);
Mapping : Mapping_Definition_Access;
Found : Boolean;
begin
Log.Debug ("Register type '{0}' mapped to '{1}' type {2}",
From, Target, Basic_Type'Image (Kind));
Found := Mapping_Maps.Has_Element (Pos);
if Found then
Mapping := Mapping_Maps.Element (Pos);
else
Mapping := new Mapping_Definition;
Mapping.Set_Name (From);
Types.Insert (Name, Mapping);
end if;
if Allow_Null then
Mapping.Allow_Null := new Mapping_Definition;
Mapping.Allow_Null.Target := To_Unbounded_String (Target);
Mapping.Allow_Null.Kind := Kind;
Mapping.Allow_Null.Nullable := True;
if not Found then
Mapping.Target := To_Unbounded_String (Target);
Mapping.Kind := Kind;
end if;
else
Mapping.Target := To_Unbounded_String (Target);
Mapping.Kind := Kind;
end if;
end Register_Type;
-- ------------------------------
-- Setup the type mapping for the language identified by the given name.
-- ------------------------------
procedure Set_Mapping_Name (Name : in String) is
begin
Log.Info ("Using type mapping {0}", Name);
Mapping_Name := To_Unbounded_String (Name & ".");
end Set_Mapping_Name;
end Gen.Model.Mappings;
|
Add 'isNullable' property to the type mapping
|
Add 'isNullable' property to the type mapping
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
68d272fd761b4a7e4c480bb3894ebf57a1fc2e75
|
boards/MicroBit/src/microbit-display.adb
|
boards/MicroBit/src/microbit-display.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with nRF51.GPIO; use nRF51.GPIO;
with nRF51.Device; use nRF51.Device;
with MicroBit.Time; use MicroBit.Time;
package body MicroBit.Display is
Is_Initialized : Boolean := False;
Bitmap : array (Coord, Coord) of Boolean := (others => (others => False));
Current_X, Current_Y : Coord := 0;
subtype Row_Range is Natural range 1 .. 3;
subtype Column_Range is Natural range 1 .. 9;
type LED_Point is record
Row_Id : Row_Range;
Column_Id : Column_Range;
end record;
Row_Points : array (Row_Range) of GPIO_Point :=
(P13, P14, P15);
Column_Points : array (Column_Range) of GPIO_Point :=
(P04, P05, P06, P07, P08, P09, P10, P11, P12);
Map : constant array (Coord, Coord) of LED_Point :=
(((1, 1), (3, 4), (2, 2), (1, 8), (3, 3)),
((2, 4), (3, 5), (1, 9), (1, 7), (2, 7)),
((1, 2), (3, 6), (2, 3), (1, 6), (3, 1)),
((2, 5), (3, 7), (3, 9), (1, 5), (2, 6)),
((1, 3), (3, 8), (2, 1), (1, 4), (3, 2))
);
procedure Initialize;
procedure Tick_Handler;
----------------
-- Initialize --
----------------
procedure Initialize is
Conf : GPIO_Configuration;
begin
Conf.Mode := Mode_Out;
Conf.Resistors := Pull_Up;
for Point of Row_Points loop
Point.Configure_IO (Conf);
Point.Clear;
end loop;
for Point of Column_Points loop
Point.Configure_IO (Conf);
Point.Set;
end loop;
Is_Initialized := True;
if not Tick_Subscribe (Tick_Handler'Access) then
raise Program_Error;
end if;
end Initialize;
------------------
-- Tick_Handler --
------------------
procedure Tick_Handler is
begin
-- Turn Off
-- Row source current
Row_Points (Map (Current_X, Current_Y).Row_Id).Clear;
-- Column sink current
Column_Points (Map (Current_X, Current_Y).Column_Id).Set;
if Current_X = Coord'Last then
Current_X := Coord'First;
if Current_Y = Coord'Last then
Current_Y := Coord'First;
else
Current_Y := Current_Y + 1;
end if;
else
Current_X := Current_X + 1;
end if;
-- Turn on?
if Bitmap (Current_X, Current_Y) then
-- Row source current
Row_Points (Map (Current_X, Current_Y).Row_Id).Set;
-- Column sink current
Column_Points (Map (Current_X, Current_Y).Column_Id).Clear;
end if;
end Tick_Handler;
-----------------
-- Initialized --
-----------------
function Initialized return Boolean is
begin
return Is_Initialized;
end Initialized;
---------
-- Set --
---------
procedure Set (X, Y : Coord) is
begin
Bitmap (X, Y) := True;
end Set;
-----------
-- Clear --
-----------
procedure Clear (X, Y : Coord) is
begin
Bitmap (X, Y) := False;
end Clear;
-----------
-- Clear --
-----------
procedure Clear is
begin
Bitmap := (others => (others => False));
end Clear;
-------------
-- Display --
-------------
procedure Display (C : Character) is
begin
Clear;
case C is
when 'A' =>
Bitmap := ((False, True, True, True, True),
(True, False, True, False, False),
(True, False, True, False, False),
(True, False, True, False, False),
(False, True, True, True, True));
when 'B' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, True),
(True, False, True, False, True),
(True, False, True, False, True),
(False, True, False, True, False));
when 'C' =>
Bitmap := ((False, True, True, True, False),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, False, True));
when 'D' =>
Bitmap := ((True, True, True, True, True),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, False, True),
(False, True, True, True, False));
when 'E' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, True),
(True, False, True, False, True),
(True, False, False, False, True),
(True, False, False, False, True));
when 'F' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, False),
(True, False, True, False, False),
(True, False, False, False, False),
(True, False, False, False, False));
when 'G' =>
Bitmap := ((False, True, True, True, False),
(True, False, False, False, True),
(True, False, True, False, True),
(True, False, True, False, True),
(False, False, True, True, False));
when 'H' =>
Bitmap := ((True, True, True, True, True),
(False, False, True, False, False),
(False, False, True, False, False),
(False, False, True, False, False),
(True, True, True, True, True));
when 'I' =>
Bitmap := ((False, False, False, False, False),
(False, False, False, False, False),
(True, True, True, True, True),
(False, False, False, False, False),
(False, False, False, False, False));
when 'J' =>
Bitmap := ((False, False, False, True, False),
(False, False, False, False, True),
(False, False, False, False, True),
(False, False, False, False, True),
(True, True, True, True, False));
when 'K' =>
Bitmap := ((True, True, True, True, True),
(False, False, True, False, False),
(False, True, False, True, False),
(True, False, False, False, True),
(False, False, False, False, False));
when 'L' =>
Bitmap := ((True, True, True, True, True),
(False, False, False, False, True),
(False, False, False, False, True),
(False, False, False, False, True),
(False, False, False, False, True));
when 'M' =>
Bitmap := ((True, True, True, True, True),
(False, True, False, False, False),
(False, False, True, False, False),
(False, True, False, False, False),
(True, True, True, True, True));
when 'N' =>
Bitmap := ((True, True, True, True, True),
(False, True, False, False, False),
(False, False, True, False, False),
(False, False, False, True, False),
(True, True, True, True, True));
when 'O' =>
Bitmap := ((False, True, True, True, False),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, False, True),
(False, True, True, True, False));
when 'P' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, False),
(True, False, True, False, False),
(True, False, True, False, False),
(False, True, False, False, False));
when 'Q' =>
Bitmap := ((False, True, True, True, False),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, True, True),
(False, True, True, True, True));
when 'R' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, False),
(True, False, True, False, False),
(True, False, True, True, False),
(False, True, False, False, True));
when 'S' =>
Bitmap := ((False, True, False, False, True),
(True, False, True, False, True),
(True, False, True, False, True),
(True, False, True, False, True),
(True, False, False, True, False));
when 'T' =>
Bitmap := ((True, False, False, False, False),
(True, False, False, False, False),
(True, True, True, True, True),
(True, False, False, False, False),
(True, False, False, False, False));
when 'U' =>
Bitmap := ((True, True, True, True, False),
(False, False, False, False, True),
(False, False, False, False, True),
(False, False, False, False, True),
(True, True, True, True, False));
when 'V' =>
Bitmap := ((True, True, False, False, False),
(False, False, True, True, False),
(False, False, False, False, True),
(False, False, True, True, False),
(True, True, False, False, False));
when 'W' =>
Bitmap := ((True, True, True, False, False),
(False, False, False, True, True),
(True, True, True, False, False),
(False, False, False, True, True),
(True, True, True, False, False));
when 'X' =>
Bitmap := ((True, False, False, False, True),
(False, True, False, True, False),
(False, False, True, False, False),
(False, True, False, True, False),
(True, False, False, False, True));
when 'Y' =>
Bitmap := ((True, False, False, False, False),
(False, True, False, False, False),
(False, False, True, True, True),
(False, True, False, False, False),
(True, False, False, False, False));
when 'Z' =>
Bitmap := ((True, False, False, False, True),
(True, False, False, True, True),
(True, False, True, False, True),
(True, True, False, False, True),
(True, False, False, False, True));
when others => null;
end case;
end Display;
begin
Initialize;
end MicroBit.Display;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with nRF51.GPIO; use nRF51.GPIO;
with nRF51.Device; use nRF51.Device;
with MicroBit.Time; use MicroBit.Time;
package body MicroBit.Display is
Bitmap : array (Coord, Coord) of Boolean := (others => (others => False));
Current_X, Current_Y : Coord := 0;
subtype Row_Range is Natural range 1 .. 3;
subtype Column_Range is Natural range 1 .. 9;
type LED_Point is record
Row_Id : Row_Range;
Column_Id : Column_Range;
end record;
Row_Points : array (Row_Range) of GPIO_Point :=
(P13, P14, P15);
Column_Points : array (Column_Range) of GPIO_Point :=
(P04, P05, P06, P07, P08, P09, P10, P11, P12);
Map : constant array (Coord, Coord) of LED_Point :=
(((1, 1), (3, 4), (2, 2), (1, 8), (3, 3)),
((2, 4), (3, 5), (1, 9), (1, 7), (2, 7)),
((1, 2), (3, 6), (2, 3), (1, 6), (3, 1)),
((2, 5), (3, 7), (3, 9), (1, 5), (2, 6)),
((1, 3), (3, 8), (2, 1), (1, 4), (3, 2))
);
procedure Initialize;
procedure Tick_Handler;
----------------
-- Initialize --
----------------
procedure Initialize is
Conf : GPIO_Configuration;
begin
Conf.Mode := Mode_Out;
Conf.Resistors := Pull_Up;
for Point of Row_Points loop
Point.Configure_IO (Conf);
Point.Clear;
end loop;
for Point of Column_Points loop
Point.Configure_IO (Conf);
Point.Set;
end loop;
if not Tick_Subscribe (Tick_Handler'Access) then
raise Program_Error;
end if;
end Initialize;
------------------
-- Tick_Handler --
------------------
procedure Tick_Handler is
begin
-- Turn Off
-- Row source current
Row_Points (Map (Current_X, Current_Y).Row_Id).Clear;
-- Column sink current
Column_Points (Map (Current_X, Current_Y).Column_Id).Set;
if Current_X = Coord'Last then
Current_X := Coord'First;
if Current_Y = Coord'Last then
Current_Y := Coord'First;
else
Current_Y := Current_Y + 1;
end if;
else
Current_X := Current_X + 1;
end if;
-- Turn on?
if Bitmap (Current_X, Current_Y) then
-- Row source current
Row_Points (Map (Current_X, Current_Y).Row_Id).Set;
-- Column sink current
Column_Points (Map (Current_X, Current_Y).Column_Id).Clear;
end if;
end Tick_Handler;
---------
-- Set --
---------
procedure Set (X, Y : Coord) is
begin
Bitmap (X, Y) := True;
end Set;
-----------
-- Clear --
-----------
procedure Clear (X, Y : Coord) is
begin
Bitmap (X, Y) := False;
end Clear;
-----------
-- Clear --
-----------
procedure Clear is
begin
Bitmap := (others => (others => False));
end Clear;
-------------
-- Display --
-------------
procedure Display (C : Character) is
begin
Clear;
case C is
when 'A' =>
Bitmap := ((False, True, True, True, True),
(True, False, True, False, False),
(True, False, True, False, False),
(True, False, True, False, False),
(False, True, True, True, True));
when 'B' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, True),
(True, False, True, False, True),
(True, False, True, False, True),
(False, True, False, True, False));
when 'C' =>
Bitmap := ((False, True, True, True, False),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, False, True));
when 'D' =>
Bitmap := ((True, True, True, True, True),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, False, True),
(False, True, True, True, False));
when 'E' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, True),
(True, False, True, False, True),
(True, False, False, False, True),
(True, False, False, False, True));
when 'F' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, False),
(True, False, True, False, False),
(True, False, False, False, False),
(True, False, False, False, False));
when 'G' =>
Bitmap := ((False, True, True, True, False),
(True, False, False, False, True),
(True, False, True, False, True),
(True, False, True, False, True),
(False, False, True, True, False));
when 'H' =>
Bitmap := ((True, True, True, True, True),
(False, False, True, False, False),
(False, False, True, False, False),
(False, False, True, False, False),
(True, True, True, True, True));
when 'I' =>
Bitmap := ((False, False, False, False, False),
(False, False, False, False, False),
(True, True, True, True, True),
(False, False, False, False, False),
(False, False, False, False, False));
when 'J' =>
Bitmap := ((False, False, False, True, False),
(False, False, False, False, True),
(False, False, False, False, True),
(False, False, False, False, True),
(True, True, True, True, False));
when 'K' =>
Bitmap := ((True, True, True, True, True),
(False, False, True, False, False),
(False, True, False, True, False),
(True, False, False, False, True),
(False, False, False, False, False));
when 'L' =>
Bitmap := ((True, True, True, True, True),
(False, False, False, False, True),
(False, False, False, False, True),
(False, False, False, False, True),
(False, False, False, False, True));
when 'M' =>
Bitmap := ((True, True, True, True, True),
(False, True, False, False, False),
(False, False, True, False, False),
(False, True, False, False, False),
(True, True, True, True, True));
when 'N' =>
Bitmap := ((True, True, True, True, True),
(False, True, False, False, False),
(False, False, True, False, False),
(False, False, False, True, False),
(True, True, True, True, True));
when 'O' =>
Bitmap := ((False, True, True, True, False),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, False, True),
(False, True, True, True, False));
when 'P' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, False),
(True, False, True, False, False),
(True, False, True, False, False),
(False, True, False, False, False));
when 'Q' =>
Bitmap := ((False, True, True, True, False),
(True, False, False, False, True),
(True, False, False, False, True),
(True, False, False, True, True),
(False, True, True, True, True));
when 'R' =>
Bitmap := ((True, True, True, True, True),
(True, False, True, False, False),
(True, False, True, False, False),
(True, False, True, True, False),
(False, True, False, False, True));
when 'S' =>
Bitmap := ((False, True, False, False, True),
(True, False, True, False, True),
(True, False, True, False, True),
(True, False, True, False, True),
(True, False, False, True, False));
when 'T' =>
Bitmap := ((True, False, False, False, False),
(True, False, False, False, False),
(True, True, True, True, True),
(True, False, False, False, False),
(True, False, False, False, False));
when 'U' =>
Bitmap := ((True, True, True, True, False),
(False, False, False, False, True),
(False, False, False, False, True),
(False, False, False, False, True),
(True, True, True, True, False));
when 'V' =>
Bitmap := ((True, True, False, False, False),
(False, False, True, True, False),
(False, False, False, False, True),
(False, False, True, True, False),
(True, True, False, False, False));
when 'W' =>
Bitmap := ((True, True, True, False, False),
(False, False, False, True, True),
(True, True, True, False, False),
(False, False, False, True, True),
(True, True, True, False, False));
when 'X' =>
Bitmap := ((True, False, False, False, True),
(False, True, False, True, False),
(False, False, True, False, False),
(False, True, False, True, False),
(True, False, False, False, True));
when 'Y' =>
Bitmap := ((True, False, False, False, False),
(False, True, False, False, False),
(False, False, True, True, True),
(False, True, False, False, False),
(True, False, False, False, False));
when 'Z' =>
Bitmap := ((True, False, False, False, True),
(True, False, False, True, True),
(True, False, True, False, True),
(True, True, False, False, True),
(True, False, False, False, True));
when others => null;
end case;
end Display;
begin
Initialize;
end MicroBit.Display;
|
Remove useless function Initialized
|
MicroBit: Remove useless function Initialized
|
Ada
|
bsd-3-clause
|
ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
2a928fec4177ace4a90e2b1192e5c0507157cbb8
|
tests/natools-s_expressions-file_rw_tests.adb
|
tests/natools-s_expressions-file_rw_tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Ada.Strings.Unbounded;
with Ada.Unchecked_Deallocation;
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.File_Writers;
with Natools.S_Expressions.Test_Tools;
with GNAT.Debug_Pools;
package body Natools.S_Expressions.File_RW_Tests is
package Stream_IO renames Ada.Streams.Stream_IO;
subtype String_Holder is Ada.Strings.Unbounded.Unbounded_String;
function Hold (S : String) return String_Holder
renames Ada.Strings.Unbounded.To_Unbounded_String;
function To_String (H : String_Holder) return String
renames Ada.Strings.Unbounded.To_String;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Atom_IO (Report);
S_Expression_IO (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Atom_IO (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Atom-based reading");
Payload : Atom (0 .. 255);
Temporary_File_Name : String_Holder;
begin
for I in Payload'Range loop
Payload (I) := Octet (I);
end loop;
Build_File :
declare
File : Stream_IO.File_Type;
begin
Stream_IO.Create (File, Stream_IO.Out_File, "");
Stream_IO.Write (File, Payload);
Temporary_File_Name := Hold (Stream_IO.Name (File));
Stream_IO.Close (File);
end Build_File;
Read_Test :
declare
Reader : File_Readers.Atom_Reader
:= File_Readers.Reader (To_String (Temporary_File_Name));
begin
Test_Tools.Test_Atom (Test, Payload, Reader.Read);
Small_Read :
declare
Buffer : Atom (1 .. 100) := (others => 0);
Length : Count;
begin
Reader.Read (Buffer, Length);
Test_Tools.Test_Atom
(Test, Payload (0 .. Buffer'Length - 1), Buffer);
if Length /= Payload'Length then
Test.Fail ("Expected total length"
& Count'Image (Payload'Length)
& " in small read, found"
& Count'Image (Length));
end if;
end Small_Read;
Large_Read :
declare
Buffer : Atom (1 .. 512) := (others => 0);
Length : Count;
begin
Reader.Read (Buffer, Length);
Test_Tools.Test_Atom
(Test, Payload, Buffer (Buffer'First .. Length));
Test_Tools.Test_Atom
(Test,
(1 .. Buffer'Length - Length => 0),
Buffer (Length + 1 .. Buffer'Last));
end Large_Read;
Reader.Set_Filename (To_String (Temporary_File_Name));
Buffer_Read :
declare
Buffer : Atom_Buffers.Atom_Buffer;
begin
Reader.Read (Buffer, 100);
Test_Tools.Test_Atom (Test, Payload, Buffer.Data);
end Buffer_Read;
Block_Read :
declare
procedure Process (Block : in Atom);
Offset : Count := 0;
procedure Process (Block : in Atom) is
Next : constant Count := Offset + Block'Length;
begin
Test_Tools.Test_Atom
(Test, Payload (Offset .. Next - 1), Block);
Offset := Next;
end Process;
begin
Reader.Block_Query (100, Process'Access);
if Offset /= Payload'Last + 1 then
Test.Fail ("Expected final offset"
& Count'Image (Payload'Last + 1)
& ", found"
& Count'Image (Offset));
end if;
Offset := 0;
Reader.Block_Query (350, Process'Access);
if Offset /= Payload'Last + 1 then
Test.Fail ("Expected second final offset"
& Count'Image (Payload'Last + 1)
& ", found"
& Count'Image (Offset));
end if;
end Block_Read;
Heap_Read :
declare
procedure Tester (Data : in Atom);
procedure Raiser (Data : in Atom);
Local_Exception : exception;
procedure Tester (Data : in Atom) is
begin
Test_Tools.Test_Atom (Test, Payload, Data);
end Tester;
procedure Raiser (Data : in Atom) is
begin
raise Local_Exception;
end Raiser;
Pool : GNAT.Debug_Pools.Debug_Pool;
type Local_Atom_Access is access Atom;
for Local_Atom_Access'Storage_Pool use Pool;
procedure Unchecked_Deallocation is new Ada.Unchecked_Deallocation
(Atom, Local_Atom_Access);
procedure Query is new File_Readers.Query
(Local_Atom_Access, Unchecked_Deallocation);
begin
Query (Reader, Tester'Access);
begin
Query (Reader, Raiser'Access);
exception
when Local_Exception => null;
end;
end Heap_Read;
end Read_Test;
exception
when Error : others => Test.Report_Exception (Error);
end Atom_IO;
procedure S_Expression_IO (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("S-expression writing and re-reading");
Temporary_File_Name, Secondary_File_Name : String_Holder;
begin
First_Write :
declare
Writer : File_Writers.Writer := File_Writers.Create ("");
begin
Temporary_File_Name := Hold (Writer.Name);
Writer.Append_Atom (To_Atom ("begin"));
Writer.Open_List;
Writer.Open_List;
Writer.Close_List;
Writer.Open_List;
Writer.Append_Atom (To_Atom ("head"));
Writer.Append_Atom (To_Atom ("tail"));
Writer.Close_List;
Writer.Close_List;
Writer.Append_Atom (To_Atom ("end"));
Writer.Create ("");
Secondary_File_Name := Hold (Writer.Name);
Writer.Open_List;
Writer.Append_Atom (To_Atom ("first"));
Writer.Append_Atom (To_Atom ("last"));
Writer.Close_List;
end First_Write;
First_Read :
declare
Reader : File_Readers.S_Reader
:= File_Readers.Reader (To_String (Temporary_File_Name));
begin
Test_Tools.Test_Atom_Accessors (Test, Reader, To_Atom ("begin"), 0);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("head"), 2);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("tail"), 2);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("end"), 0);
Test_Tools.Next_And_Check (Test, Reader, Events.End_Of_Input, 0);
Reader.Rewind;
Test_Tools.Test_Atom_Accessors (Test, Reader, To_Atom ("begin"), 0);
Reader.Set_Filename (To_String (Secondary_File_Name));
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("first"), 1);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("last"), 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Reader, Events.End_Of_Input, 0);
end First_Read;
Second_Write :
declare
Writer : File_Writers.Writer
:= File_Writers.Open (To_String (Temporary_File_Name));
begin
Writer.Open_List;
Writer.Append_Atom (To_Atom ("foo"));
Writer.Append_Atom (To_Atom ("bar"));
Writer.Open_List;
Writer.Close_List;
Writer.Close_List;
Writer.Open (To_String (Secondary_File_Name));
Writer.Open_List;
Writer.Append_Atom (To_Atom ("unfinished"));
end Second_Write;
Raw_Read :
begin
Test_Tools.Test_Atom
(Test,
To_Atom ("5:begin(()(4:head4:tail))3:end(3:foo3:bar())"),
File_Readers.Reader (To_String (Temporary_File_Name)).Read);
Test_Tools.Test_Atom
(Test,
To_Atom ("(5:first4:last)(10:unfinished"),
File_Readers.Reader (To_String (Secondary_File_Name)).Read);
end Raw_Read;
exception
when Error : others => Test.Report_Exception (Error);
end S_Expression_IO;
end Natools.S_Expressions.File_RW_Tests;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Ada.Strings.Unbounded;
with Ada.Unchecked_Deallocation;
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Atom_Refs;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.File_Writers;
with Natools.S_Expressions.Test_Tools;
with GNAT.Debug_Pools;
package body Natools.S_Expressions.File_RW_Tests is
package Stream_IO renames Ada.Streams.Stream_IO;
subtype String_Holder is Ada.Strings.Unbounded.Unbounded_String;
function Hold (S : String) return String_Holder
renames Ada.Strings.Unbounded.To_Unbounded_String;
function To_String (H : String_Holder) return String
renames Ada.Strings.Unbounded.To_String;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Atom_IO (Report);
S_Expression_IO (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Atom_IO (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Atom-based reading");
Payload : Atom (0 .. 255);
Temporary_File_Name : String_Holder;
begin
for I in Payload'Range loop
Payload (I) := Octet (I);
end loop;
Build_File :
declare
File : Stream_IO.File_Type;
begin
Stream_IO.Create (File, Stream_IO.Out_File, "");
Stream_IO.Write (File, Payload);
Temporary_File_Name := Hold (Stream_IO.Name (File));
Stream_IO.Close (File);
end Build_File;
Read_Test :
declare
Reader : File_Readers.Atom_Reader
:= File_Readers.Reader (To_String (Temporary_File_Name));
begin
Test_Tools.Test_Atom (Test, Payload, Reader.Read);
Small_Read :
declare
Buffer : Atom (1 .. 100) := (others => 0);
Length : Count;
begin
Reader.Read (Buffer, Length);
Test_Tools.Test_Atom
(Test, Payload (0 .. Buffer'Length - 1), Buffer);
if Length /= Payload'Length then
Test.Fail ("Expected total length"
& Count'Image (Payload'Length)
& " in small read, found"
& Count'Image (Length));
end if;
end Small_Read;
Large_Read :
declare
Buffer : Atom (1 .. 512) := (others => 0);
Length : Count;
begin
Reader.Read (Buffer, Length);
Test_Tools.Test_Atom
(Test, Payload, Buffer (Buffer'First .. Length));
Test_Tools.Test_Atom
(Test,
(1 .. Buffer'Length - Length => 0),
Buffer (Length + 1 .. Buffer'Last));
end Large_Read;
Reader.Set_Filename (To_String (Temporary_File_Name));
Buffer_Read :
declare
Buffer : Atom_Buffers.Atom_Buffer;
begin
Reader.Read (Buffer, 100);
Test_Tools.Test_Atom (Test, Payload, Buffer.Data);
end Buffer_Read;
Reference_Read :
declare
Buffer : Atom_Refs.Reference;
begin
Buffer := Reader.Read;
Test_Tools.Test_Atom (Test, Payload, Buffer.Query.Data.all);
end Reference_Read;
Block_Read :
declare
procedure Process (Block : in Atom);
Offset : Count := 0;
procedure Process (Block : in Atom) is
Next : constant Count := Offset + Block'Length;
begin
Test_Tools.Test_Atom
(Test, Payload (Offset .. Next - 1), Block);
Offset := Next;
end Process;
begin
Reader.Block_Query (100, Process'Access);
if Offset /= Payload'Last + 1 then
Test.Fail ("Expected final offset"
& Count'Image (Payload'Last + 1)
& ", found"
& Count'Image (Offset));
end if;
Offset := 0;
Reader.Block_Query (350, Process'Access);
if Offset /= Payload'Last + 1 then
Test.Fail ("Expected second final offset"
& Count'Image (Payload'Last + 1)
& ", found"
& Count'Image (Offset));
end if;
end Block_Read;
Heap_Read :
declare
procedure Tester (Data : in Atom);
procedure Raiser (Data : in Atom);
Local_Exception : exception;
procedure Tester (Data : in Atom) is
begin
Test_Tools.Test_Atom (Test, Payload, Data);
end Tester;
procedure Raiser (Data : in Atom) is
begin
raise Local_Exception;
end Raiser;
Pool : GNAT.Debug_Pools.Debug_Pool;
type Local_Atom_Access is access Atom;
for Local_Atom_Access'Storage_Pool use Pool;
procedure Unchecked_Deallocation is new Ada.Unchecked_Deallocation
(Atom, Local_Atom_Access);
procedure Query is new File_Readers.Query
(Local_Atom_Access, Unchecked_Deallocation);
begin
Query (Reader, Tester'Access);
begin
Query (Reader, Raiser'Access);
exception
when Local_Exception => null;
end;
end Heap_Read;
end Read_Test;
exception
when Error : others => Test.Report_Exception (Error);
end Atom_IO;
procedure S_Expression_IO (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("S-expression writing and re-reading");
Temporary_File_Name, Secondary_File_Name : String_Holder;
begin
First_Write :
declare
Writer : File_Writers.Writer := File_Writers.Create ("");
begin
Temporary_File_Name := Hold (Writer.Name);
Writer.Append_Atom (To_Atom ("begin"));
Writer.Open_List;
Writer.Open_List;
Writer.Close_List;
Writer.Open_List;
Writer.Append_Atom (To_Atom ("head"));
Writer.Append_Atom (To_Atom ("tail"));
Writer.Close_List;
Writer.Close_List;
Writer.Append_Atom (To_Atom ("end"));
Writer.Create ("");
Secondary_File_Name := Hold (Writer.Name);
Writer.Open_List;
Writer.Append_Atom (To_Atom ("first"));
Writer.Append_Atom (To_Atom ("last"));
Writer.Close_List;
end First_Write;
First_Read :
declare
Reader : File_Readers.S_Reader
:= File_Readers.Reader (To_String (Temporary_File_Name));
begin
Test_Tools.Test_Atom_Accessors (Test, Reader, To_Atom ("begin"), 0);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("head"), 2);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("tail"), 2);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("end"), 0);
Test_Tools.Next_And_Check (Test, Reader, Events.End_Of_Input, 0);
Reader.Rewind;
Test_Tools.Test_Atom_Accessors (Test, Reader, To_Atom ("begin"), 0);
Reader.Set_Filename (To_String (Secondary_File_Name));
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("first"), 1);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("last"), 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Reader, Events.End_Of_Input, 0);
end First_Read;
Second_Write :
declare
Writer : File_Writers.Writer
:= File_Writers.Open (To_String (Temporary_File_Name));
begin
Writer.Open_List;
Writer.Append_Atom (To_Atom ("foo"));
Writer.Append_Atom (To_Atom ("bar"));
Writer.Open_List;
Writer.Close_List;
Writer.Close_List;
Writer.Open (To_String (Secondary_File_Name));
Writer.Open_List;
Writer.Append_Atom (To_Atom ("unfinished"));
end Second_Write;
Raw_Read :
begin
Test_Tools.Test_Atom
(Test,
To_Atom ("5:begin(()(4:head4:tail))3:end(3:foo3:bar())"),
File_Readers.Reader (To_String (Temporary_File_Name)).Read);
Test_Tools.Test_Atom
(Test,
To_Atom ("(5:first4:last)(10:unfinished"),
File_Readers.Reader (To_String (Secondary_File_Name)).Read);
end Raw_Read;
exception
when Error : others => Test.Report_Exception (Error);
end S_Expression_IO;
end Natools.S_Expressions.File_RW_Tests;
|
test the new atom-reference reader
|
s_expressions-file_rw_tests: test the new atom-reference reader
|
Ada
|
isc
|
faelys/natools
|
1a1556b7b5eafb74823dd34ff25a68c9605ac7a4
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new ASF.Servlets.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Db_Host : Util.Beans.Objects.Object;
Db_Port : Util.Beans.Objects.Object;
Has_Error : Boolean := False;
Done : Boolean := False;
pragma Atomic (Done);
pragma Volatile (Done);
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Validate the database configuration parameters.
procedure Validate (From : in out Application);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and exit the setup.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
end AWA.Setup.Applications;
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new ASF.Servlets.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the
-- <tt>STARTING</tt> state after the application is configured and it is started.
-- Once the application is initialized and registered in the server container, the
-- state is changed to <tt>READY</tt>.
type Configure_State is (CONFIGURING, STARTING, READY);
-- Maintains the state of the configuration between the main task and the http configuration
-- requests.
protected type State is
-- Wait until the configuration is finished.
entry Wait_Configuring;
-- Wait until the server application is initialized and ready.
entry Wait_Ready;
-- Set the configuration state.
procedure Set (V : in Configure_State);
private
Value : Configure_State := CONFIGURING;
end State;
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Db_Host : Util.Beans.Objects.Object;
Db_Port : Util.Beans.Objects.Object;
Has_Error : Boolean := False;
Status : State;
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Validate the database configuration parameters.
procedure Validate (From : in out Application);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and exit the setup.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
end AWA.Setup.Applications;
|
Declare the Configure_State type and the State protected type for the configuration state management
|
Declare the Configure_State type and the State protected type for the configuration state management
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d9d1ccc18cca70b1c7074722c9f1175afc1362f4
|
src/asf-servlets-files.adb
|
src/asf-servlets-files.adb
|
-----------------------------------------------------------------------
-- asf.servlets.files -- Static file servlet
-- Copyright (C) 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 Util.Files;
with Util.Strings;
with Util.Streams;
with Util.Streams.Files;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Directories;
with ASF.Streams;
with ASF.Applications;
package body ASF.Servlets.Files is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out File_Servlet;
Context : in Servlet_Registry'Class) is
Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR);
Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default");
begin
Server.Dir := new String '(Dir);
Server.Default_Content_Type := new String '(Def_Type);
end Initialize;
-- ------------------------------
-- Returns the time the Request object was last modified, in milliseconds since
-- midnight January 1, 1970 GMT. If the time is unknown, this method returns
-- a negative number (the default).
--
-- Servlets that support HTTP GET requests and can quickly determine their
-- last modification time should override this method. This makes browser and
-- proxy caches work more effectively, reducing the load on server and network
-- resources.
-- ------------------------------
function Get_Last_Modified (Server : in File_Servlet;
Request : in Requests.Request'Class)
return Ada.Calendar.Time is
pragma Unreferenced (Server, Request);
begin
return Ada.Calendar.Clock;
end Get_Last_Modified;
-- ------------------------------
-- Set the content type associated with the given file
-- ------------------------------
procedure Set_Content_Type (Server : in File_Servlet;
Path : in String;
Response : in out Responses.Response'Class) is
Pos : constant Natural := Util.Strings.Rindex (Path, '.');
begin
if Pos = 0 then
Response.Set_Content_Type (Server.Default_Content_Type.all);
return;
end if;
if Path (Pos .. Path'Last) = ".css" then
Response.Set_Content_Type ("text/css");
return;
end if;
if Path (Pos .. Path'Last) = ".js" then
Response.Set_Content_Type ("text/javascript");
return;
end if;
if Path (Pos .. Path'Last) = ".html" then
Response.Set_Content_Type ("text/html");
return;
end if;
if Path (Pos .. Path'Last) = ".txt" then
Response.Set_Content_Type ("text/plain");
return;
end if;
if Path (Pos .. Path'Last) = ".png" then
Response.Set_Content_Type ("image/png");
return;
end if;
if Path (Pos .. Path'Last) = ".jpg" then
Response.Set_Content_Type ("image/jpg");
return;
end if;
Response.Set_Content_Type (Server.Default_Content_Type.all);
end Set_Content_Type;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
procedure Do_Get (Server : in File_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use Util.Files;
URI : constant String := Request.Get_Servlet_Path;
Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all);
begin
if Path'Length = 0 or else not Ada.Directories.Exists (Path)
or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File
then
Response.Send_Error (Responses.SC_NOT_FOUND);
return;
end if;
File_Servlet'Class (Server).Set_Content_Type (Path, Response);
declare
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
Input : Util.Streams.Files.File_Stream;
begin
Input.Open (Name => Path, Mode => In_File);
Util.Streams.Copy (From => Input, Into => Output);
end;
end Do_Get;
end ASF.Servlets.Files;
|
-----------------------------------------------------------------------
-- asf.servlets.files -- Static file servlet
-- Copyright (C) 2010, 2011, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Files;
with Util.Log.Loggers;
with Util.Strings;
with Util.Streams;
with Util.Streams.Files;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Directories;
with ASF.Streams;
with ASF.Applications;
package body ASF.Servlets.Files is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Servlets.Files");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out File_Servlet;
Context : in Servlet_Registry'Class) is
Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR);
Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default");
begin
if Dir = "" then
Server.Dir := new String '("./");
else
Server.Dir := new String '(Dir);
end if;
Server.Default_Content_Type := new String '(Def_Type);
Log.Info ("File servlet using directory '{0}'", Server.Dir.all);
end Initialize;
-- ------------------------------
-- Returns the time the Request object was last modified, in milliseconds since
-- midnight January 1, 1970 GMT. If the time is unknown, this method returns
-- a negative number (the default).
--
-- Servlets that support HTTP GET requests and can quickly determine their
-- last modification time should override this method. This makes browser and
-- proxy caches work more effectively, reducing the load on server and network
-- resources.
-- ------------------------------
function Get_Last_Modified (Server : in File_Servlet;
Request : in Requests.Request'Class)
return Ada.Calendar.Time is
pragma Unreferenced (Server, Request);
begin
return Ada.Calendar.Clock;
end Get_Last_Modified;
-- ------------------------------
-- Set the content type associated with the given file
-- ------------------------------
procedure Set_Content_Type (Server : in File_Servlet;
Path : in String;
Response : in out Responses.Response'Class) is
Pos : constant Natural := Util.Strings.Rindex (Path, '.');
begin
if Pos = 0 then
Response.Set_Content_Type (Server.Default_Content_Type.all);
return;
end if;
if Path (Pos .. Path'Last) = ".css" then
Response.Set_Content_Type ("text/css");
return;
end if;
if Path (Pos .. Path'Last) = ".js" then
Response.Set_Content_Type ("text/javascript");
return;
end if;
if Path (Pos .. Path'Last) = ".html" then
Response.Set_Content_Type ("text/html");
return;
end if;
if Path (Pos .. Path'Last) = ".txt" then
Response.Set_Content_Type ("text/plain");
return;
end if;
if Path (Pos .. Path'Last) = ".png" then
Response.Set_Content_Type ("image/png");
return;
end if;
if Path (Pos .. Path'Last) = ".jpg" then
Response.Set_Content_Type ("image/jpg");
return;
end if;
Response.Set_Content_Type (Server.Default_Content_Type.all);
end Set_Content_Type;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
procedure Do_Get (Server : in File_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use Util.Files;
URI : constant String := Request.Get_Servlet_Path;
Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all);
begin
if Path'Length = 0 or else not Ada.Directories.Exists (Path)
or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File
then
Log.Debug ("Servlet file cannot read file {0}", Path);
Response.Send_Error (Responses.SC_NOT_FOUND);
return;
end if;
File_Servlet'Class (Server).Set_Content_Type (Path, Response);
declare
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
Input : Util.Streams.Files.File_Stream;
begin
Input.Open (Name => Path, Mode => In_File);
Util.Streams.Copy (From => Input, Into => Output);
end;
end Do_Get;
end ASF.Servlets.Files;
|
Add a log message to track the configuration issue Use default directory "." when nothing is provided Emit a log debug message when a file cannot be found
|
Add a log message to track the configuration issue
Use default directory "." when nothing is provided
Emit a log debug message when a file cannot be found
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
774c3a7c2f393d9e504f5993f4ef7cf1ff6d7d31
|
src/asf-views-facelets.adb
|
src/asf-views-facelets.adb
|
-----------------------------------------------------------------------
-- asf-views-facelets -- Facelets representation and management
-- Copyright (C) 2009, 2010, 2011, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ASF.Views.Nodes.Reader;
with Input_Sources.File;
with Sax.Readers;
with EL.Contexts.Default;
with Util.Files;
with Util.Log.Loggers;
package body ASF.Views.Facelets is
use ASF.Views.Nodes;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets");
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info,
Name => ASF.Views.File_Info_Access);
-- Find in the factory for the facelet with the given name.
procedure Find (Factory : in out Facelet_Factory;
Name : in Unbounded_String;
Result : out Facelet);
-- Load the facelet node tree by reading the facelet XHTML file.
procedure Load (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet);
-- Update the factory to store the facelet node tree
procedure Update (Factory : in out Facelet_Factory;
Name : in Unbounded_String;
Item : in Facelet);
-- ------------------------------
-- Returns True if the facelet is null/empty.
-- ------------------------------
function Is_Null (F : Facelet) return Boolean is
begin
return F.Root = null;
end Is_Null;
-- ------------------------------
-- Get the facelet identified by the given name. If the facelet is already
-- loaded, the cached value is returned. The facelet file is searched in
-- a set of directories configured in the facelet factory.
-- ------------------------------
procedure Find_Facelet (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet) is
Res : Facelet;
Fname : constant Unbounded_String := To_Unbounded_String (Name);
begin
Log.Debug ("Find facelet {0}", Name);
Find (Factory, Fname, Res);
if Res.Root = null then
Load (Factory, Name, Context, Res);
if Res.Root = null then
Result.Root := null;
return;
end if;
Update (Factory, Fname, Res);
end if;
Result.Root := Res.Root;
Result.File := Res.File;
end Find_Facelet;
-- ------------------------------
-- Create the component tree from the facelet view.
-- ------------------------------
procedure Build_View (View : in Facelet;
Context : in out ASF.Contexts.Facelets.Facelet_Context'Class;
Root : in ASF.Components.Base.UIComponent_Access) is
Old : Unbounded_String;
begin
if View.Root /= null then
Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.File.all),
Previous => Old);
View.Root.Build_Children (Parent => Root, Context => Context);
Context.Set_Relative_Path (Path => Old);
end if;
end Build_View;
-- ------------------------------
-- Initialize the facelet factory.
-- Set the search directories for facelet files.
-- Set the ignore white space configuration when reading XHTML files.
-- Set the ignore empty lines configuration when reading XHTML files.
-- Set the escape unknown tags configuration when reading XHTML files.
-- ------------------------------
procedure Initialize (Factory : in out Facelet_Factory;
Components : access ASF.Factory.Component_Factory;
Paths : in String;
Ignore_White_Spaces : in Boolean;
Ignore_Empty_Lines : in Boolean;
Escape_Unknown_Tags : in Boolean) is
begin
Log.Info ("Set facelet search directory to: '{0}'", Paths);
Factory.Factory := Components;
Factory.Paths := To_Unbounded_String (Paths);
Factory.Ignore_White_Spaces := Ignore_White_Spaces;
Factory.Ignore_Empty_Lines := Ignore_Empty_Lines;
Factory.Escape_Unknown_Tags := Escape_Unknown_Tags;
end Initialize;
-- ------------------------------
-- Find the facelet file in one of the facelet directories.
-- Returns the path to be used for reading the facelet file.
-- ------------------------------
function Find_Facelet_Path (Factory : Facelet_Factory;
Name : String) return String is
begin
return Util.Files.Find_File_Path (Name, To_String (Factory.Paths));
end Find_Facelet_Path;
-- ------------------------------
-- Find in the factory for the facelet with the given name.
-- ------------------------------
procedure Find (Factory : in out Facelet_Factory;
Name : in Unbounded_String;
Result : out Facelet) is
use Ada.Directories;
use Ada.Calendar;
begin
Result.Root := null;
Result := Factory.Map.Find (Name);
if Result.Root /= null and then
Modification_Time (Result.File.Path) > Result.Modify_Time
then
Result.Root := null;
Log.Info ("Ignoring cache because file '{0}' was modified",
Result.File.Path);
end if;
end Find;
-- ------------------------------
-- Load the facelet node tree by reading the facelet XHTML file.
-- ------------------------------
procedure Load (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet) is
Path : constant String := Find_Facelet_Path (Factory, Name);
begin
if not Ada.Directories.Exists (Path) then
Log.Warn ("Cannot read '{0}': file does not exist", Path);
Result.Root := null;
return;
end if;
declare
RPos : constant Natural := Path'Length - Name'Length + 1;
File : File_Info_Access := Create_File_Info (Path, RPos);
Reader : ASF.Views.Nodes.Reader.Xhtml_Reader;
Read : Input_Sources.File.File_Input;
Mtime : Ada.Calendar.Time;
Ctx : aliased EL.Contexts.Default.Default_Context;
begin
Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name,
Natural'Image (File.Relative_Pos));
Ctx.Set_Function_Mapper (Context.Get_Function_Mapper);
Mtime := Ada.Directories.Modification_Time (Path);
Input_Sources.File.Open (Path, Read);
-- If True, xmlns:* attributes will be reported in Start_Element
Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False);
Reader.Set_Feature (Sax.Readers.Validation_Feature, False);
Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces);
Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags);
Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines);
begin
Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access);
exception
when ASF.Views.Nodes.Reader.Parsing_Error =>
Free (File);
when E : others =>
Free (File);
Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path,
Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E));
end;
Result.Root := Reader.Get_Root;
Result.File := File;
if File = null then
if Result.Root /= null then
Result.Root.Delete;
end if;
Result.Root := null;
else
Result.Modify_Time := Mtime;
end if;
Input_Sources.File.Close (Read);
end;
end Load;
-- ------------------------------
-- Update the factory to store the facelet node tree
-- ------------------------------
procedure Update (Factory : in out Facelet_Factory;
Name : in Unbounded_String;
Item : in Facelet) is
begin
Factory.Map.Insert (Name, Item);
end Update;
-- ------------------------------
-- Clear the facelet cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Facelet_Factory) is
begin
Log.Info ("Clearing facelet cache");
Factory.Map.Clear;
end Clear_Cache;
protected body Facelet_Cache is
-- ------------------------------
-- Find the facelet entry associated with the given name.
-- ------------------------------
function Find (Name : in Unbounded_String) return Facelet is
Pos : constant Facelet_Maps.Cursor := Map.Find (Name);
begin
if Facelet_Maps.Has_Element (Pos) then
return Element (Pos);
else
return Result : Facelet;
end if;
end Find;
-- ------------------------------
-- Insert or replace the facelet entry associated with the given name.
-- ------------------------------
procedure Insert (Name : in Unbounded_String;
Item : in Facelet) is
begin
Map.Include (Name, Item);
end Insert;
-- ------------------------------
-- Clear the cache.
-- ------------------------------
procedure Clear is
begin
loop
declare
Pos : Facelet_Maps.Cursor := Map.First;
Node : Facelet;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Map.Delete (Pos);
Free (Node.File);
ASF.Views.Nodes.Destroy (Node.Root);
end;
end loop;
end Clear;
end Facelet_Cache;
-- ------------------------------
-- Free the storage held by the factory cache.
-- ------------------------------
overriding
procedure Finalize (Factory : in out Facelet_Factory) is
begin
Factory.Clear_Cache;
end Finalize;
end ASF.Views.Facelets;
|
-----------------------------------------------------------------------
-- asf-views-facelets -- Facelets representation and management
-- Copyright (C) 2009, 2010, 2011, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with ASF.Views.Nodes.Reader;
with Input_Sources.File;
with Sax.Readers;
with EL.Contexts.Default;
with Util.Files;
with Util.Log.Loggers;
package body ASF.Views.Facelets is
use ASF.Views.Nodes;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets");
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info,
Name => ASF.Views.File_Info_Access);
-- Find in the factory for the facelet with the given name.
procedure Find (Factory : in out Facelet_Factory;
Name : in Unbounded_String;
Result : out Facelet);
-- Load the facelet node tree by reading the facelet XHTML file.
procedure Load (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet);
-- Update the factory to store the facelet node tree
procedure Update (Factory : in out Facelet_Factory;
Name : in Unbounded_String;
Item : in Facelet);
-- ------------------------------
-- Returns True if the facelet is null/empty.
-- ------------------------------
function Is_Null (F : Facelet) return Boolean is
begin
return F.Root = null;
end Is_Null;
-- ------------------------------
-- Get the facelet identified by the given name. If the facelet is already
-- loaded, the cached value is returned. The facelet file is searched in
-- a set of directories configured in the facelet factory.
-- ------------------------------
procedure Find_Facelet (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet) is
Res : Facelet;
Fname : constant Unbounded_String := To_Unbounded_String (Name);
begin
Log.Debug ("Find facelet {0}", Name);
Find (Factory, Fname, Res);
if Res.Root = null then
Load (Factory, Name, Context, Res);
if Res.Root = null then
Result.Root := null;
return;
end if;
Update (Factory, Fname, Res);
end if;
Result.Root := Res.Root;
Result.File := Res.File;
end Find_Facelet;
-- ------------------------------
-- Create the component tree from the facelet view.
-- ------------------------------
procedure Build_View (View : in Facelet;
Context : in out ASF.Contexts.Facelets.Facelet_Context'Class;
Root : in ASF.Components.Base.UIComponent_Access) is
Old : Unbounded_String;
begin
if View.Root /= null then
Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.File.all),
Previous => Old);
View.Root.Build_Children (Parent => Root, Context => Context);
Context.Set_Relative_Path (Path => Old);
end if;
end Build_View;
-- ------------------------------
-- Initialize the facelet factory.
-- Set the search directories for facelet files.
-- Set the ignore white space configuration when reading XHTML files.
-- Set the ignore empty lines configuration when reading XHTML files.
-- Set the escape unknown tags configuration when reading XHTML files.
-- ------------------------------
procedure Initialize (Factory : in out Facelet_Factory;
Components : access ASF.Factory.Component_Factory;
Paths : in String;
Ignore_White_Spaces : in Boolean;
Ignore_Empty_Lines : in Boolean;
Escape_Unknown_Tags : in Boolean) is
begin
Log.Info ("Set facelet search directory to: '{0}'", Paths);
Factory.Factory := Components;
Factory.Paths := To_Unbounded_String (Paths);
Factory.Ignore_White_Spaces := Ignore_White_Spaces;
Factory.Ignore_Empty_Lines := Ignore_Empty_Lines;
Factory.Escape_Unknown_Tags := Escape_Unknown_Tags;
end Initialize;
-- ------------------------------
-- Find the facelet file in one of the facelet directories.
-- Returns the path to be used for reading the facelet file.
-- ------------------------------
function Find_Facelet_Path (Factory : Facelet_Factory;
Name : String) return String is
begin
return Util.Files.Find_File_Path (Name, To_String (Factory.Paths));
end Find_Facelet_Path;
-- ------------------------------
-- Find in the factory for the facelet with the given name.
-- ------------------------------
procedure Find (Factory : in out Facelet_Factory;
Name : in Unbounded_String;
Result : out Facelet) is
use Ada.Directories;
use Ada.Calendar;
begin
Result.Root := null;
Result := Factory.Map.Find (Name);
if Result.Root /= null and then
Modification_Time (Result.File.Path) > Result.Modify_Time
then
Result.Root := null;
Log.Info ("Ignoring cache because file '{0}' was modified",
Result.File.Path);
end if;
end Find;
-- ------------------------------
-- Load the facelet node tree by reading the facelet XHTML file.
-- ------------------------------
procedure Load (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet) is
Path : constant String := Find_Facelet_Path (Factory, Name);
begin
if not Ada.Directories.Exists (Path) then
Log.Warn ("Cannot read '{0}': file does not exist", Path);
Result.Root := null;
return;
end if;
declare
RPos : constant Natural := Path'Length - Name'Length + 1;
File : File_Info_Access := Create_File_Info (Path, RPos);
Reader : ASF.Views.Nodes.Reader.Xhtml_Reader;
Read : Input_Sources.File.File_Input;
Mtime : Ada.Calendar.Time;
Ctx : aliased EL.Contexts.Default.Default_Context;
begin
Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name,
Natural'Image (File.Relative_Pos));
Ctx.Set_Function_Mapper (Context.Get_Function_Mapper);
Mtime := Ada.Directories.Modification_Time (Path);
Input_Sources.File.Open (Path, Read);
-- If True, xmlns:* attributes will be reported in Start_Element
Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False);
Reader.Set_Feature (Sax.Readers.Validation_Feature, False);
Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces);
Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags);
Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines);
begin
Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access);
exception
when ASF.Views.Nodes.Reader.Parsing_Error =>
Free (File);
when E : others =>
Free (File);
Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path,
Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E));
end;
Result.Root := Reader.Get_Root;
Result.File := File;
if File = null then
if Result.Root /= null then
Result.Root.Delete;
end if;
Result.Root := null;
else
Result.Modify_Time := Mtime;
end if;
Input_Sources.File.Close (Read);
end;
end Load;
-- ------------------------------
-- Update the factory to store the facelet node tree
-- ------------------------------
procedure Update (Factory : in out Facelet_Factory;
Name : in Unbounded_String;
Item : in Facelet) is
begin
Factory.Map.Insert (Name, Item);
end Update;
-- ------------------------------
-- Clear the facelet cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Facelet_Factory) is
begin
Log.Info ("Clearing facelet cache");
Factory.Map.Clear;
end Clear_Cache;
protected body Facelet_Cache is
-- ------------------------------
-- Find the facelet entry associated with the given name.
-- ------------------------------
function Find (Name : in Unbounded_String) return Facelet is
Pos : constant Facelet_Maps.Cursor := Map.Find (Name);
begin
if Facelet_Maps.Has_Element (Pos) then
return Element (Pos);
else
return Empty;
end if;
end Find;
-- ------------------------------
-- Insert or replace the facelet entry associated with the given name.
-- ------------------------------
procedure Insert (Name : in Unbounded_String;
Item : in Facelet) is
begin
Map.Include (Name, Item);
end Insert;
-- ------------------------------
-- Clear the cache.
-- ------------------------------
procedure Clear is
begin
loop
declare
Pos : Facelet_Maps.Cursor := Map.First;
Node : Facelet;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Map.Delete (Pos);
Free (Node.File);
ASF.Views.Nodes.Destroy (Node.Root);
end;
end loop;
end Clear;
end Facelet_Cache;
-- ------------------------------
-- Free the storage held by the factory cache.
-- ------------------------------
overriding
procedure Finalize (Factory : in out Facelet_Factory) is
begin
Factory.Clear_Cache;
end Finalize;
end ASF.Views.Facelets;
|
Update Find function to return the Empty facelet instance
|
Update Find function to return the Empty facelet instance
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
53e310e1af5b6040ab5ed3b908362d967bf38180
|
src/orka/implementation/orka-rendering-framebuffers.adb
|
src/orka/implementation/orka-rendering-framebuffers.adb
|
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Pixels;
with GL.Window;
with Orka.Containers.Bounded_Vectors;
package body Orka.Rendering.Framebuffers is
package Attachment_Vectors is new Containers.Bounded_Vectors (Positive, FB.Attachment_Point);
function Create_Framebuffer
(Width, Height, Samples : Size) return Framebuffer is
begin
return Result : Framebuffer
(Default => False,
Width => Width,
Height => Height,
Samples => Samples)
do
Result.GL_Framebuffer.Set_Default_Width (Width);
Result.GL_Framebuffer.Set_Default_Height (Height);
Result.GL_Framebuffer.Set_Default_Samples (Samples);
Result.Set_Draw_Buffers ((0 => GL.Buffers.Color_Attachment0));
end return;
end Create_Framebuffer;
function Create_Framebuffer
(Width, Height, Samples : Size;
Context : Contexts.Context) return Framebuffer
is (Create_Framebuffer (Width, Height, Samples => Samples));
function Create_Framebuffer
(Width, Height : Size) return Framebuffer
is (Create_Framebuffer (Width, Height, Samples => 0));
-----------------------------------------------------------------------------
function Get_Default_Framebuffer
(Window : Orka.Windows.Window'Class) return Framebuffer
is (Create_Default_Framebuffer (Size (Window.Width), Size (Window.Height)));
-- TODO Or store a Window_Ptr so we can adjust viewport when window gets resized?
function Create_Default_Framebuffer
(Width, Height : Size) return Framebuffer is
begin
return Result : Framebuffer :=
(Default => True,
Width => Width,
Height => Height,
Samples => 0,
GL_Framebuffer => GL.Objects.Framebuffers.Default_Framebuffer,
others => <>)
do
-- Assumes a double-buffered context (Front_Left for single-buffered)
Result.Set_Draw_Buffers ((0 => GL.Buffers.Back_Left));
end return;
end Create_Default_Framebuffer;
-----------------------------------------------------------------------------
function GL_Framebuffer (Object : Framebuffer) return GL.Objects.Framebuffers.Framebuffer
is (Object.GL_Framebuffer);
-----------------------------------------------------------------------------
procedure Use_Framebuffer (Object : Framebuffer) is
use GL.Objects.Framebuffers;
begin
GL.Objects.Framebuffers.Draw_Target.Bind (Object.GL_Framebuffer);
-- Adjust viewport
GL.Window.Set_Viewports
((0 => (X => 0.0,
Y => 0.0,
Width => Single (Object.Width),
Height => Single (Object.Height))
));
-- Check attachments
if not Object.Default then
declare
Status : constant Framebuffer_Status := Object.GL_Framebuffer.Status (Draw_Target);
begin
if Status /= Complete then
raise Framebuffer_Incomplete_Error with Status'Image;
end if;
end;
end if;
end Use_Framebuffer;
procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values) is
begin
Object.Defaults := Values;
end Set_Default_Values;
function Default_Values (Object : Framebuffer) return Buffer_Values is (Object.Defaults);
procedure Set_Read_Buffer
(Object : Framebuffer;
Buffer : GL.Buffers.Color_Buffer_Selector) is
begin
Object.GL_Framebuffer.Set_Read_Buffer (Buffer);
end Set_Read_Buffer;
procedure Set_Draw_Buffers
(Object : in out Framebuffer;
Buffers : GL.Buffers.Color_Buffer_List) is
begin
Object.GL_Framebuffer.Set_Draw_Buffers (Buffers);
Object.Draw_Buffers.Replace_Element (Buffers);
end Set_Draw_Buffers;
procedure Clear
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (others => True))
is
Depth_Stencil : constant Boolean := Object.Has_Attachment (FB.Depth_Stencil_Attachment);
Depth : constant Boolean := Object.Has_Attachment (FB.Depth_Attachment);
Stencil : constant Boolean := Object.Has_Attachment (FB.Stencil_Attachment);
begin
if Mask.Depth or Mask.Stencil then
if Mask.Depth and Mask.Stencil and Depth_Stencil then
-- This procedure is used because it may be faster for
-- combined depth/stencil textures
Object.GL_Framebuffer.Clear_Depth_And_Stencil_Buffer
(Depth_Value => Object.Defaults.Depth,
Stencil_Value => Object.Defaults.Stencil);
else
if Mask.Depth and (Depth_Stencil or Depth) then
Object.GL_Framebuffer.Clear_Depth_Buffer (Object.Defaults.Depth);
end if;
if Mask.Stencil and (Depth_Stencil or Stencil) then
Object.GL_Framebuffer.Clear_Stencil_Buffer (Object.Defaults.Stencil);
end if;
end if;
end if;
if Mask.Color then
declare
procedure Clear_Attachments (List : GL.Buffers.Color_Buffer_List) is
use all type GL.Buffers.Color_Buffer_Selector;
Index : GL.Buffers.Draw_Buffer_Index := GL.Buffers.Draw_Buffer_Index'First;
Data_Type : GL.Pixels.Channel_Data_Type;
begin
for Buffer of List loop
if Buffer /= None then
if Object.Default then
Data_Type := GL.Pixels.Float_Type;
else
Data_Type := Object.Attachments (Color_Attachment_Point'Val
(GL.Buffers.Color_Buffer_Selector'Pos (Buffer)
- GL.Buffers.Color_Buffer_Selector'Pos (GL.Buffers.Color_Attachment0)
+ Color_Attachment_Point'Pos (Color_Attachment_Point'First)
)).Element.Red_Type;
end if;
Object.GL_Framebuffer.Clear_Color_Buffer
(Index, Data_Type, Object.Defaults.Color);
end if;
Index := Index + 1;
end loop;
end Clear_Attachments;
begin
Object.Draw_Buffers.Query_Element (Clear_Attachments'Access);
end;
end if;
end Clear;
procedure Invalidate
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits)
is
Attachments : Attachment_Vectors.Vector (Capacity => Attachment_Array'Length);
Depth_Stencil : constant Boolean := Object.Has_Attachment (FB.Depth_Stencil_Attachment);
Depth : constant Boolean := Object.Has_Attachment (FB.Depth_Attachment);
Stencil : constant Boolean := Object.Has_Attachment (FB.Stencil_Attachment);
procedure Invalidate_Attachments (Elements : Attachment_Vectors.Element_Array) is
begin
Object.GL_Framebuffer.Invalidate_Data (FB.Attachment_List (Elements));
end Invalidate_Attachments;
begin
if Mask.Depth or Mask.Stencil then
if Mask.Depth and Mask.Stencil and Depth_Stencil then
Attachments.Append (FB.Depth_Stencil_Attachment);
else
if Mask.Depth and (Depth_Stencil or Depth) then
Attachments.Append (FB.Depth_Attachment);
end if;
if Mask.Stencil and (Depth_Stencil or Stencil) then
Attachments.Append (FB.Stencil_Attachment);
end if;
end if;
end if;
if Mask.Color then
for Attachment in Color_Attachment_Point loop
if Object.Has_Attachment (Attachment) then
Attachments.Append (Attachment);
end if;
end loop;
end if;
Attachments.Query (Invalidate_Attachments'Access);
end Invalidate;
procedure Resolve_To
(Object, Subject : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False)) is
begin
FB.Blit
(Object.GL_Framebuffer, Subject.GL_Framebuffer,
0, 0, Object.Width, Object.Height,
0, 0, Subject.Width, Subject.Height,
Mask, GL.Objects.Textures.Nearest);
end Resolve_To;
procedure Attach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0;
Layer : Natural := 0) is
begin
if not Texture.Layered then
Object.GL_Framebuffer.Attach_Texture (Attachment, Texture, Level);
else
Object.GL_Framebuffer.Attach_Texture_Layer (Attachment, Texture, Level, Layer => Layer);
end if;
Object.Attachments (Attachment) := Attachment_Holder.To_Holder (Texture);
end Attach;
procedure Attach
(Object : in out Framebuffer;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0;
Layer : Natural := 0)
is
use all type GL.Pixels.Internal_Format;
begin
case Texture.Internal_Format is
when Depth24_Stencil8 | Depth32F_Stencil8 =>
Object.Attach (FB.Depth_Stencil_Attachment, Texture, Level, Layer);
when Depth_Component16 | Depth_Component24 | Depth_Component32F =>
Object.Attach (FB.Depth_Attachment, Texture, Level, Layer);
when Stencil_Index8 =>
Object.Attach (FB.Stencil_Attachment, Texture, Level, Layer);
when others =>
Object.Attach (FB.Color_Attachment_0, Texture, Level, Layer);
end case;
end Attach;
procedure Detach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point) is
begin
Object.GL_Framebuffer.Detach (Attachment);
Object.Attachments (Attachment).Clear;
end Detach;
function Has_Attachment
(Object : Framebuffer;
Attachment : FB.Attachment_Point) return Boolean
is (not Object.Attachments (Attachment).Is_Empty);
end Orka.Rendering.Framebuffers;
|
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Pixels;
with GL.Window;
with Orka.Containers.Bounded_Vectors;
package body Orka.Rendering.Framebuffers is
package Attachment_Vectors is new Containers.Bounded_Vectors (Positive, FB.Attachment_Point);
function Create_Framebuffer
(Width, Height, Samples : Size) return Framebuffer is
begin
return Result : Framebuffer
(Default => False,
Width => Width,
Height => Height,
Samples => Samples)
do
Result.GL_Framebuffer.Set_Default_Width (Width);
Result.GL_Framebuffer.Set_Default_Height (Height);
Result.GL_Framebuffer.Set_Default_Samples (Samples);
Result.Set_Draw_Buffers ((0 => GL.Buffers.Color_Attachment0));
end return;
end Create_Framebuffer;
function Create_Framebuffer
(Width, Height, Samples : Size;
Context : Contexts.Context) return Framebuffer
is (Create_Framebuffer (Width, Height, Samples => Samples));
function Create_Framebuffer
(Width, Height : Size) return Framebuffer
is (Create_Framebuffer (Width, Height, Samples => 0));
-----------------------------------------------------------------------------
function Get_Default_Framebuffer
(Window : Orka.Windows.Window'Class) return Framebuffer
is (Create_Default_Framebuffer (Size (Window.Width), Size (Window.Height)));
-- TODO Or store a Window_Ptr so we can adjust viewport when window gets resized?
function Create_Default_Framebuffer
(Width, Height : Size) return Framebuffer is
begin
return Result : Framebuffer :=
(Default => True,
Width => Width,
Height => Height,
Samples => 0,
GL_Framebuffer => GL.Objects.Framebuffers.Default_Framebuffer,
others => <>)
do
-- Assumes a double-buffered context (Front_Left for single-buffered)
Result.Set_Draw_Buffers ((0 => GL.Buffers.Back_Left));
end return;
end Create_Default_Framebuffer;
-----------------------------------------------------------------------------
function GL_Framebuffer (Object : Framebuffer) return GL.Objects.Framebuffers.Framebuffer
is (Object.GL_Framebuffer);
-----------------------------------------------------------------------------
procedure Use_Framebuffer (Object : Framebuffer) is
use GL.Objects.Framebuffers;
begin
GL.Objects.Framebuffers.Draw_Target.Bind (Object.GL_Framebuffer);
-- Adjust viewport
GL.Window.Set_Viewports
((0 => (X => 0.0,
Y => 0.0,
Width => Single (Object.Width),
Height => Single (Object.Height))
));
-- Check attachments
if not Object.Default then
declare
Status : constant Framebuffer_Status := Object.GL_Framebuffer.Status (Draw_Target);
begin
if Status /= Complete then
raise Framebuffer_Incomplete_Error with Status'Image;
end if;
end;
end if;
end Use_Framebuffer;
procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values) is
begin
Object.Defaults := Values;
end Set_Default_Values;
function Default_Values (Object : Framebuffer) return Buffer_Values is (Object.Defaults);
procedure Set_Read_Buffer
(Object : Framebuffer;
Buffer : GL.Buffers.Color_Buffer_Selector) is
begin
Object.GL_Framebuffer.Set_Read_Buffer (Buffer);
end Set_Read_Buffer;
procedure Set_Draw_Buffers
(Object : in out Framebuffer;
Buffers : GL.Buffers.Color_Buffer_List) is
begin
Object.GL_Framebuffer.Set_Draw_Buffers (Buffers);
Object.Draw_Buffers.Replace_Element (Buffers);
end Set_Draw_Buffers;
procedure Clear
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (others => True))
is
Depth_Stencil : constant Boolean := Object.Has_Attachment (FB.Depth_Stencil_Attachment);
Depth : constant Boolean := Object.Has_Attachment (FB.Depth_Attachment);
Stencil : constant Boolean := Object.Has_Attachment (FB.Stencil_Attachment);
begin
if Mask.Depth or Mask.Stencil then
if Mask.Depth and Mask.Stencil and Depth_Stencil then
-- This procedure is used because it may be faster for
-- combined depth/stencil textures
Object.GL_Framebuffer.Clear_Depth_And_Stencil_Buffer
(Depth_Value => Object.Defaults.Depth,
Stencil_Value => Object.Defaults.Stencil);
else
if Mask.Depth and (Depth_Stencil or Depth) then
Object.GL_Framebuffer.Clear_Depth_Buffer (Object.Defaults.Depth);
end if;
if Mask.Stencil and (Depth_Stencil or Stencil) then
Object.GL_Framebuffer.Clear_Stencil_Buffer (Object.Defaults.Stencil);
end if;
end if;
end if;
if Mask.Color then
declare
procedure Clear_Attachments (List : GL.Buffers.Color_Buffer_List) is
use all type GL.Buffers.Color_Buffer_Selector;
Index : GL.Buffers.Draw_Buffer_Index := GL.Buffers.Draw_Buffer_Index'First;
begin
for Buffer of List loop
if Buffer /= None then
if Object.Default then
Object.GL_Framebuffer.Clear_Color_Buffer
(Index, GL.Pixels.Float_Type, Object.Defaults.Color);
else
declare
Point : constant FB.Attachment_Point := Color_Attachment_Point'Val
(GL.Buffers.Color_Buffer_Selector'Pos (Buffer)
- GL.Buffers.Color_Buffer_Selector'Pos (GL.Buffers.Color_Attachment0)
+ Color_Attachment_Point'Pos (Color_Attachment_Point'First));
begin
if Object.Has_Attachment (Point) then
Object.GL_Framebuffer.Clear_Color_Buffer
(Index, Object.Attachments (Point).Element.Red_Type,
Object.Defaults.Color);
end if;
end;
end if;
end if;
Index := Index + 1;
end loop;
end Clear_Attachments;
begin
Object.Draw_Buffers.Query_Element (Clear_Attachments'Access);
end;
end if;
end Clear;
procedure Invalidate
(Object : Framebuffer;
Mask : GL.Buffers.Buffer_Bits)
is
Attachments : Attachment_Vectors.Vector (Capacity => Attachment_Array'Length);
Depth_Stencil : constant Boolean := Object.Has_Attachment (FB.Depth_Stencil_Attachment);
Depth : constant Boolean := Object.Has_Attachment (FB.Depth_Attachment);
Stencil : constant Boolean := Object.Has_Attachment (FB.Stencil_Attachment);
procedure Invalidate_Attachments (Elements : Attachment_Vectors.Element_Array) is
begin
Object.GL_Framebuffer.Invalidate_Data (FB.Attachment_List (Elements));
end Invalidate_Attachments;
begin
if Mask.Depth or Mask.Stencil then
if Mask.Depth and Mask.Stencil and Depth_Stencil then
Attachments.Append (FB.Depth_Stencil_Attachment);
else
if Mask.Depth and (Depth_Stencil or Depth) then
Attachments.Append (FB.Depth_Attachment);
end if;
if Mask.Stencil and (Depth_Stencil or Stencil) then
Attachments.Append (FB.Stencil_Attachment);
end if;
end if;
end if;
if Mask.Color then
for Attachment in Color_Attachment_Point loop
if Object.Has_Attachment (Attachment) then
Attachments.Append (Attachment);
end if;
end loop;
end if;
Attachments.Query (Invalidate_Attachments'Access);
end Invalidate;
procedure Resolve_To
(Object, Subject : Framebuffer;
Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False)) is
begin
FB.Blit
(Object.GL_Framebuffer, Subject.GL_Framebuffer,
0, 0, Object.Width, Object.Height,
0, 0, Subject.Width, Subject.Height,
Mask, GL.Objects.Textures.Nearest);
end Resolve_To;
procedure Attach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0;
Layer : Natural := 0) is
begin
if not Texture.Layered then
Object.GL_Framebuffer.Attach_Texture (Attachment, Texture, Level);
else
Object.GL_Framebuffer.Attach_Texture_Layer (Attachment, Texture, Level, Layer => Layer);
end if;
Object.Attachments (Attachment) := Attachment_Holder.To_Holder (Texture);
end Attach;
procedure Attach
(Object : in out Framebuffer;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level := 0;
Layer : Natural := 0)
is
use all type GL.Pixels.Internal_Format;
begin
case Texture.Internal_Format is
when Depth24_Stencil8 | Depth32F_Stencil8 =>
Object.Attach (FB.Depth_Stencil_Attachment, Texture, Level, Layer);
when Depth_Component16 | Depth_Component24 | Depth_Component32F =>
Object.Attach (FB.Depth_Attachment, Texture, Level, Layer);
when Stencil_Index8 =>
Object.Attach (FB.Stencil_Attachment, Texture, Level, Layer);
when others =>
Object.Attach (FB.Color_Attachment_0, Texture, Level, Layer);
end case;
end Attach;
procedure Detach
(Object : in out Framebuffer;
Attachment : FB.Attachment_Point) is
begin
Object.GL_Framebuffer.Detach (Attachment);
Object.Attachments (Attachment).Clear;
end Detach;
function Has_Attachment
(Object : Framebuffer;
Attachment : FB.Attachment_Point) return Boolean
is (not Object.Attachments (Attachment).Is_Empty);
end Orka.Rendering.Framebuffers;
|
Fix Constraint_Error when trying to clear unattached color buffers
|
orka: Fix Constraint_Error when trying to clear unattached color buffers
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
1dbcadc151670f4ceb83a693d8626a95feba12c2
|
src/orka/interface/orka-transforms-simd_matrices.ads
|
src/orka/interface/orka-transforms-simd_matrices.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.SIMD;
with Orka.Transforms.SIMD_Vectors;
generic
with package Vectors is new Orka.Transforms.SIMD_Vectors (<>);
type Matrix_Type is array (SIMD.Index_Homogeneous) of Vectors.Vector_Type;
with function Multiply_Matrices (Left, Right : Matrix_Type) return Matrix_Type;
with function Multiply_Vector
(Left : Matrix_Type;
Right : Vectors.Vector_Type) return Vectors.Vector_Type;
with function Transpose_Matrix (Matrix : Matrix_Type) return Matrix_Type;
package Orka.Transforms.SIMD_Matrices is
pragma Preelaborate;
subtype Element_Type is Vectors.Element_Type;
subtype Vector_Type is Vectors.Vector_Type;
subtype Matrix4 is Matrix_Type;
subtype Vector4 is Vector_Type;
function Identity_Value return Matrix_Type is
(((1.0, 0.0, 0.0, 0.0),
(0.0, 1.0, 0.0, 0.0),
(0.0, 0.0, 1.0, 0.0),
(0.0, 0.0, 0.0, 1.0)))
with Inline;
-- Return the identity matrix
function Zero_Point return Vector_Type renames Vectors.Zero_Point;
-- Return a zero vector that indicates a point. The fourth (W) component
-- is 1.
-- Linear transform: a transform in which vector addition and scalar
-- multiplication is preserved.
-- Affine transform: a transform that includes a linear transform and
-- a translation. Parallelism of lines remain unchanged, but lengths
-- and angles may not. A concatenation of affine transforms is affine.
--
-- Orthogonal matrix: the inverse of the matrix is equal to the transpose.
-- A concatenation of orthogonal matrices is orthogonal.
function T (Offset : Vector_Type) return Matrix_Type;
-- Translate points by the given amount
--
-- Matrix is affine.
--
-- The inverse T^-1 (t) = T (-t).
function Rx (Angle : Element_Type) return Matrix_Type;
-- Rotate around the x-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Rx^-1 (o) = Rx (-o) = (Rx (o))^T.
function Ry (Angle : Element_Type) return Matrix_Type;
-- Rotate around the y-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Ry^-1 (o) = Ry (-o) = (Ry (o))^T.
function Rz (Angle : Element_Type) return Matrix_Type;
-- Rotate around the z-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Rz^-1 (o) = Rz (-o) = (Rz (o))^T.
function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type;
-- Rotate around the given axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse is R^-1 (a, o) = R (a, -o) = (R (a, o))^T.
function R (Quaternion : Vector_Type) return Matrix_Type;
-- Converts a quaternion to a rotation matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
function S (Factors : Vector_Type) return Matrix_Type;
-- Scale points by the given amount in the x-, y-, and z-axis
--
-- If all axes are scaled by the same amount, then the matrix is
-- affine.
--
-- The inverse is S^-1 (s) = S (1/s_x, 1/s_y, 1/s_z).
function "*" (Left, Right : Matrix_Type) return Matrix_Type renames Multiply_Matrices;
function "*" (Left : Matrix_Type; Right : Vector_Type) return Vector_Type renames Multiply_Vector;
function "+" (Offset : Vector_Type; Matrix : Matrix_Type) return Matrix_Type;
-- Add a translation transformation to the matrix
function "*" (Factor : Element_Type; Matrix : Matrix_Type) return Matrix_Type;
-- Add a scale transformation to the matrix
function Transpose (Matrix : Matrix_Type) return Matrix_Type renames Transpose_Matrix;
procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Axis : Vector_Type; Angle : Element_Type);
-- Add a rotation transformation to the matrix with the center
-- of rotation at the origin to the matrix
procedure Rotate (Matrix : in out Matrix_Type; Axis : Vector_Type;
Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation to the matrix with the center
-- of rotation at the given point to the matrix
procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Quaternion : Vector_Type);
-- Add a rotation transformation based on a quaternion to the matrix
-- with the center of rotation at the origin to the matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
procedure Rotate (Matrix : in out Matrix_Type; Quaternion : Vector_Type;
Point : Vector_Type);
-- Add a rotation transformation based on a quaternion to the matrix
-- with the center of rotation at the given point to the matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
procedure Rotate_X_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the X axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_Y_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the Y axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_Z_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the Z axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_X (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the X axis with the center
-- of rotation at the given point to the matrix
procedure Rotate_Y (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the Y axis with the center
-- of rotation at the given point to the matrix
procedure Rotate_Z (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the Z axis with the center
-- of rotation at the given point to the matrix
-- procedure Rotate_Quaternion (Matrix : in out Matrix_Type; Quaternion : ?);
-- procedure Rotate_Euler (Matrix : in out Matrix_Type; Euler : ?);
procedure Translate (Matrix : in out Matrix_Type; Offset : Vector_Type);
-- Add a translation transformation to the matrix
procedure Scale (Matrix : in out Matrix_Type; Factors : Vector_Type);
procedure Scale (Matrix : in out Matrix_Type; Factor : Element_Type);
procedure Transpose (Matrix : in out Matrix_Type);
-- Transpose the matrix
use type Element_Type;
function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0 and Z_Far > Z_Near;
function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
function Infinite_Perspective_Reversed_Z
(FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => Z_Near >= 0.0 and Z_Far >= 0.0;
end Orka.Transforms.SIMD_Matrices;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.SIMD;
with Orka.Transforms.SIMD_Vectors;
generic
with package Vector_Transforms is new Orka.Transforms.SIMD_Vectors (<>);
type Matrix_Type is array (SIMD.Index_Homogeneous) of Vector_Transforms.Vector_Type;
with function Multiply_Matrices (Left, Right : Matrix_Type) return Matrix_Type;
with function Multiply_Vector
(Left : Matrix_Type;
Right : Vector_Transforms.Vector_Type) return Vector_Transforms.Vector_Type;
with function Transpose_Matrix (Matrix : Matrix_Type) return Matrix_Type;
package Orka.Transforms.SIMD_Matrices is
pragma Preelaborate;
package Vectors renames Vector_Transforms;
subtype Element_Type is Vectors.Element_Type;
subtype Vector_Type is Vectors.Vector_Type;
subtype Matrix4 is Matrix_Type;
subtype Vector4 is Vector_Type;
function Identity_Value return Matrix_Type is
(((1.0, 0.0, 0.0, 0.0),
(0.0, 1.0, 0.0, 0.0),
(0.0, 0.0, 1.0, 0.0),
(0.0, 0.0, 0.0, 1.0)))
with Inline;
-- Return the identity matrix
function Zero_Point return Vector_Type renames Vectors.Zero_Point;
-- Return a zero vector that indicates a point. The fourth (W) component
-- is 1.
-- Linear transform: a transform in which vector addition and scalar
-- multiplication is preserved.
-- Affine transform: a transform that includes a linear transform and
-- a translation. Parallelism of lines remain unchanged, but lengths
-- and angles may not. A concatenation of affine transforms is affine.
--
-- Orthogonal matrix: the inverse of the matrix is equal to the transpose.
-- A concatenation of orthogonal matrices is orthogonal.
function T (Offset : Vector_Type) return Matrix_Type;
-- Translate points by the given amount
--
-- Matrix is affine.
--
-- The inverse T^-1 (t) = T (-t).
function Rx (Angle : Element_Type) return Matrix_Type;
-- Rotate around the x-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Rx^-1 (o) = Rx (-o) = (Rx (o))^T.
function Ry (Angle : Element_Type) return Matrix_Type;
-- Rotate around the y-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Ry^-1 (o) = Ry (-o) = (Ry (o))^T.
function Rz (Angle : Element_Type) return Matrix_Type;
-- Rotate around the z-axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse Rz^-1 (o) = Rz (-o) = (Rz (o))^T.
function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type;
-- Rotate around the given axis by the given amount in radians
--
-- Matrix is orthogonal and affine.
--
-- The inverse is R^-1 (a, o) = R (a, -o) = (R (a, o))^T.
function R (Quaternion : Vector_Type) return Matrix_Type;
-- Converts a quaternion to a rotation matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
function S (Factors : Vector_Type) return Matrix_Type;
-- Scale points by the given amount in the x-, y-, and z-axis
--
-- If all axes are scaled by the same amount, then the matrix is
-- affine.
--
-- The inverse is S^-1 (s) = S (1/s_x, 1/s_y, 1/s_z).
function "*" (Left, Right : Matrix_Type) return Matrix_Type renames Multiply_Matrices;
function "*" (Left : Matrix_Type; Right : Vector_Type) return Vector_Type renames Multiply_Vector;
function "+" (Offset : Vector_Type; Matrix : Matrix_Type) return Matrix_Type;
-- Add a translation transformation to the matrix
function "*" (Factor : Element_Type; Matrix : Matrix_Type) return Matrix_Type;
-- Add a scale transformation to the matrix
function Transpose (Matrix : Matrix_Type) return Matrix_Type renames Transpose_Matrix;
procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Axis : Vector_Type; Angle : Element_Type);
-- Add a rotation transformation to the matrix with the center
-- of rotation at the origin to the matrix
procedure Rotate (Matrix : in out Matrix_Type; Axis : Vector_Type;
Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation to the matrix with the center
-- of rotation at the given point to the matrix
procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Quaternion : Vector_Type);
-- Add a rotation transformation based on a quaternion to the matrix
-- with the center of rotation at the origin to the matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
procedure Rotate (Matrix : in out Matrix_Type; Quaternion : Vector_Type;
Point : Vector_Type);
-- Add a rotation transformation based on a quaternion to the matrix
-- with the center of rotation at the given point to the matrix
--
-- Note: the quaternion must be a unit quaternion (normalized).
procedure Rotate_X_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the X axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_Y_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the Y axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_Z_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type);
-- Add a rotation transformation around the Z axis with the center
-- of rotation at the origin to the matrix
procedure Rotate_X (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the X axis with the center
-- of rotation at the given point to the matrix
procedure Rotate_Y (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the Y axis with the center
-- of rotation at the given point to the matrix
procedure Rotate_Z (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type);
-- Add a rotation transformation around the Z axis with the center
-- of rotation at the given point to the matrix
-- procedure Rotate_Quaternion (Matrix : in out Matrix_Type; Quaternion : ?);
-- procedure Rotate_Euler (Matrix : in out Matrix_Type; Euler : ?);
procedure Translate (Matrix : in out Matrix_Type; Offset : Vector_Type);
-- Add a translation transformation to the matrix
procedure Scale (Matrix : in out Matrix_Type; Factors : Vector_Type);
procedure Scale (Matrix : in out Matrix_Type; Factor : Element_Type);
procedure Transpose (Matrix : in out Matrix_Type);
-- Transpose the matrix
use type Element_Type;
function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0 and Z_Far > Z_Near;
function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
function Infinite_Perspective_Reversed_Z
(FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0;
function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type
with Pre => Z_Near >= 0.0 and Z_Far >= 0.0;
end Orka.Transforms.SIMD_Matrices;
|
Add inner package Vectors to package SIMD_Matrices
|
orka: Add inner package Vectors to package SIMD_Matrices
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
3792d34547e3a56292369fb7c0f0210c1fdf53c2
|
src/ado.ads
|
src/ado.ads
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C;
package ADO is
subtype Int8 is Interfaces.C.signed_char;
subtype Int16 is Interfaces.C.short;
subtype Int32 is Interfaces.C.int;
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
end ADO;
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C;
package ADO is
type Identifier is new Integer;
NO_IDENTIFIER : constant Identifier := -1;
-- subtype Int8 is Interfaces.C.signed_char;
-- subtype Int16 is Interfaces.C.short;
-- subtype Int32 is Interfaces.C.int;
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
end ADO;
|
Define the Identifier type
|
Define the Identifier type
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
5c170ebd0ca4a102a2e4f4c9fef16b442452200d
|
awa/regtests/awa-jobs-services-tests.adb
|
awa/regtests/awa-jobs-services-tests.adb
|
-----------------------------------------------------------------------
-- jobs-tests -- Unit tests for AWA jobs
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Log.Loggers;
with AWA.Jobs.Modules;
with AWA.Services.Contexts;
package body AWA.Jobs.Services.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services.Tests");
package Caller is new Util.Test_Caller (Test, "Jobs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register",
Test_Job_Schedule'Access);
end Add_Tests;
procedure Work_1 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
Msg : constant String := Job.Get_Parameter ("message");
Cnt : constant Natural := Job.Get_Parameter ("count", 0);
begin
Log.Info ("Execute work_1 {0}, count {1}", Msg, Natural'Image (Cnt));
end Work_1;
procedure Work_2 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
begin
null;
end Work_2;
-- ------------------------------
-- Test the job factory.
-- ------------------------------
procedure Test_Job_Schedule (T : in out Test) is
use type AWA.Jobs.Models.Job_Status_Type;
J : AWA.Jobs.Services.Job_Type;
M : AWA.Jobs.Modules.Job_Module_Access := AWA.Jobs.Modules.Get_Job_Module;
Context : AWA.Services.Contexts.Service_Context;
begin
Context.Set_Context (AWA.Tests.Get_Application, null);
M.Register (Definition => Services.Tests.Work_1_Definition.Factory);
J.Set_Parameter ("count", 1);
Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param");
J.Set_Parameter ("message", "Hello");
Util.Tests.Assert_Equals (T, "Hello", J.Get_Parameter ("message"), "Invalid message param");
J.Schedule (Work_1_Definition.Factory);
T.Assert (J.Get_Status = AWA.Jobs.Models.SCHEDULED, "Job is not scheduled");
--
for I in 1 .. 10 loop
delay 0.1;
end loop;
end Test_Job_Schedule;
-- Execute the job. This operation must be implemented and should perform the work
-- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve
-- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result.
overriding
procedure Execute (Job : in out Test_Job) is
begin
null;
end Execute;
end AWA.Jobs.Services.Tests;
|
-----------------------------------------------------------------------
-- jobs-tests -- Unit tests for AWA jobs
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Log.Loggers;
with AWA.Jobs.Modules;
with AWA.Services.Contexts;
package body AWA.Jobs.Services.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services.Tests");
package Caller is new Util.Test_Caller (Test, "Jobs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register",
Test_Job_Schedule'Access);
end Add_Tests;
procedure Work_1 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
Msg : constant String := Job.Get_Parameter ("message");
Cnt : constant Natural := Job.Get_Parameter ("count", 0);
begin
Log.Info ("Execute work_1 {0}, count {1}", Msg, Natural'Image (Cnt));
end Work_1;
procedure Work_2 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
begin
null;
end Work_2;
-- ------------------------------
-- Test the job factory.
-- ------------------------------
procedure Test_Job_Schedule (T : in out Test) is
use type AWA.Jobs.Models.Job_Status_Type;
J : AWA.Jobs.Services.Job_Type;
M : AWA.Jobs.Modules.Job_Module_Access := AWA.Jobs.Modules.Get_Job_Module;
Context : AWA.Services.Contexts.Service_Context;
begin
Context.Set_Context (AWA.Tests.Get_Application, null);
M.Register (Definition => Services.Tests.Work_1_Definition.Factory);
J.Set_Parameter ("count", 1);
Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param");
J.Set_Parameter ("message", "Hello");
Util.Tests.Assert_Equals (T, "Hello", J.Get_Parameter ("message"), "Invalid message param");
J.Schedule (Work_1_Definition.Factory.all);
T.Assert (J.Get_Status = AWA.Jobs.Models.SCHEDULED, "Job is not scheduled");
--
for I in 1 .. 10 loop
delay 0.1;
end loop;
end Test_Job_Schedule;
-- Execute the job. This operation must be implemented and should perform the work
-- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve
-- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result.
overriding
procedure Execute (Job : in out Test_Job) is
begin
null;
end Execute;
end AWA.Jobs.Services.Tests;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e3262ec4d9d9d36772d365e13d58951113e49cc8
|
src/nanomsg-bus.ads
|
src/nanomsg-bus.ads
|
{header}
-- The MIT License (MIT)
-- Copyright (c) 2015 Pavel Zhukov <[email protected]>
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
package Nanomsg.Bus is
Nn_Proto_Bus : constant := 7;
Nn_Bus : constant Protocol_T := Nn_Proto_Bus * 16 + 0;и
end Nanomsg.Bus;
|
-- The MIT License (MIT)
-- Copyright (c) 2015 Pavel Zhukov <[email protected]>
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
package Nanomsg.Bus is
Nn_Proto_Bus : constant := 7;
Nn_Bus : constant Protocol_T := Nn_Proto_Bus * 16 + 0;
end Nanomsg.Bus;
|
Fix typos
|
Fix typos
|
Ada
|
mit
|
landgraf/nanomsg-ada
|
971283201ad518fd9e9a09fff1be8af16db9a3c4
|
src/gen-commands-info.adb
|
src/gen-commands-info.adb
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Files;
package body Gen.Commands.Info is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector);
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean);
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition);
procedure Print_Dynamo_Projects (Project : in out Gen.Model.Projects.Root_Project_Definition);
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count);
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition);
List : Gen.Utils.String_List.Vector;
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector) is
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String);
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String) is
Path : constant String := Util.Files.Compose (Base_Dir, Dir);
begin
if not Result.Contains (Path)
and then Ada.Directories.Exists (Path) then
Result.Append (Path);
end if;
end Add_Model_Dir;
Iter : Gen.Utils.String_List.Cursor := List.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Add_Model_Dir (Dir, "db");
Add_Model_Dir (Dir, "db/regtests");
Add_Model_Dir (Dir, "db/samples");
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Collect_Directories;
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
begin
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (File);
Done := False;
end Print_Model_File;
-- ------------------------------
-- Print the list of GNAT projects used by the main project.
-- ------------------------------
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is
use Gen.Utils.GNAT;
Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First;
Info : Project_Info;
begin
if Project_Info_Vectors.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("GNAT project files:");
while Project_Info_Vectors.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Info := Project_Info_Vectors.Element (Iter);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path));
Project_Info_Vectors.Next (Iter);
end loop;
end if;
end Print_GNAT_Projects;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := Project.Modules.First;
Ref : Model.Projects.Project_Reference;
begin
if Project_Vectors.Has_Element (Iter) then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name));
Ada.Text_IO.Set_Col (Indent + 30);
if Ref.Project /= null then
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path));
else
Ada.Text_IO.Put_Line ("?");
end if;
Project_Vectors.Next (Iter);
end loop;
Iter := Project.Modules.First;
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
if Ref.Project /= null then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("== " & Ada.Strings.Unbounded.To_String (Ref.Name));
Print_Modules (Ref.Project.all, Indent + 4);
end if;
Project_Vectors.Next (Iter);
end loop;
end if;
end Print_Modules;
-- ------------------------------
-- Print the list of Dynamo projects used by the main project.
-- ------------------------------
procedure Print_Dynamo_Projects (Project : in out Gen.Model.Projects.Root_Project_Definition) is
Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First;
begin
if Gen.Utils.String_List.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("Dynamo project files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Gen.Utils.String_List.Next (Iter);
end loop;
end if;
end Print_Dynamo_Projects;
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is
begin
Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project));
Print_Dynamo_Projects (Project);
Print_Modules (Project, 1);
declare
Model_Dirs : Gen.Utils.String_List.Vector;
begin
Collect_Directories (List, Model_Dirs);
declare
Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First;
begin
Ada.Text_IO.Put_Line ("ADO model files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Util.Files.Iterate_Files_Path (Pattern => "*.xml",
Path => Gen.Utils.String_List.Element (Iter),
Process => Print_Model_File'Access);
Gen.Utils.String_List.Next (Iter);
end loop;
end;
end;
end Print_Project;
begin
Generator.Read_Project ("dynamo.xml", True);
Generator.Update_Project (Print_Project'Access);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
begin
Ada.Text_IO.Put_Line ("info: Print information about the current project");
Ada.Text_IO.Put_Line ("Usage: info");
Ada.Text_IO.New_Line;
end Help;
end Gen.Commands.Info;
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Files;
package body Gen.Commands.Info is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector);
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean);
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition);
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition);
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count);
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition);
List : Gen.Utils.String_List.Vector;
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector) is
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String);
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String) is
Path : constant String := Util.Files.Compose (Base_Dir, Dir);
begin
if not Result.Contains (Path)
and then Ada.Directories.Exists (Path) then
Result.Append (Path);
end if;
end Add_Model_Dir;
Iter : Gen.Utils.String_List.Cursor := List.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Add_Model_Dir (Dir, "db");
Add_Model_Dir (Dir, "db/regtests");
Add_Model_Dir (Dir, "db/samples");
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Collect_Directories;
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
begin
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (File);
Done := False;
end Print_Model_File;
-- ------------------------------
-- Print the list of GNAT projects used by the main project.
-- ------------------------------
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is
use Gen.Utils.GNAT;
Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First;
Info : Project_Info;
begin
if Project_Info_Vectors.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("GNAT project files:");
while Project_Info_Vectors.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Info := Project_Info_Vectors.Element (Iter);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path));
Project_Info_Vectors.Next (Iter);
end loop;
end if;
end Print_GNAT_Projects;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := Project.Modules.First;
Ref : Model.Projects.Project_Reference;
begin
if Project_Vectors.Has_Element (Iter) then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name));
Ada.Text_IO.Set_Col (Indent + 30);
if Ref.Project /= null then
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path));
else
Ada.Text_IO.Put_Line ("?");
end if;
Project_Vectors.Next (Iter);
end loop;
Iter := Project.Modules.First;
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("== " & Ada.Strings.Unbounded.To_String (Ref.Name));
Print_Modules (Ref.Project.all, Indent + 4);
end if;
Project_Vectors.Next (Iter);
end loop;
end if;
end Print_Modules;
-- ------------------------------
-- Print the list of Dynamo projects used by the main project.
-- ------------------------------
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is
Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First;
begin
if Gen.Utils.String_List.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("Dynamo project files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Gen.Utils.String_List.Next (Iter);
end loop;
end if;
end Print_Dynamo_Projects;
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is
begin
Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project));
Print_Dynamo_Projects (Project);
Print_Modules (Project, 1);
declare
Model_Dirs : Gen.Utils.String_List.Vector;
begin
Collect_Directories (List, Model_Dirs);
declare
Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First;
begin
Ada.Text_IO.Put_Line ("ADO model files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Util.Files.Iterate_Files_Path (Pattern => "*.xml",
Path => Gen.Utils.String_List.Element (Iter),
Process => Print_Model_File'Access);
Gen.Utils.String_List.Next (Iter);
end loop;
end;
end;
end Print_Project;
begin
Generator.Read_Project ("dynamo.xml", True);
Generator.Update_Project (Print_Project'Access);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
begin
Ada.Text_IO.Put_Line ("info: Print information about the current project");
Ada.Text_IO.Put_Line ("Usage: info");
Ada.Text_IO.New_Line;
end Help;
end Gen.Commands.Info;
|
Fix compilation warnings and simplify the output
|
Fix compilation warnings and simplify the output
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
49713869a67910cd74466c14f9ec120d74d1a9b5
|
src/wiki-render.ads
|
src/wiki-render.ads
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Nodes;
with Wiki.Documents;
-- == Wiki Renderer ==
-- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document
-- and render the result either in text, HTML or another format.
package Wiki.Render is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Link_Renderer is limited interface;
type Link_Renderer_Access is access all Link_Renderer'Class;
-- Get the image link that must be rendered from the wiki image link.
procedure Make_Image_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is abstract;
-- Get the page link that must be rendered from the wiki page link.
procedure Make_Page_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is abstract;
type Default_Link_Renderer is new Link_Renderer with null record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- ------------------------------
-- Document renderer
-- ------------------------------
type Renderer is limited interface;
type Renderer_Access is access all Renderer'Class;
-- Render the node instance from the document.
procedure Render (Engine : in out Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is abstract;
-- Finish the rendering pass after all the wiki document nodes are rendered.
procedure Finish (Engine : in out Renderer) is abstract;
-- Render the list of nodes from the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document;
List : in Wiki.Nodes.Node_List_Access);
-- Render the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document);
end Wiki.Render;
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Nodes;
with Wiki.Documents;
-- == Wiki Renderer ==
-- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document
-- and render the result either in text, HTML or another format.
package Wiki.Render is
pragma Preelaborate;
use Ada.Strings.Wide_Wide_Unbounded;
type Link_Renderer is limited interface;
type Link_Renderer_Access is access all Link_Renderer'Class;
-- Get the image link that must be rendered from the wiki image link.
procedure Make_Image_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is abstract;
-- Get the page link that must be rendered from the wiki page link.
procedure Make_Page_Link (Renderer : in Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is abstract;
type Default_Link_Renderer is new Link_Renderer with null record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- ------------------------------
-- Document renderer
-- ------------------------------
type Renderer is limited interface;
type Renderer_Access is access all Renderer'Class;
-- Render the node instance from the document.
procedure Render (Engine : in out Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is abstract;
-- Finish the rendering pass after all the wiki document nodes are rendered.
procedure Finish (Engine : in out Renderer;
Doc : in Wiki.Documents.Document) is null;
-- Render the list of nodes from the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document;
List : in Wiki.Nodes.Node_List_Access);
-- Render the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document);
end Wiki.Render;
|
Add the document to the Finish procedure
|
Add the document to the Finish procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
5ddb26591501f1fdc268c4adfb3302b81daeb37b
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Storages.Models;
with ADO.Objects;
with ADO.Sessions;
with ADO.Statements;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Stat_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access);
App.Add_Servlet ("blog-image", Plugin.Image_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX);
begin
Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix));
end Configure;
-- ------------------------------
-- 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;
-- ------------------------------
-- Get the image prefix that was configured for the Blog module.
-- ------------------------------
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString is
begin
return Module.Image_Prefix;
end Get_Image_Prefix;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Workspaces.Modules.Add_Permission (Session => DB,
User => User,
Entity => Blog,
Workspace => WS.Get_Id,
List => (ACL_Delete_Blog.Permission,
ACL_Update_Post.Permission,
ACL_Create_Post.Permission,
ACL_Delete_Post.Permission));
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
use type AWA.Blogs.Models.Post_Status_Type;
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);
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
-- ------------------------------
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if not Publish_Date.Is_Null then
Post.Set_Publish_Date (Publish_Date);
end if;
if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
-- ------------------------------
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
-- ------------------------------
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Model);
use type AWA.Storages.Models.Storage_Type;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement;
Kind : AWA.Storages.Models.Storage_Type;
begin
if Width = Natural'Last or Height = Natural'Last then
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
elsif Width > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data);
Query.Bind_Param ("width", Width);
elsif Height > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data);
Query.Bind_Param ("height", Height);
else
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
end if;
Query.Bind_Param ("post_id", Post_Id);
Query.Bind_Param ("store_id", Image_Id);
Query.Bind_Param ("user_id", User);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Width := Query.Get_Natural (4);
Height := Query.Get_Natural (5);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (6);
else
null;
end if;
end Load_Image;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Storages.Models;
with ADO.Objects;
with ADO.Sessions;
with ADO.Statements;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Stat_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access);
App.Add_Servlet ("blog-image", Plugin.Image_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX);
begin
Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix));
end Configure;
-- ------------------------------
-- 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;
-- ------------------------------
-- Get the image prefix that was configured for the Blog module.
-- ------------------------------
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString is
begin
return Module.Image_Prefix;
end Get_Image_Prefix;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Workspaces.Modules.Add_Permission (Session => DB,
User => User,
Entity => Blog,
Workspace => WS.Get_Id,
List => (ACL_Delete_Blog.Permission,
ACL_Update_Post.Permission,
ACL_Create_Post.Permission,
ACL_Delete_Post.Permission));
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type AWA.Blogs.Models.Post_Status_Type;
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);
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
-- ------------------------------
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if not Publish_Date.Is_Null then
Post.Set_Publish_Date (Publish_Date);
end if;
if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
-- ------------------------------
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
-- ------------------------------
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Model);
use type AWA.Storages.Models.Storage_Type;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement;
Kind : AWA.Storages.Models.Storage_Type;
begin
if Width = Natural'Last or Height = Natural'Last then
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
elsif Width > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data);
Query.Bind_Param ("width", Width);
elsif Height > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data);
Query.Bind_Param ("height", Height);
else
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
end if;
Query.Bind_Param ("post_id", Post_Id);
Query.Bind_Param ("store_id", Image_Id);
Query.Bind_Param ("user_id", User);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Width := Query.Get_Natural (4);
Height := Query.Get_Natural (5);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (6);
else
null;
end if;
end Load_Image;
end AWA.Blogs.Modules;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3921ddd54ced38a08e944fec458accd6c6e48422
|
awa/plugins/awa-images/src/awa-images-beans.ads
|
awa/plugins/awa-images/src/awa-images-beans.ads
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- Copyright (C) 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ADO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Storages.Beans;
with AWA.Images.Models;
with AWA.Images.Modules;
-- == Ada Beans ==
-- The `Image_List_Bean` type is used to represent a list of image stored in
-- a folder.
--
-- The `Image_Bean` type holds all the data to give information about an image.
--
-- @include-bean images.xml
-- @include-bean image-info.xml
-- @include-bean image-list.xml
package AWA.Images.Beans is
-- ------------------------------
-- Image List Bean
-- ------------------------------
-- This bean represents a list of images for a given folder.
type Image_List_Bean is new AWA.Storages.Beans.Storage_List_Bean with record
-- List of images.
Image_List : aliased AWA.Images.Models.Image_Info_List_Bean;
Image_List_Bean : AWA.Images.Models.Image_Info_List_Bean_Access;
end record;
type Image_List_Bean_Access is access all Image_List_Bean'Class;
-- Load the list of images associated with the current folder.
overriding
procedure Load_Files (Storage : in Image_List_Bean);
overriding
function Get_Value (List : in Image_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Create the Image_List_Bean bean instance.
function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Image Bean
-- ------------------------------
-- Information about an image (excluding the image data itself).
type Image_Bean is new AWA.Images.Models.Image_Bean with record
Module : AWA.Images.Modules.Image_Module_Access;
end record;
type Image_Bean_Access is access all Image_Bean'Class;
overriding
procedure Load (Into : in out Image_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Image_Bean bean instance.
function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Images.Beans;
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- Copyright (C) 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Storages.Beans;
with AWA.Images.Models;
with AWA.Images.Modules;
-- == Ada Beans ==
-- The `Image_List_Bean` type is used to represent a list of image stored in
-- a folder.
--
-- The `Image_Bean` type holds all the data to give information about an image.
--
-- @include-bean images.xml
-- @include-bean image-info.xml
-- @include-bean image-list.xml
package AWA.Images.Beans is
-- ------------------------------
-- Image List Bean
-- ------------------------------
-- This bean represents a list of images for a given folder.
type Image_List_Bean is new AWA.Storages.Beans.Storage_List_Bean with record
-- List of images.
Image_List : aliased AWA.Images.Models.Image_Info_List_Bean;
Image_List_Bean : AWA.Images.Models.Image_Info_List_Bean_Access;
end record;
type Image_List_Bean_Access is access all Image_List_Bean'Class;
-- Load the list of images associated with the current folder.
overriding
procedure Load_Files (Storage : in Image_List_Bean);
overriding
function Get_Value (List : in Image_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Create the Image_List_Bean bean instance.
function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Image Bean
-- ------------------------------
-- Information about an image (excluding the image data itself).
type Image_Bean is new AWA.Images.Models.Image_Bean with record
Module : AWA.Images.Modules.Image_Module_Access;
end record;
type Image_Bean_Access is access all Image_Bean'Class;
overriding
procedure Load (Into : in out Image_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Image_Bean bean instance.
function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Images.Beans;
|
Fix compilation warning: remove unused with clause for ADO package
|
Fix compilation warning: remove unused with clause for ADO package
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e4ea0b00f0f9deb3c8aca8acce9c64b3ed159280
|
awa/plugins/awa-tags/src/awa-tags.ads
|
awa/plugins/awa-tags/src/awa-tags.ads
|
-----------------------------------------------------------------------
-- awa-tags -- Tags management
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Tags</b> module allows to associate general purpose tags to any database entity.
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png]
--
-- @include awa-tags-modules.ads
package AWA.Tags is
pragma Pure;
end AWA.Tags;
|
-----------------------------------------------------------------------
-- awa-tags -- Tags management
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Tags</b> module allows to associate general purpose tags to any database entity.
-- It provides a JSF component that allows to insert easily a list of tags in a page and
-- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt>
-- to define the tags and it will use the <tt>awa:tagList</tt> component to display them.
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png]
--
-- @include awa-tags-modules.ads
-- @include awa-tags-beans.ads
-- @include awa-tags-components.ads
--
package AWA.Tags is
pragma Pure;
end AWA.Tags;
|
Document the Tags plugin in AWA
|
Document the Tags plugin in AWA
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7c0a78f75c0dadc2d51c5394c0737326b964d76c
|
regtests/util-processes-tests.adb
|
regtests/util-processes-tests.adb
|
-----------------------------------------------------------------------
-- util-processes-tests - Test for processes
-- Copyright (C) 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Test_Caller;
with Util.Files;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Streams.Texts;
with Util.Systems.Os;
package body Util.Processes.Tests is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests");
package Caller is new Util.Test_Caller (Test, "Processes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Processes.Is_Running",
Test_No_Process'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status",
Test_Spawn'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)",
Test_Output_Pipe'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)",
Test_Input_Pipe'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)",
Test_Shell_Splitting_Pipe'Access);
pragma Warnings (Off);
if Util.Systems.Os.Directory_Separator /= '\' then
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)",
Test_Output_Redirect'Access);
end if;
pragma Warnings (On);
Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)",
Test_Multi_Spawn'Access);
end Add_Tests;
-- ------------------------------
-- Tests when the process is not launched
-- ------------------------------
procedure Test_No_Process (T : in out Test) is
P : Process;
begin
T.Assert (not P.Is_Running, "Process should not be running");
T.Assert (P.Get_Pid < 0, "Invalid process id");
end Test_No_Process;
-- ------------------------------
-- Test executing a process
-- ------------------------------
procedure Test_Spawn (T : in out Test) is
P : Process;
begin
-- Launch the test process => exit code 2
P.Spawn ("bin/util_test_process");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status");
-- Launch the test process => exit code 0
P.Spawn ("bin/util_test_process 0 write b c d e f");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Spawn;
-- ------------------------------
-- Test output pipe redirection: read the process standard output
-- ------------------------------
procedure Test_Output_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 write b c d e f test_marker");
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (null, P'Unchecked_Access, 19);
Buffer.Read (Content);
P.Close;
Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Output_Pipe;
-- ------------------------------
-- Test shell splitting.
-- ------------------------------
procedure Test_Shell_Splitting_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 write 'b c d e f' test_marker");
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (null, P'Unchecked_Access, 19);
Buffer.Read (Content);
P.Close;
Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Shell_Splitting_Pipe;
-- ------------------------------
-- Test input pipe redirection: write the process standard input
-- At the same time, read the process standard output.
-- ------------------------------
procedure Test_Input_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 read -", READ_WRITE);
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
Print : Util.Streams.Texts.Print_Stream;
begin
-- Write on the process input stream.
Print.Initialize (P'Unchecked_Access);
Print.Write ("Write test on the input pipe");
Print.Close;
-- Read the output.
Buffer.Initialize (null, P'Unchecked_Access, 19);
Buffer.Read (Content);
-- Wait for the process to finish.
P.Close;
Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Input_Pipe;
-- ------------------------------
-- Test launching several processes through pipes in several threads.
-- ------------------------------
procedure Test_Multi_Spawn (T : in out Test) is
Task_Count : constant Natural := 8;
Count_By_Task : constant Natural := 10;
type State_Array is array (1 .. Task_Count) of Boolean;
States : State_Array;
begin
declare
task type Worker is
entry Start (Count : in Natural);
entry Result (Status : out Boolean);
end Worker;
task body Worker is
Cnt : Natural;
State : Boolean := True;
begin
accept Start (Count : in Natural) do
Cnt := Count;
end Start;
declare
type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream;
Pipes : Pipe_Array;
begin
-- Launch the processes.
-- They will print their arguments on stdout, one by one on each line.
-- The expected exit status is the first argument.
for I in 1 .. Cnt loop
Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker");
end loop;
-- Read their output
for I in 1 .. Cnt loop
declare
Buffer : Util.Streams.Buffered.Buffered_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (null, Pipes (I)'Unchecked_Access, 19);
Buffer.Read (Content);
Pipes (I).Close;
-- Check status and output.
State := State and Pipes (I).Get_Exit_Status = 0;
State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception raised", E);
State := False;
end;
accept Result (Status : out Boolean) do
Status := State;
end Result;
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
for I in Tasks'Range loop
Tasks (I).Start (Count_By_Task);
end loop;
-- Get the results (do not raise any assertion here because we have to call
-- 'Result' to ensure the thread terminates.
for I in Tasks'Range loop
Tasks (I).Result (States (I));
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
for I in States'Range loop
T.Assert (States (I), "Task " & Natural'Image (I) & " failed");
end loop;
end Test_Multi_Spawn;
-- ------------------------------
-- Test output file redirection.
-- ------------------------------
procedure Test_Output_Redirect (T : in out Test) is
P : Process;
Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt");
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Processes.Set_Output_Stream (P, Path);
Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker");
Util.Processes.Wait (P);
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed");
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*test_marker", Content,
"Invalid content");
Util.Processes.Set_Output_Stream (P, Path, True);
Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text");
Util.Processes.Wait (P);
Content := Ada.Strings.Unbounded.Null_Unbounded_String;
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*appended_text", Content,
"Invalid content");
Util.Tests.Assert_Matches (T, ".*test_marker.*", Content,
"Invalid content");
end Test_Output_Redirect;
end Util.Processes.Tests;
|
-----------------------------------------------------------------------
-- util-processes-tests - Test for processes
-- Copyright (C) 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Test_Caller;
with Util.Files;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Streams.Texts;
with Util.Systems.Os;
package body Util.Processes.Tests is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests");
package Caller is new Util.Test_Caller (Test, "Processes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Processes.Is_Running",
Test_No_Process'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status",
Test_Spawn'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)",
Test_Output_Pipe'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)",
Test_Input_Pipe'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)",
Test_Shell_Splitting_Pipe'Access);
pragma Warnings (Off);
if Util.Systems.Os.Directory_Separator /= '\' then
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)",
Test_Output_Redirect'Access);
end if;
pragma Warnings (On);
Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)",
Test_Multi_Spawn'Access);
end Add_Tests;
-- ------------------------------
-- Tests when the process is not launched
-- ------------------------------
procedure Test_No_Process (T : in out Test) is
P : Process;
begin
T.Assert (not P.Is_Running, "Process should not be running");
T.Assert (P.Get_Pid < 0, "Invalid process id");
end Test_No_Process;
-- ------------------------------
-- Test executing a process
-- ------------------------------
procedure Test_Spawn (T : in out Test) is
P : Process;
begin
-- Launch the test process => exit code 2
P.Spawn ("bin/util_test_process");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status");
-- Launch the test process => exit code 0
P.Spawn ("bin/util_test_process 0 write b c d e f");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Spawn;
-- ------------------------------
-- Test output pipe redirection: read the process standard output
-- ------------------------------
procedure Test_Output_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 write b c d e f test_marker");
declare
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (P'Unchecked_Access, 19);
Buffer.Read (Content);
P.Close;
Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Output_Pipe;
-- ------------------------------
-- Test shell splitting.
-- ------------------------------
procedure Test_Shell_Splitting_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 write 'b c d e f' test_marker");
declare
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (P'Unchecked_Access, 19);
Buffer.Read (Content);
P.Close;
Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Shell_Splitting_Pipe;
-- ------------------------------
-- Test input pipe redirection: write the process standard input
-- At the same time, read the process standard output.
-- ------------------------------
procedure Test_Input_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 read -", READ_WRITE);
declare
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
Print : Util.Streams.Texts.Print_Stream;
begin
-- Write on the process input stream.
Print.Initialize (P'Unchecked_Access);
Print.Write ("Write test on the input pipe");
Print.Close;
-- Read the output.
Buffer.Initialize (P'Unchecked_Access, 19);
Buffer.Read (Content);
-- Wait for the process to finish.
P.Close;
Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Input_Pipe;
-- ------------------------------
-- Test launching several processes through pipes in several threads.
-- ------------------------------
procedure Test_Multi_Spawn (T : in out Test) is
Task_Count : constant Natural := 8;
Count_By_Task : constant Natural := 10;
type State_Array is array (1 .. Task_Count) of Boolean;
States : State_Array;
begin
declare
task type Worker is
entry Start (Count : in Natural);
entry Result (Status : out Boolean);
end Worker;
task body Worker is
Cnt : Natural;
State : Boolean := True;
begin
accept Start (Count : in Natural) do
Cnt := Count;
end Start;
declare
type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream;
Pipes : Pipe_Array;
begin
-- Launch the processes.
-- They will print their arguments on stdout, one by one on each line.
-- The expected exit status is the first argument.
for I in 1 .. Cnt loop
Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker");
end loop;
-- Read their output
for I in 1 .. Cnt loop
declare
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (Pipes (I)'Unchecked_Access, 19);
Buffer.Read (Content);
Pipes (I).Close;
-- Check status and output.
State := State and Pipes (I).Get_Exit_Status = 0;
State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception raised", E);
State := False;
end;
accept Result (Status : out Boolean) do
Status := State;
end Result;
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
for I in Tasks'Range loop
Tasks (I).Start (Count_By_Task);
end loop;
-- Get the results (do not raise any assertion here because we have to call
-- 'Result' to ensure the thread terminates.
for I in Tasks'Range loop
Tasks (I).Result (States (I));
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
for I in States'Range loop
T.Assert (States (I), "Task " & Natural'Image (I) & " failed");
end loop;
end Test_Multi_Spawn;
-- ------------------------------
-- Test output file redirection.
-- ------------------------------
procedure Test_Output_Redirect (T : in out Test) is
P : Process;
Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt");
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Processes.Set_Output_Stream (P, Path);
Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker");
Util.Processes.Wait (P);
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed");
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*test_marker", Content,
"Invalid content");
Util.Processes.Set_Output_Stream (P, Path, True);
Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text");
Util.Processes.Wait (P);
Content := Ada.Strings.Unbounded.Null_Unbounded_String;
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*appended_text", Content,
"Invalid content");
Util.Tests.Assert_Matches (T, ".*test_marker.*", Content,
"Invalid content");
end Test_Output_Redirect;
end Util.Processes.Tests;
|
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
|
a7806e8cfef925503dabbf74a00e797d48eef195
|
src/portscan-tests.adb
|
src/portscan-tests.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with File_Operations;
with PortScan.Log;
with Parameters;
with Unix;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Ada.Exceptions;
package body PortScan.Tests is
package FOP renames File_Operations;
package LOG renames PortScan.Log;
package PM renames Parameters;
package LAT renames Ada.Characters.Latin_1;
package DIR renames Ada.Directories;
package EX renames Ada.Exceptions;
--------------------------------------------------------------------------------------------
-- exec_phase_check_plist
--------------------------------------------------------------------------------------------
function exec_check_plist
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
phase_name : String;
seq_id : port_id;
rootdir : String) return Boolean
is
passed_check : Boolean := True;
namebase : constant String := specification.get_namebase;
directory_list : entry_crate.Map;
dossier_list : entry_crate.Map;
begin
LOG.log_phase_begin (log_handle, phase_name);
TIO.Put_Line (log_handle, "====> Checking for package manifest issues");
if not ingest_manifests (specification => specification,
log_handle => log_handle,
directory_list => directory_list,
dossier_list => dossier_list,
seq_id => seq_id,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if orphaned_directories_detected (log_handle => log_handle,
directory_list => directory_list,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if missing_directories_detected (log_handle, directory_list) then
passed_check := False;
end if;
if orphaned_files_detected (log_handle, dossier_list, namebase, rootdir) then
passed_check := False;
end if;
if missing_files_detected (log_handle, dossier_list) then
passed_check := False;
end if;
if passed_check then
TIO.Put_Line (log_handle, "====> No manifest issues found");
end if;
LOG.log_phase_end (log_handle);
return passed_check;
end exec_check_plist;
--------------------------------------------------------------------------------------------
-- ingest_manifests
--------------------------------------------------------------------------------------------
function ingest_manifests
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
dossier_list : in out entry_crate.Map;
seq_id : port_id;
namebase : String;
rootdir : String) return Boolean
is
procedure eat_plist (position : subpackage_crate.Cursor);
procedure insert_directory (directory : String; subpackage : HT.Text);
result : Boolean := True;
procedure insert_directory (directory : String; subpackage : HT.Text)
is
numsep : Natural := HT.count_char (directory, LAT.Solidus);
canvas : HT.Text := HT.SUS (directory);
begin
for x in 1 .. numsep + 1 loop
declare
paint : String := HT.USS (canvas);
my_new_rec : entry_record := (subpackage, False);
begin
if paint /= "" then
if not directory_list.Contains (canvas) then
directory_list.Insert (canvas, my_new_rec);
end if;
canvas := HT.SUS (HT.head (paint, "/"));
end if;
end;
end loop;
end insert_directory;
procedure eat_plist (position : subpackage_crate.Cursor)
is
subpackage : HT.Text := subpackage_crate.Element (position).subpackage;
manifest_file : String := "/construction/" & namebase & "/.manifest." &
HT.USS (subpackage) & ".mktmp";
contents : String := FOP.get_file_contents (rootdir & manifest_file);
identifier : constant String := HT.USS (subpackage) & " manifest: ";
markers : HT.Line_Markers;
begin
HT.initialize_markers (contents, markers);
loop
exit when not HT.next_line_present (contents, markers);
declare
line : constant String := HT.extract_line (contents, markers);
line_text : HT.Text := HT.SUS (line);
new_rec : entry_record := (subpackage, False);
begin
if HT.leads (line, "@comment ") then
null;
elsif HT.leads (line, "@dir ") then
declare
dir : String := line (line'First + 5 .. line'Last);
dir_text : HT.Text := HT.SUS (dir);
begin
if directory_list.Contains (dir_text) then
result := False;
declare
spkg : String := HT.USS (dossier_list.Element (line_text).subpackage);
begin
if spkg /= "" then
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by the " & spkg & " manifest");
else
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by another manifest");
end if;
end;
else
insert_directory (dir, subpackage);
end if;
end;
else
declare
modline : String := modify_file_if_necessary (line);
ml_text : HT.Text := HT.SUS (modline);
begin
if dossier_list.Contains (ml_text) then
result := False;
declare
spkg : String := HT.USS (dossier_list.Element (ml_text).subpackage);
begin
TIO.Put_Line
(log_handle,
"Duplicate file entry, " & identifier & modline &
" already present in " & spkg & " manifest");
end;
else
dossier_list.Insert (ml_text, new_rec);
declare
plistdir : String := DIR.Containing_Directory (modline);
begin
insert_directory (plistdir, subpackage);
end;
end if;
end;
end if;
end;
end loop;
exception
when issue : others =>
TIO.Put_Line (log_handle, "check-plist error: " & EX.Exception_Message (issue));
end eat_plist;
begin
all_ports (seq_id).subpackages.Iterate (eat_plist'Access);
return result;
end ingest_manifests;
--------------------------------------------------------------------------------------------
-- directory_excluded
--------------------------------------------------------------------------------------------
function directory_excluded (candidate : String) return Boolean
is
-- mandatory candidate has ${STAGEDIR}/ stripped (no leading slash)
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
lblen : constant Natural := localbase'Length;
begin
if candidate = localbase then
return True;
end if;
if not HT.leads (candidate, localbase & "/") then
-- This should never happen
return False;
end if;
declare
shortcan : String := candidate (candidate'First + lblen + 1 .. candidate'Last);
begin
if shortcan = "bin" or else
shortcan = "etc" or else
shortcan = "etc/rc.d" or else
shortcan = "include" or else
shortcan = "lib" or else
shortcan = "lib/pkgconfig" or else
shortcan = "libdata" or else
shortcan = "libexec" or else
shortcan = "sbin" or else
shortcan = "share" or else
shortcan = "www"
then
return True;
end if;
if not HT.leads (shortcan, "share/") then
return False;
end if;
end;
declare
shortcan : String := candidate (candidate'First + lblen + 7 .. candidate'Last);
begin
if shortcan = "doc" or else
shortcan = "examples" or else
shortcan = "info" or else
shortcan = "locale" or else
shortcan = "man" or else
shortcan = "nls"
then
return True;
end if;
if shortcan'Length /= 8 or else
not HT.leads (shortcan, "man/man")
then
return False;
end if;
case shortcan (shortcan'Last) is
when '1' .. '9' | 'l' | 'n' => return True;
when others => return False;
end case;
end;
end directory_excluded;
--------------------------------------------------------------------------------------------
-- orphaned_directories_detected
--------------------------------------------------------------------------------------------
function orphaned_directories_detected
(log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
namebase : String;
rootdir : String) return Boolean
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
stagedir : String := rootdir & "/construction/" & namebase & "/stage";
command : String := rootdir & "/usr/bin/find " & stagedir & " -type d -printf " &
LAT.Quotation & "%P\n" & LAT.Quotation;
status : Integer;
comres : String := HT.USS (Unix.piped_command (command, status));
markers : HT.Line_Markers;
lblen : constant Natural := localbase'Length;
result : Boolean := False;
errprefix : constant String := "Orphaned directory detected: ";
begin
if status /= 0 then
TIO.Put_Line ("orphaned_directories_detected: command error: " & comres);
return True;
end if;
HT.initialize_markers (comres, markers);
loop
exit when not HT.next_line_present (comres, markers);
declare
line : constant String := HT.extract_line (comres, markers);
line_text : HT.Text := HT.SUS (line);
begin
if line /= "" then
if HT.leads (line, localbase) then
declare
plist_dir : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last));
begin
if directory_list.Contains (plist_dir) then
directory_list.Update_Element (Position => directory_list.Find (plist_dir),
Process => mark_verified'Access);
else
if not directory_excluded (line) then
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end;
else
if directory_list.Contains (line_text) then
directory_list.Update_Element (Position => directory_list.Find (line_text),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end if;
end;
end loop;
return result;
end orphaned_directories_detected;
--------------------------------------------------------------------------------------------
-- mark_verified
--------------------------------------------------------------------------------------------
procedure mark_verified (key : HT.Text; Element : in out entry_record) is
begin
Element.verified := True;
end mark_verified;
--------------------------------------------------------------------------------------------
-- missing_directories_detected
--------------------------------------------------------------------------------------------
function missing_directories_detected
(log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_dir : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"Directory " & plist_dir & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
directory_list.Iterate (check'Access);
return result;
end missing_directories_detected;
--------------------------------------------------------------------------------------------
-- missing_files_detected
--------------------------------------------------------------------------------------------
function missing_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_file : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"File " & plist_file & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
dossier_list.Iterate (check'Access);
return result;
end missing_files_detected;
--------------------------------------------------------------------------------------------
-- orphaned_files_detected
--------------------------------------------------------------------------------------------
function orphaned_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map;
namebase : String;
rootdir : String) return Boolean
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
stagedir : String := rootdir & "/construction/" & namebase & "/stage";
command : String := rootdir & "/usr/bin/find " & stagedir &
" \( -type f -o -type l \) -printf " &
LAT.Quotation & "%P\n" & LAT.Quotation;
status : Integer;
comres : String := HT.USS (Unix.piped_command (command, status));
markers : HT.Line_Markers;
lblen : constant Natural := localbase'Length;
result : Boolean := False;
errprefix : constant String := "Orphaned file detected: ";
begin
if status /= 0 then
TIO.Put_Line ("orphaned_files_detected: command error: " & comres);
return True;
end if;
HT.initialize_markers (comres, markers);
loop
exit when not HT.next_line_present (comres, markers);
declare
line : constant String := HT.extract_line (comres, markers);
line_text : HT.Text := HT.SUS (line);
begin
if line /= "" then
if HT.leads (line, localbase) then
declare
plist_file : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last));
begin
if dossier_list.Contains (plist_file) then
dossier_list.Update_Element (Position => dossier_list.Find (plist_file),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end;
else
if dossier_list.Contains (line_text) then
dossier_list.Update_Element (Position => dossier_list.Find (line_text),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end if;
end;
end loop;
return result;
end orphaned_files_detected;
--------------------------------------------------------------------------------------------
-- modify_file_if_necessary
--------------------------------------------------------------------------------------------
function modify_file_if_necessary (original : String) return String
is
function strip_raw_localbase (wrkstr : String) return String;
function strip_raw_localbase (wrkstr : String) return String
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase) & "/";
begin
if HT.leads (wrkstr, rawlbase) then
return wrkstr (wrkstr'First + rawlbase'Length .. wrkstr'Last);
else
return wrkstr;
end if;
end strip_raw_localbase;
begin
if HT.leads (original, "@info ") then
return strip_raw_localbase (original (original'First + 6 .. original 'Last));
else
return original;
end if;
end modify_file_if_necessary;
end PortScan.Tests;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with File_Operations;
with PortScan.Log;
with Parameters;
with Unix;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Ada.Exceptions;
package body PortScan.Tests is
package FOP renames File_Operations;
package LOG renames PortScan.Log;
package PM renames Parameters;
package LAT renames Ada.Characters.Latin_1;
package DIR renames Ada.Directories;
package EX renames Ada.Exceptions;
--------------------------------------------------------------------------------------------
-- exec_phase_check_plist
--------------------------------------------------------------------------------------------
function exec_check_plist
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
phase_name : String;
seq_id : port_id;
rootdir : String) return Boolean
is
passed_check : Boolean := True;
namebase : constant String := specification.get_namebase;
directory_list : entry_crate.Map;
dossier_list : entry_crate.Map;
begin
LOG.log_phase_begin (log_handle, phase_name);
TIO.Put_Line (log_handle, "====> Checking for package manifest issues");
if not ingest_manifests (specification => specification,
log_handle => log_handle,
directory_list => directory_list,
dossier_list => dossier_list,
seq_id => seq_id,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if orphaned_directories_detected (log_handle => log_handle,
directory_list => directory_list,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if missing_directories_detected (log_handle, directory_list) then
passed_check := False;
end if;
if orphaned_files_detected (log_handle, dossier_list, namebase, rootdir) then
passed_check := False;
end if;
if missing_files_detected (log_handle, dossier_list) then
passed_check := False;
end if;
if passed_check then
TIO.Put_Line (log_handle, "====> No manifest issues found");
end if;
LOG.log_phase_end (log_handle);
return passed_check;
end exec_check_plist;
--------------------------------------------------------------------------------------------
-- ingest_manifests
--------------------------------------------------------------------------------------------
function ingest_manifests
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
dossier_list : in out entry_crate.Map;
seq_id : port_id;
namebase : String;
rootdir : String) return Boolean
is
procedure eat_plist (position : subpackage_crate.Cursor);
procedure insert_directory (directory : String; subpackage : HT.Text);
result : Boolean := True;
procedure insert_directory (directory : String; subpackage : HT.Text)
is
numsep : Natural := HT.count_char (directory, LAT.Solidus);
canvas : HT.Text := HT.SUS (directory);
begin
for x in 1 .. numsep + 1 loop
declare
paint : String := HT.USS (canvas);
my_new_rec : entry_record := (subpackage, False);
begin
if paint /= "" then
if not directory_list.Contains (canvas) then
directory_list.Insert (canvas, my_new_rec);
end if;
canvas := HT.SUS (HT.head (paint, "/"));
end if;
end;
end loop;
end insert_directory;
procedure eat_plist (position : subpackage_crate.Cursor)
is
subpackage : HT.Text := subpackage_crate.Element (position).subpackage;
manifest_file : String := "/construction/" & namebase & "/.manifest." &
HT.USS (subpackage) & ".mktmp";
contents : String := FOP.get_file_contents (rootdir & manifest_file);
identifier : constant String := HT.USS (subpackage) & " manifest: ";
markers : HT.Line_Markers;
begin
HT.initialize_markers (contents, markers);
loop
exit when not HT.next_line_present (contents, markers);
declare
line : constant String := HT.extract_line (contents, markers);
line_text : HT.Text := HT.SUS (line);
new_rec : entry_record := (subpackage, False);
begin
if HT.leads (line, "@comment ") then
null;
elsif HT.leads (line, "@dir ") then
declare
dir : String := line (line'First + 5 .. line'Last);
dir_text : HT.Text := HT.SUS (dir);
begin
if directory_list.Contains (dir_text) then
result := False;
declare
spkg : String := HT.USS (directory_list.Element (dir_text).subpackage);
begin
if spkg /= "" then
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by the " & spkg & " manifest");
else
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by another manifest");
end if;
end;
else
insert_directory (dir, subpackage);
end if;
end;
else
declare
modline : String := modify_file_if_necessary (line);
ml_text : HT.Text := HT.SUS (modline);
begin
if dossier_list.Contains (ml_text) then
result := False;
declare
spkg : String := HT.USS (dossier_list.Element (ml_text).subpackage);
begin
TIO.Put_Line
(log_handle,
"Duplicate file entry, " & identifier & modline &
" already present in " & spkg & " manifest");
end;
else
dossier_list.Insert (ml_text, new_rec);
declare
plistdir : String := DIR.Containing_Directory (modline);
begin
insert_directory (plistdir, subpackage);
end;
end if;
end;
end if;
end;
end loop;
exception
when issue : others =>
TIO.Put_Line (log_handle, "check-plist error: " & EX.Exception_Message (issue));
end eat_plist;
begin
all_ports (seq_id).subpackages.Iterate (eat_plist'Access);
return result;
end ingest_manifests;
--------------------------------------------------------------------------------------------
-- directory_excluded
--------------------------------------------------------------------------------------------
function directory_excluded (candidate : String) return Boolean
is
-- mandatory candidate has ${STAGEDIR}/ stripped (no leading slash)
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
lblen : constant Natural := localbase'Length;
begin
if candidate = localbase then
return True;
end if;
if not HT.leads (candidate, localbase & "/") then
-- This should never happen
return False;
end if;
declare
shortcan : String := candidate (candidate'First + lblen + 1 .. candidate'Last);
begin
if shortcan = "bin" or else
shortcan = "etc" or else
shortcan = "etc/rc.d" or else
shortcan = "include" or else
shortcan = "lib" or else
shortcan = "lib/pkgconfig" or else
shortcan = "libdata" or else
shortcan = "libexec" or else
shortcan = "sbin" or else
shortcan = "share" or else
shortcan = "www"
then
return True;
end if;
if not HT.leads (shortcan, "share/") then
return False;
end if;
end;
declare
shortcan : String := candidate (candidate'First + lblen + 7 .. candidate'Last);
begin
if shortcan = "doc" or else
shortcan = "examples" or else
shortcan = "info" or else
shortcan = "locale" or else
shortcan = "man" or else
shortcan = "nls"
then
return True;
end if;
if shortcan'Length /= 8 or else
not HT.leads (shortcan, "man/man")
then
return False;
end if;
case shortcan (shortcan'Last) is
when '1' .. '9' | 'l' | 'n' => return True;
when others => return False;
end case;
end;
end directory_excluded;
--------------------------------------------------------------------------------------------
-- orphaned_directories_detected
--------------------------------------------------------------------------------------------
function orphaned_directories_detected
(log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
namebase : String;
rootdir : String) return Boolean
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
stagedir : String := rootdir & "/construction/" & namebase & "/stage";
command : String := rootdir & "/usr/bin/find " & stagedir & " -type d -printf " &
LAT.Quotation & "%P\n" & LAT.Quotation;
status : Integer;
comres : String := HT.USS (Unix.piped_command (command, status));
markers : HT.Line_Markers;
lblen : constant Natural := localbase'Length;
result : Boolean := False;
errprefix : constant String := "Orphaned directory detected: ";
begin
if status /= 0 then
TIO.Put_Line ("orphaned_directories_detected: command error: " & comres);
return True;
end if;
HT.initialize_markers (comres, markers);
loop
exit when not HT.next_line_present (comres, markers);
declare
line : constant String := HT.extract_line (comres, markers);
line_text : HT.Text := HT.SUS (line);
begin
if line /= "" then
if HT.leads (line, localbase) then
declare
plist_dir : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last));
begin
if directory_list.Contains (plist_dir) then
directory_list.Update_Element (Position => directory_list.Find (plist_dir),
Process => mark_verified'Access);
else
if not directory_excluded (line) then
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end;
else
if directory_list.Contains (line_text) then
directory_list.Update_Element (Position => directory_list.Find (line_text),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end if;
end;
end loop;
return result;
end orphaned_directories_detected;
--------------------------------------------------------------------------------------------
-- mark_verified
--------------------------------------------------------------------------------------------
procedure mark_verified (key : HT.Text; Element : in out entry_record) is
begin
Element.verified := True;
end mark_verified;
--------------------------------------------------------------------------------------------
-- missing_directories_detected
--------------------------------------------------------------------------------------------
function missing_directories_detected
(log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_dir : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"Directory " & plist_dir & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
directory_list.Iterate (check'Access);
return result;
end missing_directories_detected;
--------------------------------------------------------------------------------------------
-- missing_files_detected
--------------------------------------------------------------------------------------------
function missing_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_file : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"File " & plist_file & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
dossier_list.Iterate (check'Access);
return result;
end missing_files_detected;
--------------------------------------------------------------------------------------------
-- orphaned_files_detected
--------------------------------------------------------------------------------------------
function orphaned_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map;
namebase : String;
rootdir : String) return Boolean
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
stagedir : String := rootdir & "/construction/" & namebase & "/stage";
command : String := rootdir & "/usr/bin/find " & stagedir &
" \( -type f -o -type l \) -printf " &
LAT.Quotation & "%P\n" & LAT.Quotation;
status : Integer;
comres : String := HT.USS (Unix.piped_command (command, status));
markers : HT.Line_Markers;
lblen : constant Natural := localbase'Length;
result : Boolean := False;
errprefix : constant String := "Orphaned file detected: ";
begin
if status /= 0 then
TIO.Put_Line ("orphaned_files_detected: command error: " & comres);
return True;
end if;
HT.initialize_markers (comres, markers);
loop
exit when not HT.next_line_present (comres, markers);
declare
line : constant String := HT.extract_line (comres, markers);
line_text : HT.Text := HT.SUS (line);
begin
if line /= "" then
if HT.leads (line, localbase) then
declare
plist_file : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last));
begin
if dossier_list.Contains (plist_file) then
dossier_list.Update_Element (Position => dossier_list.Find (plist_file),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end;
else
if dossier_list.Contains (line_text) then
dossier_list.Update_Element (Position => dossier_list.Find (line_text),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end if;
end;
end loop;
return result;
end orphaned_files_detected;
--------------------------------------------------------------------------------------------
-- modify_file_if_necessary
--------------------------------------------------------------------------------------------
function modify_file_if_necessary (original : String) return String
is
function strip_raw_localbase (wrkstr : String) return String;
function strip_raw_localbase (wrkstr : String) return String
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase) & "/";
begin
if HT.leads (wrkstr, rawlbase) then
return wrkstr (wrkstr'First + rawlbase'Length .. wrkstr'Last);
else
return wrkstr;
end if;
end strip_raw_localbase;
begin
if HT.leads (original, "@info ") then
return strip_raw_localbase (original (original'First + 6 .. original 'Last));
else
return original;
end if;
end modify_file_if_necessary;
end PortScan.Tests;
|
fix typo in redundant @dir detection algorithm
|
fix typo in redundant @dir detection algorithm
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
cc337ec2cbba13e0b291956970d71b96b322e67f
|
src/asm-intrinsic/util-concurrent-counters.ads
|
src/asm-intrinsic/util-concurrent-counters.ads
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>Counters</b> package defines the <b>Counter</b> type which provides
-- atomic increment and decrement operations. It is intended to be used to
-- implement reference counting in a multi-threaded environment.
--
-- type Ref is record
-- Cnt : Counter;
-- Data : ...;
-- end record;
--
-- Object : access Ref;
-- Is_Last : Boolean;
-- begin
-- Decrement (Object.Cnt, Is_Last); -- Multi-task safe operation
-- if Is_Last then
-- Free (Object);
-- end if;
--
-- Unlike the Ada portable implementation based on protected type, this implementation
-- does not require that <b>Counter</b> be a limited type.
private with Interfaces;
package Util.Concurrent.Counters is
pragma Preelaborate;
-- ------------------------------
-- Atomic Counter
-- ------------------------------
-- The atomic <b>Counter</b> implements a simple counter that can be
-- incremented or decremented atomically.
type Counter is private;
type Counter_Access is access all Counter;
-- Increment the counter atomically.
procedure Increment (C : in out Counter);
pragma Inline_Always (Increment);
-- Increment the counter atomically and return the value before increment.
procedure Increment (C : in out Counter;
Value : out Integer);
pragma Inline_Always (Increment);
-- Decrement the counter atomically.
procedure Decrement (C : in out Counter);
pragma Inline_Always (Decrement);
-- Decrement the counter atomically and return a status.
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean);
pragma Inline_Always (Decrement);
-- Get the counter value
function Value (C : in Counter) return Integer;
pragma Inline_Always (Value);
ONE : constant Counter;
private
-- This implementation works without an Ada protected type:
-- o The size of the target object is 10 times smaller.
-- o Increment and Decrement operations are 5 times faster.
-- o It works by using special instructions
-- o The counter is Atomic to make sure the compiler will use atomic read/write instructions
-- and it prevents optimization (Atomic implies Volatile). The Atomic does not mean
-- that atomic instructions are used.
type Counter is record
Value : aliased Interfaces.Unsigned_32 := 0;
pragma Atomic (Value);
end record;
ONE : constant Counter := Counter '(Value => 1);
end Util.Concurrent.Counters;
|
-----------------------------------------------------------------------
-- util-concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010, 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.
-----------------------------------------------------------------------
-- The <b>Counters</b> package defines the <b>Counter</b> type which provides
-- atomic increment and decrement operations. It is intended to be used to
-- implement reference counting in a multi-threaded environment.
--
-- type Ref is record
-- Cnt : Counter;
-- Data : ...;
-- end record;
--
-- Object : access Ref;
-- Is_Last : Boolean;
-- begin
-- Decrement (Object.Cnt, Is_Last); -- Multi-task safe operation
-- if Is_Last then
-- Free (Object);
-- end if;
--
-- Unlike the Ada portable implementation based on protected type, this implementation
-- does not require that <b>Counter</b> be a limited type.
private with Interfaces;
package Util.Concurrent.Counters is
pragma Preelaborate;
-- ------------------------------
-- Atomic Counter
-- ------------------------------
-- The atomic <b>Counter</b> implements a simple counter that can be
-- incremented or decremented atomically.
type Counter is private;
type Counter_Access is access all Counter;
-- Increment the counter atomically.
procedure Increment (C : in out Counter);
pragma Inline_Always (Increment);
-- Increment the counter atomically and return the value before increment.
procedure Increment (C : in out Counter;
Value : out Integer);
pragma Inline_Always (Increment);
-- Decrement the counter atomically.
procedure Decrement (C : in out Counter);
pragma Inline_Always (Decrement);
-- Decrement the counter atomically and return a status.
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean);
pragma Inline_Always (Decrement);
-- Get the counter value
function Value (C : in Counter) return Integer;
pragma Inline_Always (Value);
ONE : constant Counter;
private
-- This implementation works without an Ada protected type:
-- o The size of the target object is 10 times smaller.
-- o Increment and Decrement operations are 5 times faster.
-- o It works by using special instructions
-- o The counter is Atomic to make sure the compiler will use atomic read/write instructions
-- and it prevents optimization (Atomic implies Volatile). The Atomic does not mean
-- that atomic instructions are used.
type Counter is record
Value : aliased Interfaces.Unsigned_32 := 0;
pragma Atomic (Value);
end record;
ONE : constant Counter := Counter '(Value => 1);
end Util.Concurrent.Counters;
|
Update the header
|
Update the header
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a3ef9f30b5f6b23f42f0b22449affedad9942d7e
|
src/security-oauth.ads
|
src/security-oauth.ads
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization
-- framework as defined by the IETF working group.
-- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26
package Security.OAuth is
-- OAuth 2.0: Section 10.2.2. Initial Registry Contents
Client_Id : constant String := "client_id";
Client_Secret : constant String := "client_secret";
Response_Type : constant String := "response_type";
Redirect_Uri : constant String := "redirect_uri";
Scope : constant String := "scope";
State : constant String := "state";
Code : constant String := "code";
Error_Description : constant String := "error_description";
Error_Uri : constant String := "error_uri";
Grant_Type : constant String := "grant_type";
Access_Token : constant String := "access_token";
Token_Type : constant String := "token_type";
Expires_In : constant String := "expires_in";
Username : constant String := "username";
Password : constant String := "password";
Refresh_Token : constant String := "refresh_token";
end Security.OAuth;
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == OAuth ==
-- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization
-- framework as defined by the IETF working group.
-- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26
package Security.OAuth is
-- OAuth 2.0: Section 10.2.2. Initial Registry Contents
Client_Id : constant String := "client_id";
Client_Secret : constant String := "client_secret";
Response_Type : constant String := "response_type";
Redirect_Uri : constant String := "redirect_uri";
Scope : constant String := "scope";
State : constant String := "state";
Code : constant String := "code";
Error_Description : constant String := "error_description";
Error_Uri : constant String := "error_uri";
Grant_Type : constant String := "grant_type";
Access_Token : constant String := "access_token";
Token_Type : constant String := "token_type";
Expires_In : constant String := "expires_in";
Username : constant String := "username";
Password : constant String := "password";
Refresh_Token : constant String := "refresh_token";
end Security.OAuth;
|
Include in generated documentation by Dynamo
|
Include in generated documentation by Dynamo
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
0c6ea2464b399734b8bd5cba2f733bb34f47c93e
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes.Lists;
-- == Documents ==
-- The `Document` type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The `Document` 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 `Wiki.Documents` 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;
--
-- After parsing some HTML or Wiki text, it will contain a representation of the
-- HTML or Wiki text. It is possible to populate the document by using one of
-- the `Append`, `Add_Link`, `Add_Image` operation.
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 (<ul> or <ol>) starting at the given number.
procedure Add_List (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);
-- Add a new row to the current table.
procedure Add_Row (Into : in out Document);
-- 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);
-- Finish the creation of the table.
procedure Finish_Table (Into : in out Document);
-- 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;
-- Hide the table of contents.
procedure Hide_TOC (Doc : in out Document);
-- 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);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.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.Lists.Node_List_Ref;
TOC : Wiki.Nodes.Lists.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes.Lists;
-- == Documents ==
-- The `Document` type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The `Document` 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 `Wiki.Documents` 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;
--
-- After parsing some HTML or Wiki text, it will contain a representation of the
-- HTML or Wiki text. It is possible to populate the document by using one of
-- the `Append`, `Add_Link`, `Add_Image` operation.
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 definition item at end of the document.
procedure Add_Definition (Into : in out Document;
Definition : in Wiki.Strings.WString);
-- 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 (<ul> or <ol>) starting at the given number.
procedure Add_List (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);
-- Add a new row to the current table.
procedure Add_Row (Into : in out Document);
-- 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);
-- Finish the creation of the table.
procedure Finish_Table (Into : in out Document);
-- 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;
-- Hide the table of contents.
procedure Hide_TOC (Doc : in out Document);
-- 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);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.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.Lists.Node_List_Ref;
TOC : Wiki.Nodes.Lists.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
Declare the Add_Definition procedure
|
Declare the Add_Definition procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
97957204ff3ca07403d6f7c2e096beed63123998
|
src/wiki-nodes.ads
|
src/wiki-nodes.ads
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
package Wiki.Nodes is
subtype Format_Map is Wiki.Documents.Format_Map;
subtype WString is Wide_Wide_String;
type Node_Kind is (N_HEADER,
N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_TAG_END,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag_Type is
(
-- Section 4.1 The root element
HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT =>
Level : Natural := 0;
Header : WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : WString (1 .. Len);
when N_LINK | N_IMAGE =>
Link : Wiki.Attributes.Attribute_List_Type;
when N_QUOTE =>
Quote : WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag_Type;
Attributes : Wiki.Attributes.Attribute_List_Type;
Children : Node_List_Access;
when N_TAG_END =>
Tag_End : Html_Tag_Type;
when others =>
null;
end case;
end record;
type Node_Type_Access is access all Node_Type;
type Document_Node_Access is private;
type Document is limited private;
-- Create a text node.
function Create_Text (Text : in WString) return Node_Type_Access;
-- procedure Add_Text (Doc : in out Document;
-- Text : in WString);
-- type Renderer is limited interface;
--
-- procedure Render (Engine : in out Renderer;
-- Doc : in Document;
-- Node : in Node_Type) is abstract;
--
-- procedure Iterate (Doc : in Document;
-- Process : access procedure (Doc : in Document; Node : in Node_Type)) is
-- Node : Document_Node_Access := Doc.First;
-- begin
-- while Node /= null loop
-- Process (Doc, Node.Data);
-- Node := Node.Next;
-- end loop;
-- end Iterate;
private
NODE_LIST_BLOCK_SIZE : constant Positive := 20;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
type Document_Node;
type Document_Node_Access is access all Document_Node;
type Document_Node (Kind : Node_Kind; Len : Natural) is limited record
Next : Document_Node_Access;
Prev : Document_Node_Access;
Data : Node_Type (Kind, Len);
end record;
type Document is limited record
First : Document_Node_Access;
Last : Document_Node_Access;
end record;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
package Wiki.Nodes is
subtype Format_Map is Wiki.Documents.Format_Map;
subtype WString is Wide_Wide_String;
type Node_Kind is (N_HEADER,
N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_TAG_END,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag_Type is
(
-- Section 4.1 The root element
HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT =>
Level : Natural := 0;
Header : WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : WString (1 .. Len);
when N_LINK | N_IMAGE =>
Link : Wiki.Attributes.Attribute_List_Type;
when N_QUOTE =>
Quote : WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag_Type;
Attributes : Wiki.Attributes.Attribute_List_Type;
Children : Node_List_Access;
when N_TAG_END =>
Tag_End : Html_Tag_Type;
when others =>
null;
end case;
end record;
type Node_Type_Access is access all Node_Type;
type Document_Node_Access is private;
type Document is limited private;
-- Create a text node.
function Create_Text (Text : in WString) return Node_Type_Access;
-- procedure Add_Text (Doc : in out Document;
-- Text : in WString);
-- type Renderer is limited interface;
--
-- procedure Render (Engine : in out Renderer;
-- Doc : in Document;
-- Node : in Node_Type) is abstract;
--
-- procedure Iterate (Doc : in Document;
-- Process : access procedure (Doc : in Document; Node : in Node_Type)) is
-- Node : Document_Node_Access := Doc.First;
-- begin
-- while Node /= null loop
-- Process (Doc, Node.Data);
-- Node := Node.Next;
-- end loop;
-- end Iterate;
private
NODE_LIST_BLOCK_SIZE : constant Positive := 20;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block_Access;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
-- Append a node to the node list.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
type Document_Node;
type Document_Node_Access is access all Document_Node;
type Document_Node (Kind : Node_Kind; Len : Natural) is limited record
Next : Document_Node_Access;
Prev : Document_Node_Access;
Data : Node_Type (Kind, Len);
end record;
type Document is limited record
First : Document_Node_Access;
Last : Document_Node_Access;
end record;
end Wiki.Nodes;
|
Declare the Append procedure
|
Declare the Append procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
5ab63f08d8dc51a025aaaee0037b7ac1108e471e
|
regtests/gen-integration-tests.adb
|
regtests/gen-integration-tests.adb
|
-----------------------------------------------------------------------
-- gen-integration-tests -- Tests for integration
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Tests;
with Util.Test_Caller;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Processes;
package body Gen.Integration.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Integration.Tests");
package Caller is new Util.Test_Caller (Test, "Dynamo");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Create_Project",
Test_Create_Project'Access);
Caller.Add_Test (Suite, "Configure",
Test_Configure'Access);
Caller.Add_Test (Suite, "Propset",
Test_Change_Property'Access);
Caller.Add_Test (Suite, "Add Module",
Test_Add_Module'Access);
end Add_Tests;
-- ------------------------------
-- Execute the command and get the output in a string.
-- ------------------------------
procedure Execute (T : in out Test;
Command : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
begin
P.Open (Command, Util.Processes.READ);
-- Write on the process input stream.
Buffer.Initialize (null, P'Unchecked_Access, 8192);
Buffer.Read (Result);
P.Close;
Log.Info ("Command result: {0}", Result);
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Command '" & Command & "' failed");
end Execute;
-- ------------------------------
-- Test dynamo create-project command.
-- ------------------------------
procedure Test_Create_Project (T : in out Test) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
Ada.Directories.Delete_Tree ("test-app");
T.Execute ("bin/dynamo -o test-app create-project -l apache test", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*test.properties", Result,
"Invalid generation");
Util.Tests.Assert_Matches (T, ".*Generating file.*src/test.ads", Result,
"Invalid generation");
end Test_Create_Project;
-- ------------------------------
-- Test project configure.
-- ------------------------------
procedure Test_Configure (T : in out Test) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("./configure", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*test.properties", Result,
"Invalid configure");
end Test_Configure;
-- ------------------------------
-- Test propset command.
-- ------------------------------
procedure Test_Change_Property (T : in out Test) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/dynamo -o test-app propset author Druss", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*test.properties", Result,
"Invalid configure");
T.Execute ("bin/dynamo -o test-app propset author_email [email protected]", Result);
T.Execute ("bin/dynamo -o test-app propset license Apache", Result);
end Test_Change_Property;
-- ------------------------------
-- Test add-module command.
-- ------------------------------
procedure Test_Add_Module (T : in out Test) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/dynamo -o test-app add-module blog", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*model/test-blog-model.ads", Result,
"Invalid add-module");
T.Execute ("bin/dynamo -o test-app add-module user", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*model/test-user-model.ads", Result,
"Invalid add-module");
end Test_Add_Module;
end Gen.Integration.Tests;
|
-----------------------------------------------------------------------
-- gen-integration-tests -- Tests for integration
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Log.Loggers;
with Util.Tests;
with Util.Test_Caller;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Processes;
package body Gen.Integration.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Integration.Tests");
package Caller is new Util.Test_Caller (Test, "Dynamo");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Create_Project",
Test_Create_Project'Access);
Caller.Add_Test (Suite, "Configure",
Test_Configure'Access);
Caller.Add_Test (Suite, "Propset",
Test_Change_Property'Access);
Caller.Add_Test (Suite, "Add Module",
Test_Add_Module'Access);
end Add_Tests;
-- ------------------------------
-- Execute the command and get the output in a string.
-- ------------------------------
procedure Execute (T : in out Test;
Command : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
begin
P.Open (Command, Util.Processes.READ);
-- Write on the process input stream.
Buffer.Initialize (null, P'Unchecked_Access, 8192);
Buffer.Read (Result);
P.Close;
Log.Info ("Command result: {0}", Result);
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Command '" & Command & "' failed");
end Execute;
-- ------------------------------
-- Test dynamo create-project command.
-- ------------------------------
procedure Test_Create_Project (T : in out Test) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
Ada.Directories.Delete_Tree ("test-app");
T.Execute ("bin/dynamo -o test-app create-project -l apache test", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*test.properties", Result,
"Invalid generation");
Util.Tests.Assert_Matches (T, ".*Generating file.*src/test.ads", Result,
"Invalid generation");
end Test_Create_Project;
-- ------------------------------
-- Test project configure.
-- ------------------------------
procedure Test_Configure (T : in out Test) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("./configure", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*test.properties", Result,
"Invalid configure");
end Test_Configure;
-- ------------------------------
-- Test propset command.
-- ------------------------------
procedure Test_Change_Property (T : in out Test) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/dynamo -o test-app propset author Druss", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*test.properties", Result,
"Invalid configure");
T.Execute ("bin/dynamo -o test-app propset author_email [email protected]", Result);
T.Execute ("bin/dynamo -o test-app propset license Apache", Result);
end Test_Change_Property;
-- ------------------------------
-- Test add-module command.
-- ------------------------------
procedure Test_Add_Module (T : in out Test) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/dynamo -o test-app add-module blog", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*model/test-blog-model.ads", Result,
"Invalid add-module");
T.Execute ("bin/dynamo -o test-app add-module user", Result);
Util.Tests.Assert_Matches (T, ".*Generating file.*model/test-user-model.ads", Result,
"Invalid add-module");
end Test_Add_Module;
end Gen.Integration.Tests;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
01c11f19ed9816f61dc3e24f31f1ffa792b45e35
|
awa/src/awa-users-beans.ads
|
awa/src/awa-users-beans.ads
|
-----------------------------------------------------------------------
-- awa-users-beans -- ASF Beans for user module
-- Copyright (C) 2011, 2012, 2013, 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.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Methods;
with Ada.Strings.Unbounded;
with AWA.Users.Services;
with AWA.Users.Modules;
with AWA.Users.Principals;
-- == Ada Beans ==
-- Several bean types are provided to represent and manage the users.
-- The user module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application
-- XML configuration.
--
-- @include-bean users.xml
--
package AWA.Users.Beans is
use Ada.Strings.Unbounded;
type Authenticate_Bean is new Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Module : AWA.Users.Modules.User_Module_Access := null;
Manager : AWA.Users.Services.User_Service_Access := null;
Email : Unbounded_String;
Password : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Access_Key : Unbounded_String;
end record;
-- Attributes exposed by the <b>Authenticate_Bean</b> through Get_Value.
EMAIL_ATTR : constant String := "email";
PASSWORD_ATTR : constant String := "password";
FIRST_NAME_ATTR : constant String := "firstName";
LAST_NAME_ATTR : constant String := "lastName";
KEY_ATTR : constant String := "key";
type Authenticate_Bean_Access is access all Authenticate_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Authenticate_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Authenticate_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Authenticate_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
procedure Set_Session_Principal (Data : in Authenticate_Bean;
Principal : in AWA.Users.Principals.Principal_Access);
procedure Set_Authenticate_Cookie (Data : in out Authenticate_Bean;
Principal : in AWA.Users.Principals.Principal_Access);
-- Action to register a user
procedure Register_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Action to verify the user after the registration
procedure Verify_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Action to trigger the lost password email process.
procedure Lost_Password (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Action to validate the reset password key and set a new password.
procedure Reset_Password (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Action to authenticate a user (password authentication).
procedure Authenticate_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Logout the user and closes the session.
procedure Logout_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
procedure Load_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Create an authenticate bean.
function Create_Authenticate_Bean (Module : in AWA.Users.Modules.User_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Current user
-- ------------------------------
-- The <b>Current_User_Bean</b> provides information about the current user.
-- It relies on the <b>AWA.Services.Contexts</b> to identify the current user
-- and return information about him/her.
type Current_User_Bean is new Util.Beans.Basic.Readonly_Bean with null record;
type Current_User_Bean_Access is access all Current_User_Bean'Class;
-- Attributes exposed by <b>Current_User_Bean</b>
IS_LOGGED_ATTR : constant String := "isLogged";
USER_EMAIL_ATTR : constant String := "email";
USER_NAME_ATTR : constant String := "name";
USER_ID_ATTR : constant String := "id";
-- Get the value identified by the name. The following names are recognized:
-- o isLogged Boolean True if a user is logged
-- o name String The user name
-- o email String The user email address
-- o id Long The user identifier
overriding
function Get_Value (From : in Current_User_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Create the current user bean.
function Create_Current_User_Bean (Module : in AWA.Users.Modules.User_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Users.Beans;
|
-----------------------------------------------------------------------
-- awa-users-beans -- ASF Beans for user module
-- Copyright (C) 2011, 2012, 2013, 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.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Methods;
with Ada.Strings.Unbounded;
with AWA.Users.Services;
with AWA.Users.Modules;
with AWA.Users.Principals;
-- == Ada Beans ==
-- Several bean types are provided to represent and manage the users.
-- The user module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application
-- XML configuration.
--
-- @include-bean users.xml
--
package AWA.Users.Beans is
use Ada.Strings.Unbounded;
type Authenticate_Bean is new Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Module : AWA.Users.Modules.User_Module_Access := null;
Manager : AWA.Users.Services.User_Service_Access := null;
Email : Unbounded_String;
Password : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Access_Key : Unbounded_String;
Redirect : Unbounded_String;
end record;
-- Attributes exposed by the <b>Authenticate_Bean</b> through Get_Value.
EMAIL_ATTR : constant String := "email";
PASSWORD_ATTR : constant String := "password";
FIRST_NAME_ATTR : constant String := "firstName";
LAST_NAME_ATTR : constant String := "lastName";
KEY_ATTR : constant String := "key";
REDIRECT_ATTR : constant String := "redirect";
type Authenticate_Bean_Access is access all Authenticate_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Authenticate_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Authenticate_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Authenticate_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
procedure Set_Session_Principal (Data : in Authenticate_Bean;
Principal : in AWA.Users.Principals.Principal_Access);
procedure Set_Authenticate_Cookie (Data : in out Authenticate_Bean;
Principal : in AWA.Users.Principals.Principal_Access);
-- Action to register a user
procedure Register_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Action to verify the user after the registration
procedure Verify_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Action to trigger the lost password email process.
procedure Lost_Password (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Action to validate the reset password key and set a new password.
procedure Reset_Password (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Action to authenticate a user (password authentication).
procedure Authenticate_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Logout the user and closes the session.
procedure Logout_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
procedure Load_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String);
-- Create an authenticate bean.
function Create_Authenticate_Bean (Module : in AWA.Users.Modules.User_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Current user
-- ------------------------------
-- The <b>Current_User_Bean</b> provides information about the current user.
-- It relies on the <b>AWA.Services.Contexts</b> to identify the current user
-- and return information about him/her.
type Current_User_Bean is new Util.Beans.Basic.Readonly_Bean with null record;
type Current_User_Bean_Access is access all Current_User_Bean'Class;
-- Attributes exposed by <b>Current_User_Bean</b>
IS_LOGGED_ATTR : constant String := "isLogged";
USER_EMAIL_ATTR : constant String := "email";
USER_NAME_ATTR : constant String := "name";
USER_ID_ATTR : constant String := "id";
-- Get the value identified by the name. The following names are recognized:
-- o isLogged Boolean True if a user is logged
-- o name String The user name
-- o email String The user email address
-- o id Long The user identifier
overriding
function Get_Value (From : in Current_User_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Create the current user bean.
function Create_Current_User_Bean (Module : in AWA.Users.Modules.User_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Users.Beans;
|
Add Redirect member in the Authenticate_Bean to redirect to a specific page after login
|
Add Redirect member in the Authenticate_Bean to redirect to a specific page after login
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
654614746b700639bae12edd4f20a4f474a768bf
|
matp/regtests/mat-memory-tests.adb
|
matp/regtests/mat-memory-tests.adb
|
-----------------------------------------------------------------------
-- mat-memory-tests -- Unit tests for MAT memory
-- Copyright (C) 2014, 2015, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with MAT.Expressions;
with MAT.Frames.Targets;
with MAT.Memory.Targets;
package body MAT.Memory.Tests is
package Caller is new Util.Test_Caller (Test, "Memory");
-- Builtin and well known definition of test frames.
Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) :=
(1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc",
Test_Probe_Malloc'Access);
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free",
Test_Probe_Free'Access);
end Add_Tests;
-- ------------------------------
-- Basic consistency checks when creating the test tree
-- ------------------------------
procedure Test_Probe_Malloc (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
F : MAT.Frames.Targets.Target_Frames;
begin
S.Size := 4;
F.Insert (Frame_1_0, S.Frame);
-- Create memory slots:
-- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104]
for I in 1 .. 10 loop
M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S);
end loop;
-- Search for a memory region that does not overlap a memory slot.
M.Find (15, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [15 .. 19]");
M.Find (1, 9, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [1 .. 9]");
M.Find (105, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [105 .. 1000]");
-- Search with an overlap.
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 10, Integer (R.Length),
"Find must return 10 slots in range [1 .. 1000]");
R.Clear;
M.Find (1, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [1 .. 19]");
R.Clear;
M.Find (13, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [13 .. 19]");
R.Clear;
M.Find (100, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [100 .. 1000]");
R.Clear;
M.Find (101, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [101 .. 1000]");
end Test_Probe_Malloc;
-- ------------------------------
-- Test Probe_Free with update of memory slots.
-- ------------------------------
procedure Test_Probe_Free (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
Size : MAT.Types.Target_Size;
Id : MAT.Events.Event_Id_Type;
F : MAT.Frames.Targets.Target_Frames;
begin
S.Size := 4;
F.Insert (Frame_1_0, S.Frame);
-- Malloc followed by a free.
M.Probe_Malloc (10, S);
M.Probe_Free (10, S, Size, Id);
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slot after a free");
-- Free the same slot a second time (free error).
M.Probe_Free (10, S, Size, Id);
-- Malloc followed by a free.
M.Probe_Malloc (10, S);
M.Probe_Malloc (20, S);
M.Probe_Malloc (30, S);
M.Probe_Free (20, S, Size, Id);
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 2, Integer (R.Length),
"Find must return 2 slots after a malloc/free sequence");
end Test_Probe_Free;
end MAT.Memory.Tests;
|
-----------------------------------------------------------------------
-- mat-memory-tests -- Unit tests for MAT memory
-- Copyright (C) 2014, 2015, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with MAT.Expressions;
with MAT.Frames.Targets;
with MAT.Memory.Targets;
package body MAT.Memory.Tests is
package Caller is new Util.Test_Caller (Test, "Memory");
-- Builtin and well known definition of test frames.
Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) :=
(1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc",
Test_Probe_Malloc'Access);
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free",
Test_Probe_Free'Access);
end Add_Tests;
-- ------------------------------
-- Basic consistency checks when creating the test tree
-- ------------------------------
procedure Test_Probe_Malloc (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
F : MAT.Frames.Targets.Target_Frames;
begin
S.Size := 4;
F.Insert (Frame_1_0, S.Frame);
-- Create memory slots:
-- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104]
for I in 1 .. 10 loop
M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S);
end loop;
-- Search for a memory region that does not overlap a memory slot.
M.Find (15, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [15 .. 19]");
M.Find (1, 9, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [1 .. 9]");
M.Find (105, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [105 .. 1000]");
-- Search with an overlap.
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 10, Integer (R.Length),
"Find must return 10 slots in range [1 .. 1000]");
R.Clear;
M.Find (1, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [1 .. 19]");
R.Clear;
M.Find (13, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [13 .. 19]");
R.Clear;
M.Find (100, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [100 .. 1000]");
R.Clear;
M.Find (101, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [101 .. 1000]");
end Test_Probe_Malloc;
-- ------------------------------
-- Test Probe_Free with update of memory slots.
-- ------------------------------
procedure Test_Probe_Free (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
Size : MAT.Types.Target_Size;
Id : MAT.Events.Event_Id_Type with Unreferenced;
F : MAT.Frames.Targets.Target_Frames;
begin
S.Size := 4;
S.Event := 1;
F.Insert (Frame_1_0, S.Frame);
-- Malloc followed by a free.
M.Probe_Malloc (10, S);
Id := 12;
M.Probe_Free (10, S, Size, Id);
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slot after a free");
-- Free the same slot a second time (free error).
M.Probe_Free (10, S, Size, Id);
-- Malloc followed by a free.
M.Probe_Malloc (10, S);
M.Probe_Malloc (20, S);
M.Probe_Malloc (30, S);
M.Probe_Free (20, S, Size, Id);
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 2, Integer (R.Length),
"Find must return 2 slots after a malloc/free sequence");
end Test_Probe_Free;
end MAT.Memory.Tests;
|
Fix compilation warning and un-initialized data
|
Fix compilation warning and un-initialized data
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
6ef53ab9fbd920ab54a33f3bcedea2b66c0e446c
|
src/asf-views-nodes-jsf.adb
|
src/asf-views-nodes-jsf.adb
|
-----------------------------------------------------------------------
-- views.nodes.jsf -- JSF Core Tag Library
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Converters;
with ASF.Validators.Texts;
with ASF.Validators.Numbers;
with ASF.Components.Holders;
with ASF.Components.Core.Views;
package body ASF.Views.Nodes.Jsf is
use ASF;
use EL.Objects;
-- ------------------------------
-- Converter Tag
-- ------------------------------
-- ------------------------------
-- Create the Converter Tag
-- ------------------------------
function Create_Converter_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node;
Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"converterId");
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
if Conv = null then
Node.Error ("Missing 'converterId' attribute");
else
Node.Converter := EL.Objects.To_Object (Conv.Value);
end if;
return Node.all'Access;
end Create_Converter_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children. Get the specified converter and
-- add it to the parent component. This operation does not create any
-- new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Converter_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Converters.Converter_Access;
Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter);
begin
if not (Parent.all in Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Value_Holder");
return;
end if;
if Cvt = null then
Node.Error ("Converter was not found");
return;
end if;
declare
VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access;
begin
VH.Set_Converter (Converter => Cvt);
end;
end Build_Components;
-- ------------------------------
-- Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Validator Tag
-- ------------------------------
function Create_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node;
Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"validatorId");
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
if Vid = null then
Node.Error ("Missing 'validatorId' attribute");
else
Node.Validator := EL.Objects.To_Object (Vid.Value);
end if;
return Node.all'Access;
end Create_Validator_Tag_Node;
-- ------------------------------
-- Get the specified validator and add it to the parent component.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Validator_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Validators.Validator_Access;
V : Validators.Validator_Access;
Shared : Boolean;
begin
if not (Parent.all in Editable_Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Editable_Value_Holder");
return;
end if;
Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared);
if V = null then
Node.Error ("Validator was not found");
return;
end if;
declare
VH : constant access Editable_Value_Holder'Class
:= Editable_Value_Holder'Class (Parent.all)'Access;
begin
VH.Add_Validator (Validator => V, Shared => Shared);
end;
end Build_Components;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
procedure Get_Validator (Node : in Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
begin
Validator := Context.Get_Validator (Node.Validator);
Shared := True;
end Get_Validator;
-- ------------------------------
-- Range Validator Tag
-- ------------------------------
-- Create the Range_Validator Tag
function Create_Range_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Range_Validator_Tag_Node;
-- Get the validator instance that corresponds to the range validator.
-- Returns in <b>Validator</b> the validator instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
overriding
procedure Get_Validator (Node : in Range_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Long_Long_Integer := Long_Long_Integer'First;
Max : Long_Long_Integer := Long_Long_Integer'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context));
end if;
if Node.Maximum /= null then
Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max));
return;
end if;
Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Length Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Length_Validator Tag. Verifies that the XML node defines
-- the <b>minimum</b> or the <b>maximum</b> or both attributes.
-- ------------------------------
function Create_Length_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Length_Validator_Tag_Node;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
overriding
procedure Get_Validator (Node : in Length_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Natural := 0;
Max : Natural := Natural'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context)));
end if;
if Node.Maximum /= null then
Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context)));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Natural'Image (Min), Natural'Image (Max));
return;
end if;
Validator := Validators.Texts.Create_Length_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Attribute Tag
-- ------------------------------
-- ------------------------------
-- Create the Attribute Tag
-- ------------------------------
function Create_Attribute_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name");
Node : Attribute_Tag_Node_Access;
begin
Node := new Attribute_Tag_Node;
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Attr_Name := Attr;
Node.Value := Find_Attribute (Attributes, "value");
if Node.Attr_Name = null then
Node.Error ("Missing 'name' attribute");
else
Node.Attr.Name := Attr.Value;
end if;
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
return Node.all'Access;
end Create_Attribute_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- Adds the attribute to the component node.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Attribute_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use EL.Expressions;
begin
if Node.Attr_Name /= null and Node.Value /= null then
if Node.Value.Binding /= null then
declare
Expr : constant EL.Expressions.Expression
:= ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context);
begin
Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr);
end;
else
Parent.Set_Attribute (Def => Node.Attr'Access,
Value => Get_Value (Node.Value.all, Context));
end if;
end if;
end Build_Components;
-- ------------------------------
-- Facet Tag
-- ------------------------------
-- ------------------------------
-- Create the Facet Tag
-- ------------------------------
function Create_Facet_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Facet_Name := Find_Attribute (Attributes, "name");
if Node.Facet_Name = null then
Node.Error ("Missing 'name' attribute");
end if;
return Node.all'Access;
end Create_Facet_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the facet component of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Facet_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
begin
null;
end Build_Components;
-- ------------------------------
-- Metadata Tag
-- ------------------------------
-- ------------------------------
-- Create the Metadata Tag
-- ------------------------------
function Create_Metadata_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
return Node.all'Access;
end Create_Metadata_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as a metadata information
-- facet for the UIView parent component.
-- ------------------------------
overriding
procedure Build_Components (Node : access Metadata_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Core.Views;
begin
if not (Parent.all in UIView'Class) then
Node.Error ("Parent component of <f:metadata> must be a <f:view>");
return;
end if;
declare
UI : constant UIViewMetaData_Access := new UIViewMetaData;
begin
UIView'Class (Parent.all).Set_Metadata (UI, Node);
Build_Attributes (UI.all, Node.all, Context);
UI.Initialize (UI.Get_Context.all);
Node.Build_Children (UI.all'Access, Context);
end;
end Build_Components;
end ASF.Views.Nodes.Jsf;
|
-----------------------------------------------------------------------
-- views.nodes.jsf -- JSF Core Tag Library
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Converters;
with ASF.Validators.Texts;
with ASF.Validators.Numbers;
with ASF.Components.Holders;
with ASF.Components.Core.Views;
package body ASF.Views.Nodes.Jsf is
-- ------------------------------
-- Converter Tag
-- ------------------------------
-- ------------------------------
-- Create the Converter Tag
-- ------------------------------
function Create_Converter_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node;
Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"converterId");
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
if Conv = null then
Node.Error ("Missing 'converterId' attribute");
else
Node.Converter := EL.Objects.To_Object (Conv.Value);
end if;
return Node.all'Access;
end Create_Converter_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children. Get the specified converter and
-- add it to the parent component. This operation does not create any
-- new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Converter_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Converters.Converter_Access;
Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter);
begin
if not (Parent.all in Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Value_Holder");
return;
end if;
if Cvt = null then
Node.Error ("Converter was not found");
return;
end if;
declare
VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access;
begin
VH.Set_Converter (Converter => Cvt);
end;
end Build_Components;
-- ------------------------------
-- Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Validator Tag
-- ------------------------------
function Create_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node;
Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"validatorId");
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
if Vid = null then
Node.Error ("Missing 'validatorId' attribute");
else
Node.Validator := EL.Objects.To_Object (Vid.Value);
end if;
return Node.all'Access;
end Create_Validator_Tag_Node;
-- ------------------------------
-- Get the specified validator and add it to the parent component.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Validator_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Validators.Validator_Access;
V : Validators.Validator_Access;
Shared : Boolean;
begin
if not (Parent.all in Editable_Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Editable_Value_Holder");
return;
end if;
Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared);
if V = null then
Node.Error ("Validator was not found");
return;
end if;
declare
VH : constant access Editable_Value_Holder'Class
:= Editable_Value_Holder'Class (Parent.all)'Access;
begin
VH.Add_Validator (Validator => V, Shared => Shared);
end;
end Build_Components;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
procedure Get_Validator (Node : in Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
begin
Validator := Context.Get_Validator (Node.Validator);
Shared := True;
end Get_Validator;
-- ------------------------------
-- Range Validator Tag
-- ------------------------------
-- Create the Range_Validator Tag
function Create_Range_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Range_Validator_Tag_Node;
-- Get the validator instance that corresponds to the range validator.
-- Returns in <b>Validator</b> the validator instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
overriding
procedure Get_Validator (Node : in Range_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Long_Long_Integer := Long_Long_Integer'First;
Max : Long_Long_Integer := Long_Long_Integer'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context));
end if;
if Node.Maximum /= null then
Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max));
return;
end if;
Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Length Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Length_Validator Tag. Verifies that the XML node defines
-- the <b>minimum</b> or the <b>maximum</b> or both attributes.
-- ------------------------------
function Create_Length_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Length_Validator_Tag_Node;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
overriding
procedure Get_Validator (Node : in Length_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Natural := 0;
Max : Natural := Natural'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context)));
end if;
if Node.Maximum /= null then
Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context)));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Natural'Image (Min), Natural'Image (Max));
return;
end if;
Validator := Validators.Texts.Create_Length_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Attribute Tag
-- ------------------------------
-- ------------------------------
-- Create the Attribute Tag
-- ------------------------------
function Create_Attribute_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name");
Node : Attribute_Tag_Node_Access;
begin
Node := new Attribute_Tag_Node;
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Attr_Name := Attr;
Node.Value := Find_Attribute (Attributes, "value");
if Node.Attr_Name = null then
Node.Error ("Missing 'name' attribute");
else
Node.Attr.Name := Attr.Value;
end if;
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
return Node.all'Access;
end Create_Attribute_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- Adds the attribute to the component node.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Attribute_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use EL.Expressions;
begin
if Node.Attr_Name /= null and Node.Value /= null then
if Node.Value.Binding /= null then
declare
Expr : constant EL.Expressions.Expression
:= ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context);
begin
Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr);
end;
else
Parent.Set_Attribute (Def => Node.Attr'Access,
Value => Get_Value (Node.Value.all, Context));
end if;
end if;
end Build_Components;
-- ------------------------------
-- Facet Tag
-- ------------------------------
-- ------------------------------
-- Create the Facet Tag
-- ------------------------------
function Create_Facet_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Facet_Name := Find_Attribute (Attributes, "name");
if Node.Facet_Name = null then
Node.Error ("Missing 'name' attribute");
end if;
return Node.all'Access;
end Create_Facet_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the facet component of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Facet_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
begin
null;
end Build_Components;
-- ------------------------------
-- Metadata Tag
-- ------------------------------
-- ------------------------------
-- Create the Metadata Tag
-- ------------------------------
function Create_Metadata_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
return Node.all'Access;
end Create_Metadata_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as a metadata information
-- facet for the UIView parent component.
-- ------------------------------
overriding
procedure Build_Components (Node : access Metadata_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Core.Views;
begin
if not (Parent.all in UIView'Class) then
Node.Error ("Parent component of <f:metadata> must be a <f:view>");
return;
end if;
declare
UI : constant UIViewMetaData_Access := new UIViewMetaData;
begin
UIView'Class (Parent.all).Set_Metadata (UI, Node);
Build_Attributes (UI.all, Node.all, Context);
UI.Initialize (UI.Get_Context.all);
Node.Build_Children (UI.all'Access, Context);
end;
end Build_Components;
end ASF.Views.Nodes.Jsf;
|
Fix some compilation warnings
|
Fix some compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
12309f08817d196a4b839429d1f47a3e03929c17
|
src/gen-commands-plugins.adb
|
src/gen-commands-plugins.adb
|
-----------------------------------------------------------------------
-- gen-commands-plugins -- Plugin creation and management commands for dynamo
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with Gen.Model.Projects;
with GNAT.Command_Line;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Plugins is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Result_Dir : constant String := Generator.Get_Result_Directory;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l:") is
when ASCII.NUL => exit;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
Dir : constant String := Generator.Get_Plugin_Directory;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
if Name'Length = 0 then
Generator.Error ("Missing plugin name");
Gen.Commands.Usage;
return;
end if;
if Ada.Directories.Exists (Path) then
Generator.Error ("Plugin {0} exists already", Name);
return;
end if;
if not Ada.Directories.Exists (Dir) then
Ada.Directories.Create_Directory (Dir);
end if;
Ada.Directories.Create_Directory (Path);
Generator.Set_Result_Directory (Path);
-- Create the plugin project instance and generate its dynamo.xml file.
-- The new plugin is added to the current project so that it will be referenced.
declare
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition);
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is
Plugin : Gen.Model.Projects.Project_Definition_Access;
File : constant String := Util.Files.Compose (Path, "dynamo.xml");
begin
Project.Create_Project (Name => Name,
Path => File,
Project => Plugin);
Project.Add_Module (Plugin);
Plugin.Props.Set ("license", Project.Props.Get ("license", "none"));
Plugin.Props.Set ("author", Project.Props.Get ("author", ""));
Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", ""));
Plugin.Save (File);
end Create_Plugin;
begin
Generator.Update_Project (Create_Plugin'Access);
end;
-- Generate the new plugin content.
Generator.Set_Force_Save (False);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin");
-- And save the project dynamo.xml file which now refers to the new plugin.
Generator.Set_Result_Directory (Result_Dir);
Generator.Save_Project;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-plugin: Create a new plugin for the current project");
Put_Line ("Usage: create-plugin NAME");
New_Line;
Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME.");
end Help;
end Gen.Commands.Plugins;
|
-----------------------------------------------------------------------
-- gen-commands-plugins -- Plugin creation and management commands for dynamo
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with Gen.Model.Projects;
with GNAT.Command_Line;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Plugins is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Result_Dir : constant String := Generator.Get_Result_Directory;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l:") is
when ASCII.NUL => exit;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
declare
Name : constant String := Get_Argument;
Kind : constant String := Get_Argument;
Dir : constant String := Generator.Get_Plugin_Directory;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
if Name'Length = 0 then
Generator.Error ("Missing plugin name");
Gen.Commands.Usage;
return;
end if;
if Kind /= "ada" and Kind /= "web" and Kind /= "" then
Generator.Error ("Invalid plugin type (must be 'ada' or 'web')");
return;
end if;
if Ada.Directories.Exists (Path) then
Generator.Error ("Plugin {0} exists already", Name);
return;
end if;
if not Ada.Directories.Exists (Dir) then
Ada.Directories.Create_Directory (Dir);
end if;
Ada.Directories.Create_Directory (Path);
Generator.Set_Result_Directory (Path);
-- Create the plugin project instance and generate its dynamo.xml file.
-- The new plugin is added to the current project so that it will be referenced.
declare
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition);
procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is
Plugin : Gen.Model.Projects.Project_Definition_Access;
File : constant String := Util.Files.Compose (Path, "dynamo.xml");
begin
Project.Create_Project (Name => Name,
Path => File,
Project => Plugin);
Project.Add_Module (Plugin);
Plugin.Props.Set ("license", Project.Props.Get ("license", "none"));
Plugin.Props.Set ("author", Project.Props.Get ("author", ""));
Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", ""));
Plugin.Save (File);
end Create_Plugin;
begin
Generator.Update_Project (Create_Plugin'Access);
end;
-- Generate the new plugin content.
Generator.Set_Force_Save (False);
Generator.Set_Global ("pluginName", Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE,
"create-plugin");
if Kind /= "" then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE,
"create-plugin-" & Kind);
end if;
-- And save the project dynamo.xml file which now refers to the new plugin.
Generator.Set_Result_Directory (Result_Dir);
Generator.Save_Project;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-plugin: Create a new plugin for the current project");
Put_Line ("Usage: create-plugin NAME");
New_Line;
Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME.");
end Help;
end Gen.Commands.Plugins;
|
Add an option to create-plugin to generate an Ada or a Web plugin
|
Add an option to create-plugin to generate an Ada or a Web plugin
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
51ba6bfd2dcbdd86fca5d2ccf467ebe666525442
|
src/lumen-window-x_input.adb
|
src/lumen-window-x_input.adb
|
-- Lumen.Window.X_Input -- Receive X windows input events
--
-- Chip Richards, NiEstu, Phoenix AZ, Spring 2010
-- This code is covered by the ISC License:
--
-- Copyright © 2010, NiEstu
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- The software is provided "as is" and the author disclaims all warranties
-- with regard to this software including all implied warranties of
-- merchantability and fitness. In no event shall the author be liable for any
-- special, direct, indirect, or consequential damages or any damages
-- whatsoever resulting from loss of use, data or profits, whether in an
-- action of contract, negligence or other tortious action, arising out of or
-- in connection with the use or performance of this software.
-- Environment
with Ada.Unchecked_Deallocation;
with System;
with XArray;
package body Lumen.Window.X_Input is
---------------------------------------------------------------------------
-- Create an extensible array to hold the window list, with "chunk" size
-- 16. For many apps, this will be all they'll ever need.
package Window_List is new XArray (Data_Type => Info_Pointer, Increment => 16);
-- The window list
Windows : Window_List.Pointer := Window_List.Create;
-- For now, we assume all windows are on the same display. What we
-- *should* do is start a separate task for each display, sheesh.
Display : Internal.Display_Pointer := Internal.Null_Display_Pointer;
-- The task that reads events from the X server
task X_Input_Event_Task is
entry Startup;
end X_Input_Event_Task;
---------------------------------------------------------------------------
--
-- Package objects
--
---------------------------------------------------------------------------
-- A semaphore that allows Shutdown to abort the event task
protected Shutdown_Signal is
procedure Set;
entry Wait;
private
Is_Set : boolean := false;
end Shutdown_Signal;
-- Simple binary semaphore, used to tell the event task that the app is
-- quitting
protected body Shutdown_Signal is
-- Indicate that a shutdown has occurred
procedure Set is
begin -- Set
Is_Set := true;
end Set;
-- Block until the signal is set, then clear it
entry Wait when Is_Set is
begin -- Wait
Is_Set := false;
end Wait;
end Shutdown_Signal;
---------------------------------------------------------------------------
--
-- Package subroutines
--
---------------------------------------------------------------------------
-- Terminates the X input events task
procedure Shutdown is
use Lumen.Internal;
-- Binding to XUnmapWindow, which creates a final event needed to get
-- the event task unstuck, and XFlush, to push the event through
-- procedure X_Unmap_Window (Display : in Display_Pointer; Window : in Window_ID);
-- pragma Import (C, X_Unmap_Window, "XUnmapWindow");
procedure X_Flush (Display : in Display_Pointer);
pragma Import (C, X_Flush, "XFlush");
-- Win : Window_ID := Windows.Data (Windows.Data'First).Window; -- should be the only one left
begin -- Shutdown
-- Terminate X input event task
-- X_Unmap_Window (Display, Win);
X_Flush (Display);
Shutdown_Signal.Set;
end Shutdown;
---------------------------------------------------------------------------
--
-- The event task, reads events from the X server, then sends them to the app
--
---------------------------------------------------------------------------
task body X_Input_Event_Task is
use type Internal.Window_ID;
X_Event : Internal.X_Event_Data;
begin -- X_Input_Event_Task
-- Wait until there's a display to use
accept Startup;
loop
-- Wait for an event to come from the X server, or for a shutdown
-- signal to arrive
select
Shutdown_Signal.Wait;
exit;
then abort
Internal.X_Next_Event (Display, X_Event'Address);
end select;
-- Find which window it came from; events coming from unregistered
-- windows are ignored
for W in Windows.Data'First .. Windows.Data'First + Windows.Current - 1 loop
if Windows.Data (W).Window = X_Event.Window then
-- Found it, stick the event on the its event queue
Windows.Data (W).Events.Enqueue ((Which => Internal.X_Input_Event, X => X_Event));
end if;
end loop;
end loop;
end X_Input_Event_Task;
---------------------------------------------------------------------------
--
-- Public subroutines
--
---------------------------------------------------------------------------
-- Register a new window with the X input event task
procedure Add_Window (Win : in Handle) is
begin -- Add_Window
-- Add the new window
Window_List.Append (Windows, Win.Info);
-- Tuck away the display pointer of the first window we add, for the
-- task to use. Once we have a display, start the event task looking
-- for events on it. This will need to change when we support multiple
-- displays.
declare
use type Internal.Display_Pointer;
begin
if Display = Internal.Null_Display_Pointer then
Display := Win.Info.Display;
X_Input_Event_Task.Startup;
end if;
end;
end Add_Window;
---------------------------------------------------------------------------
-- De-register a window with the X input event task
procedure Drop_Window (Win : in Handle) is
Found : Natural := Window_List.Find (Windows, Win.Info);
begin -- Drop_Window
-- If window found, otherwise just ignore the request
if Found > 0 then
-- Found it. First, see if it's the last one left
if Windows.Current = Windows.Data'First then
-- Dropping last window, so shut down the events task
Shutdown;
else
-- Found it, but it's not the last window, so just remove it
-- from the list
Window_List.Delete (Windows, Found);
end if;
end if;
end Drop_Window;
---------------------------------------------------------------------------
end Lumen.Window.X_Input;
|
-- Lumen.Window.X_Input -- Receive X windows input events
--
-- Chip Richards, NiEstu, Phoenix AZ, Spring 2010
-- This code is covered by the ISC License:
--
-- Copyright © 2010, NiEstu
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- The software is provided "as is" and the author disclaims all warranties
-- with regard to this software including all implied warranties of
-- merchantability and fitness. In no event shall the author be liable for any
-- special, direct, indirect, or consequential damages or any damages
-- whatsoever resulting from loss of use, data or profits, whether in an
-- action of contract, negligence or other tortious action, arising out of or
-- in connection with the use or performance of this software.
-- Environment
with Ada.Unchecked_Deallocation;
with System;
with XArray;
package body Lumen.Window.X_Input is
---------------------------------------------------------------------------
-- Create an extensible array to hold the window list, with "chunk" size
-- 16. For many apps, this will be all they'll ever need.
package Window_List is new XArray (Data_Type => Info_Pointer, Increment => 16);
-- The window list
Windows : Window_List.Pointer := Window_List.Create;
-- For now, we assume all windows are on the same display. What we
-- *should* do is start a separate task for each display, sheesh.
Display : Internal.Display_Pointer := Internal.Null_Display_Pointer;
-- The task that reads events from the X server
task X_Input_Event_Task is
entry Startup;
end X_Input_Event_Task;
---------------------------------------------------------------------------
--
-- Package objects
--
---------------------------------------------------------------------------
-- A semaphore that allows Shutdown to abort the event task
protected Shutdown_Signal is
procedure Set;
entry Wait;
private
Is_Set : boolean := false;
end Shutdown_Signal;
-- Simple binary semaphore, used to tell the event task that the app is
-- quitting
protected body Shutdown_Signal is
-- Indicate that a shutdown has occurred
procedure Set is
begin -- Set
Is_Set := true;
end Set;
-- Block until the signal is set, then clear it
entry Wait when Is_Set is
begin -- Wait
Is_Set := false;
end Wait;
end Shutdown_Signal;
---------------------------------------------------------------------------
--
-- Package subroutines
--
---------------------------------------------------------------------------
-- Terminates the X input events task
procedure Shutdown is
use Lumen.Internal;
-- Binding to XUnmapWindow, which creates a final event needed to get
-- the event task unstuck, and XFlush, to push the event through
-- procedure X_Unmap_Window (Display : in Display_Pointer; Window : in Window_ID);
-- pragma Import (C, X_Unmap_Window, "XUnmapWindow");
procedure X_Flush (Display : in Display_Pointer);
pragma Import (C, X_Flush, "XFlush");
-- Win : Window_ID := Windows.Data (Windows.Data'First).Window; -- should be the only one left
begin -- Shutdown
-- Terminate X input event task
-- X_Unmap_Window (Display, Win);
X_Flush (Display);
Shutdown_Signal.Set;
end Shutdown;
---------------------------------------------------------------------------
--
-- The event task, reads events from the X server, then sends them to the app
--
---------------------------------------------------------------------------
task body X_Input_Event_Task is
use type Internal.Window_ID;
X_Event : Internal.X_Event_Data;
begin -- X_Input_Event_Task
-- Wait until there's a display to use, or if the app quits before
-- creating a window then we just quit this task too
select
accept Startup;
or
terminate;
end select;
loop
-- Wait for an event to come from the X server, or for a shutdown
-- signal to arrive
select
Shutdown_Signal.Wait;
exit;
then abort
Internal.X_Next_Event (Display, X_Event'Address);
end select;
-- Find which window it came from; events coming from unregistered
-- windows are ignored
for W in Windows.Data'First .. Windows.Data'First + Windows.Current - 1 loop
if Windows.Data (W).Window = X_Event.Window then
-- Found it, stick the event on the its event queue
Windows.Data (W).Events.Enqueue ((Which => Internal.X_Input_Event, X => X_Event));
end if;
end loop;
end loop;
end X_Input_Event_Task;
---------------------------------------------------------------------------
--
-- Public subroutines
--
---------------------------------------------------------------------------
-- Register a new window with the X input event task
procedure Add_Window (Win : in Handle) is
begin -- Add_Window
-- Add the new window
Window_List.Append (Windows, Win.Info);
-- Tuck away the display pointer of the first window we add, for the
-- task to use. Once we have a display, start the event task looking
-- for events on it. This will need to change when we support multiple
-- displays.
declare
use type Internal.Display_Pointer;
begin
if Display = Internal.Null_Display_Pointer then
Display := Win.Info.Display;
X_Input_Event_Task.Startup;
end if;
end;
end Add_Window;
---------------------------------------------------------------------------
-- De-register a window with the X input event task
procedure Drop_Window (Win : in Handle) is
Found : Natural := Window_List.Find (Windows, Win.Info);
begin -- Drop_Window
-- If window found, otherwise just ignore the request
if Found > 0 then
-- Found it. First, see if it's the last one left
if Windows.Current = Windows.Data'First then
-- Dropping last window, so shut down the events task
Shutdown;
else
-- Found it, but it's not the last window, so just remove it
-- from the list
Window_List.Delete (Windows, Found);
end if;
end if;
end Drop_Window;
---------------------------------------------------------------------------
end Lumen.Window.X_Input;
|
Use a selective accept for the event task's startup, because it's the right thing to do
|
Use a selective accept for the event task's startup, because it's the right thing to do
|
Ada
|
isc
|
darkestkhan/lumen,darkestkhan/lumen2
|
3d649c52302f22085d57e3422b43f295ed936779
|
src/gen-commands-database.ads
|
src/gen-commands-database.ads
|
-----------------------------------------------------------------------
-- gen-commands-database -- Database creation from application model
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Database is
-- ------------------------------
-- Database Creation Command
-- ------------------------------
-- This command creates the database for the application.
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Database;
|
-----------------------------------------------------------------------
-- gen-commands-database -- Database creation from application model
-- Copyright (C) 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Database is
-- ------------------------------
-- Database Creation Command
-- ------------------------------
-- This command creates the database for the application.
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Database;
|
Update to use the new command implementation
|
Update to use the new command implementation
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
85f94411892cf0a8b607a0effb32138ffd8bbe23
|
mat/src/matp.adb
|
mat/src/matp.adb
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Util.Log.Loggers;
with GNAT.Sockets;
with MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
with MAT.Readers.Streams.Sockets;
procedure Matp is
Target : MAT.Targets.Target_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
Address : GNAT.Sockets.Sock_Addr_Type;
begin
Util.Log.Loggers.Initialize ("matp.properties");
Target.Console (Console'Unchecked_Access);
Address.Addr := GNAT.Sockets.Any_Inet_Addr;
Address.Port := 4096;
Server.Start (Address);
MAT.Commands.Interactive (Target);
Server.Stop;
exception
when Ada.IO_Exceptions.End_Error =>
Server.Stop;
end Matp;
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Util.Log.Loggers;
with GNAT.Sockets;
with MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
with MAT.Readers.Streams.Sockets;
procedure Matp is
Target : MAT.Targets.Target_Type;
Options : MAT.Commands.Options_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
Address : GNAT.Sockets.Sock_Addr_Type;
begin
Util.Log.Loggers.Initialize ("matp.properties");
Target.Console (Console'Unchecked_Access);
MAT.Commands.Initialize_Options (Target, Options);
Server.Start (Options.Address);
MAT.Commands.Interactive (Target);
Server.Stop;
exception
when Ada.IO_Exceptions.End_Error =>
Server.Stop;
end Matp;
|
Use the Initialize_Options procedure to configure
|
Use the Initialize_Options procedure to configure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
0299c8d378e7b116f23f78f444c55c1e6e63fe8f
|
src/security-controllers.ads
|
src/security-controllers.ads
|
-----------------------------------------------------------------------
-- security-controllers -- Controllers to verify a security permission
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
-- == Security Controller ==
-- The <b>Security.Controllers</b> package defines the security controller used to
-- verify that a given permission is granted. A security controller uses the security
-- context and other controller specific and internal data to verify that the permission
-- is granted.
--
-- To implement a new security controller, one must:
--
-- * Define a type that implements the <b>Controller</b> interface with the
-- <b>Has_Permission</b> operation
-- * Write a function to allocate instances of the given <b>Controller</b> type
-- * Register the function under a unique name by using <b>Register_Controller</b>
--
-- Security controller instances are created when the security policy rules are parsed.
-- These instances are shared across possibly several concurrent requests.
package Security.Controllers is
Invalid_Controller : exception;
-- ------------------------------
-- Security Controller interface
-- ------------------------------
type Controller is limited interface;
type Controller_Access is access all Controller'Class;
-- Checks whether the permission defined by the <b>Handler</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Handler : in Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is abstract;
type Controller_Factory is not null access function return Controller_Access;
-- To keep this implementation simple, a maximum of 32 security controller factory
-- can be registered. ASF provides one based on roles. AWA provides another one
-- based on entity ACLs.
MAX_CONTROLLER_FACTORY : constant Positive := 32;
-- Register in a global table the controller factory under the name <b>Name</b>.
-- When this factory is used, the <b>Factory</b> operation will be called to
-- create new instances of the controller.
procedure Register_Controller (Name : in String;
Factory : in Controller_Factory);
-- Create a security controller by using the controller factory registered under
-- the name <b>Name</b>.
-- Raises <b>Invalid_Controller</b> if the name is not recognized.
function Create_Controller (Name : in String) return Controller_Access;
end Security.Controllers;
|
-----------------------------------------------------------------------
-- security-controllers -- Controllers to verify a security permission
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
with Security.Permissions;
-- == Security Controller ==
-- The <b>Security.Controllers</b> package defines the security controller used to
-- verify that a given permission is granted. A security controller uses the security
-- context and other controller specific and internal data to verify that the permission
-- is granted.
--
-- To implement a new security controller, one must:
--
-- * Define a type that implements the <b>Controller</b> interface with the
-- <b>Has_Permission</b> operation
-- * Write a function to allocate instances of the given <b>Controller</b> type
-- * Register the function under a unique name by using <b>Register_Controller</b>
--
-- Security controller instances are created when the security policy rules are parsed.
-- These instances are shared across possibly several concurrent requests.
package Security.Controllers is
Invalid_Controller : exception;
-- ------------------------------
-- Security Controller interface
-- ------------------------------
type Controller is limited interface;
type Controller_Access is access all Controller'Class;
-- Checks whether the permission defined by the <b>Handler</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Handler : in Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is abstract;
type Controller_Factory is not null access function return Controller_Access;
-- To keep this implementation simple, a maximum of 32 security controller factory
-- can be registered. ASF provides one based on roles. AWA provides another one
-- based on entity ACLs.
MAX_CONTROLLER_FACTORY : constant Positive := 32;
-- Register in a global table the controller factory under the name <b>Name</b>.
-- When this factory is used, the <b>Factory</b> operation will be called to
-- create new instances of the controller.
procedure Register_Controller (Name : in String;
Factory : in Controller_Factory);
-- Create a security controller by using the controller factory registered under
-- the name <b>Name</b>.
-- Raises <b>Invalid_Controller</b> if the name is not recognized.
function Create_Controller (Name : in String) return Controller_Access;
end Security.Controllers;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
8ffdef0b615f472e313ddd181d2637b0a946be2d
|
src/util-processes-tools.adb
|
src/util-processes-tools.adb
|
-----------------------------------------------------------------------
-- util-processes-tools -- System specific and low level operations
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Systems.Os;
with Util.Streams.Texts;
with Util.Streams.Pipes;
package body Util.Processes.Tools is
-- ------------------------------
-- Execute the command and append the output in the vector array.
-- The program output is read line by line and the standard input is closed.
-- Return the program exit status.
-- ------------------------------
procedure Execute (Command : in String;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Proc : aliased Util.Streams.Pipes.Pipe_Stream;
Text : Util.Streams.Texts.Reader_Stream;
begin
Proc.Add_Close (Util.Systems.Os.STDIN_FILENO);
Text.Initialize (Proc'Unchecked_Access);
Proc.Open (Command, Util.Processes.READ);
while not Text.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Text.Read_Line (Line, Strip => True);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Output.Append (Ada.Strings.Unbounded.To_String (Line));
end;
end loop;
Proc.Close;
Status := Proc.Get_Exit_Status;
end Execute;
end Util.Processes.Tools;
|
-----------------------------------------------------------------------
-- util-processes-tools -- System specific and low level operations
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Systems.Os;
with Util.Streams.Texts;
package body Util.Processes.Tools is
procedure Execute (Command : in String;
Process : in out Util.Streams.Pipes.Pipe_Stream;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Text : Util.Streams.Texts.Reader_Stream;
begin
Text.Initialize (Process'Unchecked_Access);
Process.Open (Command, Util.Processes.READ);
while not Text.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Text.Read_Line (Line, Strip => True);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Output.Append (Ada.Strings.Unbounded.To_String (Line));
end;
end loop;
Process.Close;
Status := Process.Get_Exit_Status;
end Execute;
-- ------------------------------
-- Execute the command and append the output in the vector array.
-- The program output is read line by line and the standard input is closed.
-- Return the program exit status.
-- ------------------------------
procedure Execute (Command : in String;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Proc : Util.Streams.Pipes.Pipe_Stream;
begin
Proc.Add_Close (Util.Systems.Os.STDIN_FILENO);
Execute (Command, Proc, Output, Status);
end Execute;
procedure Execute (Command : in String;
Input_Path : in String;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Proc : Util.Streams.Pipes.Pipe_Stream;
begin
Proc.Set_Input_Stream (Input_Path);
Execute (Command, Proc, Output, Status);
end Execute;
end Util.Processes.Tools;
|
Implement more Execute procedures
|
Implement more Execute procedures
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f00e3b78e8fed4be14cf1b956f7de9150638c76a
|
awa/plugins/awa-questions/src/awa-questions-services.ads
|
awa/plugins/awa-questions/src/awa-questions-services.ads
|
-----------------------------------------------------------------------
-- awa-questions-services -- Service services
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with Security.Permissions;
with AWA.Modules;
with AWA.Questions.Models;
package AWA.Questions.Services is
-- Define the permissions.
package ACL_Create_Questions is new Security.Permissions.Definition ("question-create");
package ACL_Delete_Questions is new Security.Permissions.Definition ("question-delete");
package ACL_Update_Questions is new Security.Permissions.Definition ("question-update");
package ACL_Answer_Questions is new Security.Permissions.Definition ("answer-create");
-- The maximum length for a short description.
SHORT_DESCRIPTION_LENGTH : constant Positive := 200;
-- ------------------------------
-- Service services
-- ------------------------------
type Question_Service is new AWA.Modules.Module_Manager with private;
type Question_Service_Access is access all Question_Service'Class;
-- Create or save the question.
procedure Save_Question (Model : in Question_Service;
Question : in out AWA.Questions.Models.Question_Ref'Class);
-- Delete the question.
procedure Delete_Question (Model : in Question_Service;
Question : in out AWA.Questions.Models.Question_Ref'Class);
-- Load the question.
procedure Load_Question (Model : in Question_Service;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier);
-- Create or save the answer.
procedure Save_Answer (Model : in Question_Service;
Question : in AWA.Questions.Models.Question_Ref'Class;
Answer : in out AWA.Questions.Models.Answer_Ref'Class);
-- Load the answer.
procedure Load_Answer (Model : in Question_Service;
Answer : in out AWA.Questions.Models.Answer_Ref'Class;
Id : in ADO.Identifier);
private
type Question_Service is new AWA.Modules.Module_Manager with null record;
end AWA.Questions.Services;
|
-----------------------------------------------------------------------
-- awa-questions-services -- Service services
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with Security.Permissions;
with AWA.Modules;
with AWA.Questions.Models;
package AWA.Questions.Services is
-- Define the permissions.
package ACL_Create_Questions is new Security.Permissions.Definition ("question-create");
package ACL_Delete_Questions is new Security.Permissions.Definition ("question-delete");
package ACL_Update_Questions is new Security.Permissions.Definition ("question-update");
package ACL_Answer_Questions is new Security.Permissions.Definition ("answer-create");
-- The maximum length for a short description.
SHORT_DESCRIPTION_LENGTH : constant Positive := 200;
-- ------------------------------
-- Service services
-- ------------------------------
type Question_Service is new AWA.Modules.Module_Manager with private;
type Question_Service_Access is access all Question_Service'Class;
-- Create or save the question.
procedure Save_Question (Model : in Question_Service;
Question : in out AWA.Questions.Models.Question_Ref'Class);
-- Delete the question.
procedure Delete_Question (Model : in Question_Service;
Question : in out AWA.Questions.Models.Question_Ref'Class);
-- Load the question.
procedure Load_Question (Model : in Question_Service;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier);
-- Create or save the answer.
procedure Save_Answer (Model : in Question_Service;
Question : in AWA.Questions.Models.Question_Ref'Class;
Answer : in out AWA.Questions.Models.Answer_Ref'Class);
-- Load the answer.
procedure Load_Answer (Model : in Question_Service;
Answer : in out AWA.Questions.Models.Answer_Ref'Class;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier);
private
type Question_Service is new AWA.Modules.Module_Manager with null record;
end AWA.Questions.Services;
|
Load the question associated with the answer
|
Load the question associated with the answer
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
937c3409d0736cf8f68b5ef7fde8941b88ef9028
|
boards/stm32_common/dma2d/stm32-dma2d_bitmap.adb
|
boards/stm32_common/dma2d/stm32-dma2d_bitmap.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with Cortex_M.Cache; use Cortex_M.Cache;
with STM32.DMA2D; use STM32.DMA2D;
package body STM32.DMA2D_Bitmap is
function To_DMA2D_CM is new Ada.Unchecked_Conversion
(HAL.Bitmap.Bitmap_Color_Mode, STM32.DMA2D.DMA2D_Color_Mode);
function To_DMA2D_Color is new Ada.Unchecked_Conversion
(HAL.Bitmap.Bitmap_Color, STM32.DMA2D.DMA2D_Color);
---------------------
-- To_DMA2D_Buffer --
---------------------
function To_DMA2D_Buffer
(Buffer : HAL.Bitmap.Bitmap_Buffer'Class) return DMA2D_Buffer
is
Color_Mode : constant DMA2D_Color_Mode :=
To_DMA2D_CM (Buffer.Color_Mode);
Ret : DMA2D_Buffer (Color_Mode);
begin
Ret.Addr := Buffer.Addr;
Ret.Width := (if Buffer.Swapped then Buffer.Height
else Buffer.Width);
Ret.Height := (if Buffer.Swapped then Buffer.Width
else Buffer.Height);
return Ret;
end To_DMA2D_Buffer;
---------------
-- Set_Pixel --
---------------
overriding procedure Set_Pixel
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural;
Value : UInt32)
is
begin
DMA2D_Wait_Transfer;
HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel (X, Y, Value);
end Set_Pixel;
---------------------
-- Set_Pixel_Blend --
---------------------
overriding procedure Set_Pixel_Blend
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural;
Value : HAL.Bitmap.Bitmap_Color)
is
DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer);
begin
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
if not Buffer.Swapped then
DMA2D_Set_Pixel_Blend
(Buffer => DMA_Buf,
X => X,
Y => Y,
Color => To_DMA2D_Color (Value));
else
DMA2D_Set_Pixel_Blend
(Buffer => DMA_Buf,
X => Y,
Y => Buffer.Width - X - 1,
Color => To_DMA2D_Color (Value));
end if;
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel_Blend (X, Y, Value);
end if;
end Set_Pixel_Blend;
---------------
-- Get_Pixel --
---------------
overriding function Get_Pixel
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural) return UInt32
is
begin
DMA2D_Wait_Transfer;
return HAL.Bitmap.Bitmap_Buffer (Buffer).Get_Pixel (X, Y);
end Get_Pixel;
----------
-- Fill --
----------
overriding procedure Fill
(Buffer : DMA2D_Bitmap_Buffer;
Color : UInt32)
is
begin
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
DMA2D_Fill (To_DMA2D_Buffer (Buffer), Color, True);
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Fill (Color);
end if;
end Fill;
---------------
-- Fill_Rect --
---------------
overriding procedure Fill_Rect
(Buffer : DMA2D_Bitmap_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer)
is
DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer);
W, H : Integer;
begin
if X >= Buffer.Width or else Y >= Buffer.Height then
return;
end if;
if X + Width >= Buffer.Width then
W := Buffer.Width - X - 1;
else
W := Width;
end if;
if Y + Height >= Buffer.Height then
H := Buffer.Height - Y - 1;
else
H := Height;
end if;
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
if not Buffer.Swapped then
DMA2D_Fill_Rect
(DMA_Buf,
Color => Color,
X => X,
Y => Y,
Width => W,
Height => H);
else
DMA2D_Fill_Rect
(DMA_Buf,
Color => Color,
X => Y,
Y => Buffer.Width - X - W,
Width => H,
Height => W);
end if;
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Fill_Rect
(Color, X, Y, Width, Height);
end if;
end Fill_Rect;
---------------
-- Copy_Rect --
---------------
overriding procedure Copy_Rect
(Src_Buffer : HAL.Bitmap.Bitmap_Buffer'Class;
X_Src : Natural;
Y_Src : Natural;
Dst_Buffer : DMA2D_Bitmap_Buffer;
X_Dst : Natural;
Y_Dst : Natural;
Bg_Buffer : HAL.Bitmap.Bitmap_Buffer'Class;
X_Bg : Natural;
Y_Bg : Natural;
Width : Natural;
Height : Natural;
Synchronous : Boolean)
is
use type System.Address;
DMA_Buf_Src : constant DMA2D_Buffer := To_DMA2D_Buffer (Src_Buffer);
DMA_Buf_Dst : constant DMA2D_Buffer := To_DMA2D_Buffer (Dst_Buffer);
DMA_Buf_Bg : DMA2D_Buffer := To_DMA2D_Buffer (Bg_Buffer);
X0_Src : Natural := X_Src;
Y0_Src : Natural := Y_Src;
X0_Dst : Natural := X_Dst;
Y0_Dst : Natural := Y_Dst;
X0_Bg : Natural := X_Bg;
Y0_Bg : Natural := Y_Bg;
W : Natural := Width;
H : Natural := Height;
begin
if Src_Buffer.Swapped then
X0_Src := Y_Src;
Y0_Src := Src_Buffer.Width - X_Src - Width;
end if;
if Dst_Buffer.Swapped then
X0_Dst := Y_Dst;
Y0_Dst := Dst_Buffer.Width - X_Dst - Width;
W := Height;
H := Width;
end if;
if Bg_Buffer.Addr = System.Null_Address then
DMA_Buf_Bg := STM32.DMA2D.Null_Buffer;
X0_Bg := 0;
Y0_Bg := 0;
elsif Bg_Buffer.Swapped then
X0_Bg := Y_Bg;
Y0_Bg := Bg_Buffer.Width - X_Bg - Width;
end if;
Cortex_M.Cache.Clean_DCache (Src_Buffer.Addr, Src_Buffer.Buffer_Size);
DMA2D_Copy_Rect
(DMA_Buf_Src, X0_Src, Y0_Src,
DMA_Buf_Dst, X0_Dst, Y0_Dst,
DMA_Buf_Bg, X0_Bg, Y0_Bg,
W, H,
Synchronous => Synchronous);
end Copy_Rect;
-------------------
-- Wait_Transfer --
-------------------
overriding procedure Wait_Transfer (Buffer : DMA2D_Bitmap_Buffer)
is
begin
DMA2D_Wait_Transfer;
Cortex_M.Cache.Clean_Invalidate_DCache
(Start => Buffer.Addr,
Len => Buffer.Buffer_Size);
end Wait_Transfer;
end STM32.DMA2D_Bitmap;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with Cortex_M.Cache; use Cortex_M.Cache;
with STM32.DMA2D; use STM32.DMA2D;
package body STM32.DMA2D_Bitmap is
function To_DMA2D_CM is new Ada.Unchecked_Conversion
(HAL.Bitmap.Bitmap_Color_Mode, STM32.DMA2D.DMA2D_Color_Mode);
function To_DMA2D_Color is new Ada.Unchecked_Conversion
(HAL.Bitmap.Bitmap_Color, STM32.DMA2D.DMA2D_Color);
---------------------
-- To_DMA2D_Buffer --
---------------------
function To_DMA2D_Buffer
(Buffer : HAL.Bitmap.Bitmap_Buffer'Class) return DMA2D_Buffer
is
Color_Mode : constant DMA2D_Color_Mode :=
To_DMA2D_CM (Buffer.Color_Mode);
Ret : DMA2D_Buffer (Color_Mode);
begin
Ret.Addr := Buffer.Addr;
Ret.Width := (if Buffer.Swapped then Buffer.Height
else Buffer.Width);
Ret.Height := (if Buffer.Swapped then Buffer.Width
else Buffer.Height);
return Ret;
end To_DMA2D_Buffer;
---------------
-- Set_Pixel --
---------------
overriding procedure Set_Pixel
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural;
Value : UInt32)
is
begin
DMA2D_Wait_Transfer;
HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel (X, Y, Value);
end Set_Pixel;
---------------------
-- Set_Pixel_Blend --
---------------------
overriding procedure Set_Pixel_Blend
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural;
Value : HAL.Bitmap.Bitmap_Color)
is
DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer);
begin
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
if not Buffer.Swapped then
DMA2D_Set_Pixel_Blend
(Buffer => DMA_Buf,
X => X,
Y => Y,
Color => To_DMA2D_Color (Value));
else
DMA2D_Set_Pixel_Blend
(Buffer => DMA_Buf,
X => Y,
Y => Buffer.Width - X - 1,
Color => To_DMA2D_Color (Value));
end if;
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel_Blend (X, Y, Value);
end if;
end Set_Pixel_Blend;
---------------
-- Get_Pixel --
---------------
overriding function Get_Pixel
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural) return UInt32
is
begin
DMA2D_Wait_Transfer;
return HAL.Bitmap.Bitmap_Buffer (Buffer).Get_Pixel (X, Y);
end Get_Pixel;
----------
-- Fill --
----------
overriding procedure Fill
(Buffer : DMA2D_Bitmap_Buffer;
Color : UInt32)
is
begin
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
DMA2D_Fill (To_DMA2D_Buffer (Buffer), Color, True);
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Fill (Color);
end if;
end Fill;
---------------
-- Fill_Rect --
---------------
overriding procedure Fill_Rect
(Buffer : DMA2D_Bitmap_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer)
is
DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer);
W, H : Integer;
begin
if X >= Buffer.Width or else Y >= Buffer.Height then
return;
end if;
if X + Width > Buffer.Width then
W := Buffer.Width - X;
else
W := Width;
end if;
if Y + Height > Buffer.Height then
H := Buffer.Height - Y;
else
H := Height;
end if;
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
if not Buffer.Swapped then
DMA2D_Fill_Rect
(DMA_Buf,
Color => Color,
X => X,
Y => Y,
Width => W,
Height => H);
else
DMA2D_Fill_Rect
(DMA_Buf,
Color => Color,
X => Y,
Y => Buffer.Width - X - W,
Width => H,
Height => W);
end if;
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Fill_Rect
(Color, X, Y, Width, Height);
end if;
end Fill_Rect;
---------------
-- Copy_Rect --
---------------
overriding procedure Copy_Rect
(Src_Buffer : HAL.Bitmap.Bitmap_Buffer'Class;
X_Src : Natural;
Y_Src : Natural;
Dst_Buffer : DMA2D_Bitmap_Buffer;
X_Dst : Natural;
Y_Dst : Natural;
Bg_Buffer : HAL.Bitmap.Bitmap_Buffer'Class;
X_Bg : Natural;
Y_Bg : Natural;
Width : Natural;
Height : Natural;
Synchronous : Boolean)
is
use type System.Address;
DMA_Buf_Src : constant DMA2D_Buffer := To_DMA2D_Buffer (Src_Buffer);
DMA_Buf_Dst : constant DMA2D_Buffer := To_DMA2D_Buffer (Dst_Buffer);
DMA_Buf_Bg : DMA2D_Buffer := To_DMA2D_Buffer (Bg_Buffer);
X0_Src : Natural := X_Src;
Y0_Src : Natural := Y_Src;
X0_Dst : Natural := X_Dst;
Y0_Dst : Natural := Y_Dst;
X0_Bg : Natural := X_Bg;
Y0_Bg : Natural := Y_Bg;
W : Natural := Width;
H : Natural := Height;
begin
if Src_Buffer.Swapped then
X0_Src := Y_Src;
Y0_Src := Src_Buffer.Width - X_Src - Width;
end if;
if Dst_Buffer.Swapped then
X0_Dst := Y_Dst;
Y0_Dst := Dst_Buffer.Width - X_Dst - Width;
W := Height;
H := Width;
end if;
if Bg_Buffer.Addr = System.Null_Address then
DMA_Buf_Bg := STM32.DMA2D.Null_Buffer;
X0_Bg := 0;
Y0_Bg := 0;
elsif Bg_Buffer.Swapped then
X0_Bg := Y_Bg;
Y0_Bg := Bg_Buffer.Width - X_Bg - Width;
end if;
Cortex_M.Cache.Clean_DCache (Src_Buffer.Addr, Src_Buffer.Buffer_Size);
DMA2D_Copy_Rect
(DMA_Buf_Src, X0_Src, Y0_Src,
DMA_Buf_Dst, X0_Dst, Y0_Dst,
DMA_Buf_Bg, X0_Bg, Y0_Bg,
W, H,
Synchronous => Synchronous);
end Copy_Rect;
-------------------
-- Wait_Transfer --
-------------------
overriding procedure Wait_Transfer (Buffer : DMA2D_Bitmap_Buffer)
is
begin
DMA2D_Wait_Transfer;
Cortex_M.Cache.Clean_Invalidate_DCache
(Start => Buffer.Addr,
Len => Buffer.Buffer_Size);
end Wait_Transfer;
end STM32.DMA2D_Bitmap;
|
Fix check for overflow in the DMA2D driver (FillRect).
|
Fix check for overflow in the DMA2D driver (FillRect).
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library
|
a639afb57cdaabdf24d1144234d1aa231f50f7d6
|
src/atlas-server.adb
|
src/atlas-server.adb
|
-----------------------------------------------------------------------
-- Atlas-server -- Application server
-- Copyright (C) 2011, 2012, 2013, 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.Exceptions;
with Util.Log.Loggers;
with AWS.Config.Set;
with ASF.Server.Web;
with AWA.Setup.Applications;
with Atlas.Applications;
procedure Atlas.Server is
procedure Configure (Config : in out AWS.Config.Object);
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server");
App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application;
WS : ASF.Server.Web.AWS_Container;
procedure Setup is
new AWA.Setup.Applications.Configure (Atlas.Applications.Application'Class,
Atlas.Applications.Application_Access,
Atlas.Applications.Initialize);
procedure Configure (Config : in out AWS.Config.Object) is
begin
AWS.Config.Set.Input_Line_Size_Limit (1_000_000);
AWS.Config.Set.Max_Connection (Config, 2);
AWS.Config.Set.Accept_Queue_Size (Config, 100);
AWS.Config.Set.Send_Buffer_Size (Config, 128 * 1024);
AWS.Config.Set.Upload_Size_Limit (Config, 100_000_000);
end Configure;
begin
WS.Configure (Configure'Access);
WS.Start;
Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html",
Atlas.Applications.CONTEXT_PATH);
Setup (WS, App, "atlas", Atlas.Applications.CONTEXT_PATH);
delay 365.0 * 24.0 * 3600.0;
App.Close;
exception
when E : others =>
Log.Error ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Atlas.Server;
|
-----------------------------------------------------------------------
-- atlas-server -- Application server
-- Copyright (C) 2011, 2012, 2013, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Log.Loggers;
with AWS.Net.SSL;
with AWS.Config.Set;
with ASF.Server.Web;
with AWA.Setup.Applications;
with Atlas.Applications;
procedure Atlas.Server is
procedure Configure (Config : in out AWS.Config.Object);
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server");
App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application;
WS : ASF.Server.Web.AWS_Container;
procedure Setup is
new AWA.Setup.Applications.Configure (Atlas.Applications.Application'Class,
Atlas.Applications.Application_Access,
Atlas.Applications.Initialize);
procedure Configure (Config : in out AWS.Config.Object) is
begin
AWS.Config.Set.Input_Line_Size_Limit (1_000_000);
AWS.Config.Set.Max_Connection (Config, 2);
AWS.Config.Set.Accept_Queue_Size (Config, 100);
AWS.Config.Set.Send_Buffer_Size (Config, 128 * 1024);
AWS.Config.Set.Upload_Size_Limit (Config, 100_000_000);
end Configure;
begin
WS.Configure (Configure'Access);
WS.Start;
Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html",
Atlas.Applications.CONTEXT_PATH);
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OAuth2/OpenID connector to "
& "connect to OAuth2/OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
end if;
Setup (WS, App, "atlas", Atlas.Applications.CONTEXT_PATH);
delay 365.0 * 24.0 * 3600.0;
App.Close;
exception
when E : others =>
Log.Error ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Atlas.Server;
|
Check that AWS supports SSL and report an error message if this is not the case
|
Check that AWS supports SSL and report an error message if this is not the case
|
Ada
|
apache-2.0
|
stcarrez/atlas
|
f0e0ffcd45cb1429d37b44972f27d6085d3eacf8
|
src/util-streams.adb
|
src/util-streams.adb
|
-----------------------------------------------------------------------
-- Util.Streams -- Stream utilities
-- 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.
-----------------------------------------------------------------------
package body Util.Streams is
use Ada.Streams;
-- ------------------------------
-- Copy the input stream to the output stream until the end of the input stream
-- is reached.
-- ------------------------------
procedure Copy (From : in out Input_Stream'Class;
Into : in out Output_Stream'Class) is
Buffer : Stream_Element_Array (0 .. 4_096);
Last : Stream_Element_Offset;
begin
loop
From.Read (Buffer, Last);
if Last > Buffer'First then
Into.Write (Buffer (Buffer'First .. Last));
end if;
exit when Last < Buffer'Last;
end loop;
end Copy;
end Util.Streams;
|
-----------------------------------------------------------------------
-- Util.Streams -- Stream utilities
-- Copyright (C) 2010, 2011, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Streams is
use Ada.Streams;
-- ------------------------------
-- Copy the input stream to the output stream until the end of the input stream
-- is reached.
-- ------------------------------
procedure Copy (From : in out Input_Stream'Class;
Into : in out Output_Stream'Class) is
Buffer : Stream_Element_Array (0 .. 4_096);
Last : Stream_Element_Offset;
begin
loop
From.Read (Buffer, Last);
if Last > Buffer'First then
Into.Write (Buffer (Buffer'First .. Last));
end if;
exit when Last < Buffer'Last;
end loop;
end Copy;
-- ------------------------------
-- Copy the stream array to the string.
-- The string must be large enough to hold the stream array
-- or a Constraint_Error exception is raised.
-- ------------------------------
procedure Copy (From : in Ada.Streams.Stream_Element_Array;
Into : in out String) is
Pos : Positive := Into'First;
begin
for I in From'Range loop
Into (Pos) := Character'Val (From (I));
Pos := Pos + 1;
end loop;
end Copy;
-- ------------------------------
-- Copy the string to the stream array.
-- The stream array must be large enough to hold the string
-- or a Constraint_Error exception is raised.
-- ------------------------------
procedure Copy (From : in String;
Into : in out Ada.Streams.Stream_Element_Array) is
Pos : Ada.Streams.Stream_Element_Offset := Into'First;
begin
for I in From'Range loop
Into (Pos) := Character'Pos (From (I));
Pos := Pos + 1;
end loop;
end Copy;
end Util.Streams;
|
Implement Copy procedure to copy a String to a Stream_Element_Array
|
Implement Copy procedure to copy a String to a Stream_Element_Array
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
54162a5af002ccbb8828672b2598f8be60943989
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- specified in <b>Syntax</b> and invoke the document reader procedures defined
-- by <b>into</b>.
procedure Parse (Into : in Wiki.Documents.Document_Reader_Access;
Text : in Wide_Wide_String;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
private
use Ada.Strings.Wide_Wide_Unbounded;
HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#);
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#);
type Input is interface;
type Input_Access is access all Input'Class;
procedure Read_Char (From : in out Input;
Token : out Wide_Wide_Character;
Eof : out Boolean) is abstract;
type Parser is limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Document : Wiki.Documents.Document_Reader_Access;
Format : Wiki.Documents.Format_Map;
Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Input_Access := null;
Attributes : Wiki.Attributes.Attribute_List_Type;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- 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);
procedure Start_Element (P : in out Parser;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
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 Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- specified in <b>Syntax</b> and invoke the document reader procedures defined
-- by <b>into</b>.
procedure Parse (Into : in Wiki.Documents.Document_Reader_Access;
Text : in Wide_Wide_String;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
private
use Ada.Strings.Wide_Wide_Unbounded;
HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#);
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#);
type Input is interface;
type Input_Access is access all Input'Class;
procedure Read_Char (From : in out Input;
Token : out Wide_Wide_Character;
Eof : out Boolean) is abstract;
type Parser is limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Document : Wiki.Documents.Document_Reader_Access;
Format : Wiki.Documents.Format_Map;
Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Input_Access := null;
Attributes : Wiki.Attributes.Attribute_List_Type;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- 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);
procedure Start_Element (P : in out Parser;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
end Wiki.Parsers;
|
Add SYNTAX_HTML to parse HTML
|
Add SYNTAX_HTML to parse HTML
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
ed2b89f46dfb1362cc54877a240292ab875283ad
|
src/asf-servlets-faces.adb
|
src/asf-servlets-faces.adb
|
-----------------------------------------------------------------------
-- asf.servlets.faces -- Faces servlet
-- Copyright (C) 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
package body ASF.Servlets.Faces is
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Faces_Servlet;
Context : in Servlet_Registry'Class) is
pragma Unreferenced (Context);
Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
if Ctx.all in ASF.Applications.Main.Application'Class then
Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access;
end if;
end Initialize;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
procedure Do_Get (Server : in Faces_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
URI : constant String := Request.Get_Servlet_Path;
begin
Server.App.Dispatch (Page => URI,
Request => Request,
Response => Response);
end Do_Get;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a POST request. The HTTP POST method allows the client to send data of unlimited
-- length to the Web server a single time and is useful when posting information
-- such as credit card numbers.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding. When using
-- a PrintWriter object to return the response, set the content type before
-- accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container to use
-- a persistent connection to return its response to the client, improving
-- performance. The content length is automatically set if the entire response
-- fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- This method does not need to be either safe or idempotent. Operations
-- requested through POST can have side effects for which the user can be held
-- accountable, for example, updating stored data or buying items online.
--
-- If the HTTP POST request is incorrectly formatted, doPost returns
-- an HTTP "Bad Request" message.
-- ------------------------------
procedure Do_Post (Server : in Faces_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
URI : constant String := Request.Get_Servlet_Path;
begin
Server.App.Dispatch (Page => URI,
Request => Request,
Response => Response);
end Do_Post;
end ASF.Servlets.Faces;
|
-----------------------------------------------------------------------
-- asf.servlets.faces -- Faces servlet
-- Copyright (C) 2010, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Applications;
package body ASF.Servlets.Faces is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Servlets.Faces");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Faces_Servlet;
Context : in Servlet_Registry'Class) is
pragma Unreferenced (Context);
Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
if Ctx.all in ASF.Applications.Main.Application'Class then
Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access;
end if;
end Initialize;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
procedure Do_Get (Server : in Faces_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
URI : constant String := Request.Get_Servlet_Path;
begin
Log.Info ("GET {0}", URI);
Server.App.Dispatch (Page => URI,
Request => Request,
Response => Response);
end Do_Get;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a POST request. The HTTP POST method allows the client to send data of unlimited
-- length to the Web server a single time and is useful when posting information
-- such as credit card numbers.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding. When using
-- a PrintWriter object to return the response, set the content type before
-- accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container to use
-- a persistent connection to return its response to the client, improving
-- performance. The content length is automatically set if the entire response
-- fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- This method does not need to be either safe or idempotent. Operations
-- requested through POST can have side effects for which the user can be held
-- accountable, for example, updating stored data or buying items online.
--
-- If the HTTP POST request is incorrectly formatted, doPost returns
-- an HTTP "Bad Request" message.
-- ------------------------------
procedure Do_Post (Server : in Faces_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
URI : constant String := Request.Get_Servlet_Path;
begin
Log.Info ("POST {0}", URI);
Server.App.Dispatch (Page => URI,
Request => Request,
Response => Response);
end Do_Post;
end ASF.Servlets.Faces;
|
Add a Log.Info for each GET and POST request to help trouble shoting web issues
|
Add a Log.Info for each GET and POST request to help trouble shoting web issues
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
31d425adddf2507eaaf5e08d9b12fe176a475047
|
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 Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- 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_Bean (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.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
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);
Count_Query.Bind_Param (Name => "user_id", Value => User);
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 ASF.Contexts.Flash;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ADO.Utils;
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
use ASF.Applications;
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- 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_Bean (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
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_welcome_message",
Messages.INFO);
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Send_Invitation (Bean);
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_invitation_sent",
Messages.INFO);
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.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
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;
|
Add a flash message after the invitation is sent and accepted
|
Add a flash message after the invitation is sent and accepted
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
aeb08223486f1cac957f8639a9fa36b820ed5bf8
|
1-base/lace/source/text/lace-text-cursor.adb
|
1-base/lace/source/text/lace-text-cursor.adb
|
with
ada.Characters.latin_1,
ada.Characters.handling,
ada.Strings.fixed,
ada.Strings.Maps.Constants;
-- with ada.text_IO; use ada.Text_IO;
package body lace.text.Cursor
is
use ada.Strings;
Integer_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789");
Float_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789.");
--------
-- Forge
--
function First (of_Text : access constant Text.item) return Cursor.item
is
the_Cursor : constant Cursor.item := (of_Text.all'unchecked_Access, 1);
begin
return the_Cursor;
end First;
-------------
-- Attributes
--
function at_End (Self : in Item) return Boolean
is
begin
return Self.Current = 0;
end at_End;
function has_Element (Self : in Item) return Boolean
is
begin
return not at_End (Self)
and Self.Current <= Self.Target.Length;
end has_Element;
procedure advance (Self : in out Item; Delimiter : in String := " ";
Repeat : in Natural := 0;
skip_Delimiter : in Boolean := True;
match_Case : in Boolean := True)
is
begin
for Count in 1 .. Repeat + 1
loop
declare
use ada.Characters.handling;
delimiter_Position : Natural;
begin
if match_Case
then
delimiter_Position := fixed.Index (Self.Target.Data (1 .. Self.Target.Length),
Delimiter,
From => Self.Current);
else
delimiter_Position := fixed.Index (to_Lower (Self.Target.Data (1 .. Self.Target.Length)),
to_Lower (Delimiter),
From => Self.Current);
end if;
if delimiter_Position = 0
then
Self.Current := 0;
return;
else
if skip_Delimiter
then
Self.Current := delimiter_Position + Delimiter'Length;
elsif Count = Repeat + 1
then
Self.Current := delimiter_Position - 1;
else
Self.Current := delimiter_Position + Delimiter'Length - 1;
end if;
end if;
end;
end loop;
exception
when constraint_Error =>
raise at_end_Error;
end advance;
procedure skip_White (Self : in out Item)
is
begin
while has_Element (Self)
and then ( Self.Target.Data (Self.Current) = ' '
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.LF
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.HT)
loop
Self.Current := Self.Current + 1;
end loop;
end skip_White;
procedure skip_Line (Self : in out Item)
is
Line : String := next_Line (Self) with Unreferenced;
begin
null;
end skip_Line;
function next_Token (Self : in out Item;
Delimiter : in Character := ' ';
Trim : in Boolean := False) return String
is
begin
return next_Token (Self, "" & Delimiter, Trim);
end next_Token;
function next_Token (Self : in out item; Delimiter : in String;
match_Case : in Boolean := True;
Trim : in Boolean := False) return String
is
use ada.Characters.handling;
begin
if at_End (Self)
then
raise at_end_Error;
end if;
declare
use ada.Strings.fixed,
ada.Strings.Maps.Constants;
delimiter_Position : constant Natural := (if match_Case then Index (Self.Target.Data, Delimiter, from => Self.Current)
else Index (Self.Target.Data, to_Lower (Delimiter), from => Self.Current, mapping => lower_case_Map));
begin
-- put_Line ("delimiter_Position" & delimiter_Position'Image);
if delimiter_Position = 0
then
return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. Self.Target.Length), Both)
else Self.Target.Data (Self.Current .. Self.Target.Length))
do
Self.Current := 0;
end return;
end if;
return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. delimiter_Position - 1), Both)
else Self.Target.Data (Self.Current .. delimiter_Position - 1))
do
Self.Current := delimiter_Position + Delimiter'Length;
end return;
end;
end next_Token;
function next_Line (Self : in out Item; Trim : in Boolean := False) return String
is
use ada.Characters;
Token : constant String := next_Token (Self, Delimiter => latin_1.LF,
Trim => Trim);
Pad : constant String := Token; --(if Token (Token'Last) = latin_1.CR then Token (Token'First .. Token'Last - 1)
-- else Token);
begin
if Trim then return fixed.Trim (Pad, Both);
else return Pad;
end if;
end next_Line;
procedure skip_Token (Self : in out Item; Delimiter : in String := " ";
match_Case : in Boolean := True)
is
ignored_Token : String := Self.next_Token (Delimiter, match_Case);
begin
null;
end skip_Token;
function get_Integer (Self : in out Item) return Integer
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, integer_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return Integer'Value (Text (First .. Last));
end get_Integer;
function get_Integer (Self : in out Item) return long_Integer
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, integer_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return long_Integer'Value (Text (First .. Last));
end get_Integer;
function get_Real (Self : in out Item) return long_Float
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, float_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return long_Float'Value (Text (First .. Last));
end get_Real;
function Length (Self : in Item) return Natural
is
begin
return Self.Target.Length - Self.Current + 1;
end Length;
function peek (Self : in Item; Length : in Natural := Remaining) return String
is
Last : constant Natural := (if Length = Natural'Last then Self.Target.Length
else Self.Current + Length - 1);
begin
if at_End (Self)
then
return "";
end if;
return Self.Target.Data (Self.Current .. Last);
end peek;
function peek_Line (Self : in Item) return String
is
C : Cursor.item := Self;
begin
return next_Line (C);
end peek_Line;
end lace.text.Cursor;
|
with
ada.Characters.latin_1,
ada.Characters.handling,
ada.Strings.fixed,
ada.Strings.Maps.Constants;
-- with ada.text_IO; use ada.Text_IO;
package body lace.text.Cursor
is
use ada.Strings;
Integer_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789");
Float_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789.");
--------
-- Forge
--
function First (of_Text : access constant Text.item) return Cursor.item
is
the_Cursor : constant Cursor.item := (of_Text.all'unchecked_Access, 1);
begin
return the_Cursor;
end First;
-------------
-- Attributes
--
function at_End (Self : in Item) return Boolean
is
begin
return Self.Current = 0;
end at_End;
function has_Element (Self : in Item) return Boolean
is
begin
return not at_End (Self)
and Self.Current <= Self.Target.Length;
end has_Element;
procedure advance (Self : in out Item; Delimiter : in String := " ";
Repeat : in Natural := 0;
skip_Delimiter : in Boolean := True;
match_Case : in Boolean := True)
is
begin
for Count in 1 .. Repeat + 1
loop
declare
use ada.Characters.handling;
delimiter_Position : Natural;
begin
if match_Case
then
delimiter_Position := fixed.Index (Self.Target.Data (1 .. Self.Target.Length),
Delimiter,
From => Self.Current);
else
delimiter_Position := fixed.Index (to_Lower (Self.Target.Data (1 .. Self.Target.Length)),
to_Lower (Delimiter),
From => Self.Current);
end if;
if delimiter_Position = 0
then
Self.Current := 0;
return;
else
if skip_Delimiter
then
Self.Current := delimiter_Position + Delimiter'Length;
elsif Count = Repeat + 1
then
Self.Current := delimiter_Position;
else
Self.Current := delimiter_Position + Delimiter'Length - 1;
end if;
end if;
end;
end loop;
exception
when constraint_Error =>
raise at_end_Error;
end advance;
procedure skip_White (Self : in out Item)
is
begin
while has_Element (Self)
and then ( Self.Target.Data (Self.Current) = ' '
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.LF
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.HT)
loop
Self.Current := Self.Current + 1;
end loop;
end skip_White;
procedure skip_Line (Self : in out Item)
is
Line : String := next_Line (Self) with Unreferenced;
begin
null;
end skip_Line;
function next_Token (Self : in out Item;
Delimiter : in Character := ' ';
Trim : in Boolean := False) return String
is
begin
return next_Token (Self, "" & Delimiter, Trim);
end next_Token;
function next_Token (Self : in out item; Delimiter : in String;
match_Case : in Boolean := True;
Trim : in Boolean := False) return String
is
use ada.Characters.handling;
begin
if at_End (Self)
then
raise at_end_Error;
end if;
declare
use ada.Strings.fixed,
ada.Strings.Maps.Constants;
delimiter_Position : constant Natural := (if match_Case then Index (Self.Target.Data (Self.Current .. Self.Target.Length), Delimiter, from => Self.Current)
else Index (Self.Target.Data (Self.Current .. Self.Target.Length), to_Lower (Delimiter), from => Self.Current,
mapping => lower_case_Map));
begin
-- put_Line ("delimiter_Position" & delimiter_Position'Image);
if delimiter_Position = 0
then
return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. Self.Target.Length), Both)
else Self.Target.Data (Self.Current .. Self.Target.Length))
do
Self.Current := 0;
end return;
end if;
return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. delimiter_Position - 1), Both)
else Self.Target.Data (Self.Current .. delimiter_Position - 1))
do
Self.Current := delimiter_Position + Delimiter'Length;
end return;
end;
end next_Token;
function next_Line (Self : in out Item; Trim : in Boolean := False) return String
is
use ada.Characters;
Token : constant String := next_Token (Self, Delimiter => latin_1.LF,
Trim => Trim);
Pad : constant String := Token; --(if Token (Token'Last) = latin_1.CR then Token (Token'First .. Token'Last - 1)
-- else Token);
begin
if Trim then return fixed.Trim (Pad, Both);
else return Pad;
end if;
end next_Line;
procedure skip_Token (Self : in out Item; Delimiter : in String := " ";
match_Case : in Boolean := True)
is
ignored_Token : String := Self.next_Token (Delimiter, match_Case);
begin
null;
end skip_Token;
function get_Integer (Self : in out Item) return Integer
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, integer_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return Integer'Value (Text (First .. Last));
end get_Integer;
function get_Integer (Self : in out Item) return long_Integer
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, integer_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return long_Integer'Value (Text (First .. Last));
end get_Integer;
function get_Real (Self : in out Item) return long_Float
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, float_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return long_Float'Value (Text (First .. Last));
end get_Real;
function Length (Self : in Item) return Natural
is
begin
return Self.Target.Length - Self.Current + 1;
end Length;
function peek (Self : in Item; Length : in Natural := Remaining) return String
is
Last : constant Natural := (if Length = Natural'Last then Self.Target.Length
else Self.Current + Length - 1);
begin
if at_End (Self)
then
return "";
end if;
return Self.Target.Data (Self.Current .. Last);
end peek;
function peek_Line (Self : in Item) return String
is
C : Cursor.item := Self;
begin
return next_Line (C);
end peek_Line;
end lace.text.Cursor;
|
Fix bug in the 'advance' procedure.
|
lace.text.cursor: Fix bug in the 'advance' procedure.
|
Ada
|
isc
|
charlie5/lace,charlie5/lace,charlie5/lace
|
835c93cb3f6f5a5de2317ac899dd4b3841c9853f
|
awa/plugins/awa-mail/src/awa-mail-modules.adb
|
awa/plugins/awa-mail/src/awa-mail-modules.adb
|
-----------------------------------------------------------------------
-- awa-mail -- Mail module
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Mail.Beans;
with AWA.Mail.Components.Factory;
with AWA.Applications;
with ASF.Servlets;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Log.Loggers;
package body AWA.Mail.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Module");
package Register is new AWA.Modules.Beans (Module => Mail_Module,
Module_Access => Mail_Module_Access);
-- ------------------------------
-- Initialize the mail module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Mail_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the mail module");
-- Add the Mail UI components.
App.Add_Components (AWA.Mail.Components.Factory.Definition);
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Mail.Beans.Mail_Bean",
Handler => AWA.Mail.Beans.Create_Mail_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Mail_Module;
Props : in ASF.Applications.Config) is
Mailer : constant String := Props.Get ("mailer", "smtp");
begin
Log.Info ("Mail plugin is using {0} mailer", Mailer);
Plugin.Mailer := AWA.Mail.Clients.Factory (Mailer, Props);
end Configure;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
function Create_Message (Plugin : in Mail_Module)
return AWA.Mail.Clients.Mail_Message_Access is
begin
return Plugin.Mailer.Create_Message;
end Create_Message;
-- ------------------------------
-- Get the mail template that must be used for the given event name.
-- The mail template is configured by the property: <i>module</i>.template.<i>event</i>.
-- ------------------------------
function Get_Template (Plugin : in Mail_Module;
Name : in String) return String is
Prop_Name : constant String := Plugin.Get_Name & ".template." & Name;
begin
return Plugin.Get_Config (Prop_Name);
end Get_Template;
-- ------------------------------
-- Receive an event sent by another module with <b>Send_Event</b> method.
-- Format and send an email.
-- ------------------------------
procedure Send_Mail (Plugin : in Mail_Module;
Template : in String;
Props : in Util.Beans.Objects.Maps.Map;
Content : in AWA.Events.Module_Event'Class) is
Name : constant String := Content.Get_Parameter ("name");
begin
Log.Info ("Receive event {0} with template {1}", Name, Template);
if Template = "" then
Log.Debug ("No email template associated with event {0}", Name);
return;
end if;
declare
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := Content'Unrestricted_Access;
Bean : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC);
Dispatcher : constant ASF.Servlets.Request_Dispatcher
:= Plugin.Get_Application.Get_Request_Dispatcher (Template);
begin
Req.Set_Request_URI (Template);
Req.Set_Method ("GET");
Req.Set_Attribute (Name => "event", Value => Bean);
Req.Set_Attributes (Props);
ASF.Servlets.Forward (Dispatcher, Req, Reply);
end;
end Send_Mail;
-- ------------------------------
-- Get the mail module instance associated with the current application.
-- ------------------------------
function Get_Mail_Module return Mail_Module_Access is
function Get is new AWA.Modules.Get (Mail_Module, Mail_Module_Access, NAME);
begin
return Get;
end Get_Mail_Module;
end AWA.Mail.Modules;
|
-----------------------------------------------------------------------
-- awa-mail -- Mail module
-- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Mail.Beans;
with AWA.Mail.Components.Factory;
with AWA.Applications;
with ASF.Servlets;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Log.Loggers;
package body AWA.Mail.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Module");
package Register is new AWA.Modules.Beans (Module => Mail_Module,
Module_Access => Mail_Module_Access);
-- ------------------------------
-- Initialize the mail module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Mail_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the mail module");
-- Add the Mail UI components.
App.Add_Components (AWA.Mail.Components.Factory.Definition);
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Mail.Beans.Mail_Bean",
Handler => AWA.Mail.Beans.Create_Mail_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Mail_Module;
Props : in ASF.Applications.Config) is
Mailer : constant String := Props.Get ("mailer", "smtp");
begin
Log.Info ("Mail plugin is using {0} mailer", Mailer);
Plugin.Mailer := AWA.Mail.Clients.Factory (Mailer, Props);
end Configure;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
function Create_Message (Plugin : in Mail_Module)
return AWA.Mail.Clients.Mail_Message_Access is
begin
return Plugin.Mailer.Create_Message;
end Create_Message;
-- ------------------------------
-- Receive an event sent by another module with <b>Send_Event</b> method.
-- Format and send an email.
-- ------------------------------
procedure Send_Mail (Plugin : in Mail_Module;
Template : in String;
Props : in Util.Beans.Objects.Maps.Map;
Content : in AWA.Events.Module_Event'Class) is
Name : constant String := Content.Get_Parameter ("name");
begin
Log.Info ("Receive event {0} with template {1}", Name, Template);
if Template = "" then
Log.Debug ("No email template associated with event {0}", Name);
return;
end if;
declare
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := Content'Unrestricted_Access;
Bean : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC);
Dispatcher : constant ASF.Servlets.Request_Dispatcher
:= Plugin.Get_Application.Get_Request_Dispatcher (Template);
begin
Req.Set_Request_URI (Template);
Req.Set_Method ("GET");
Req.Set_Attribute (Name => "event", Value => Bean);
Req.Set_Attributes (Props);
ASF.Servlets.Forward (Dispatcher, Req, Reply);
end;
end Send_Mail;
-- ------------------------------
-- Get the mail module instance associated with the current application.
-- ------------------------------
function Get_Mail_Module return Mail_Module_Access is
function Get is new AWA.Modules.Get (Mail_Module, Mail_Module_Access, NAME);
begin
return Get;
end Get_Mail_Module;
end AWA.Mail.Modules;
|
Remove the Get_Template function that is not used
|
Remove the Get_Template function that is not used
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e5c898830882cd0c83abe17f2491af554336e37e
|
awa/plugins/awa-mail/src/awa-mail-modules.ads
|
awa/plugins/awa-mail/src/awa-mail-modules.ads
|
-----------------------------------------------------------------------
-- awa-mail -- Mail module
-- Copyright (C) 2011, 2012, 2017, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects.Maps;
with ASF.Applications;
with AWA.Modules;
with AWA.Events;
with AWA.Mail.Clients;
-- == Integration ==
-- To be able to use the `mail` module, you will need to add the following
-- line in your GNAT project file:
--
-- with "awa_mail";
--
-- The `Mail_Module` type represents the mail module. An instance
-- of the mail module must be declared and registered when the application
-- is created and initialized. The module instance can be defined
-- as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Mail_Module : aliased AWA.Mail.Modules.Mail_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Mail.Modules.NAME,
-- Module => App.Mail_Module'Access);
--
-- == Configuration ==
-- The `mail` module needs some properties to configure the SMTP
-- server.
--
-- |Configuration | Default | Description |
-- | --------------- | --------- | ----------------------------------------------- |
-- |mail.smtp.host | localhost | Defines the SMTP server host name |
-- |mail.smtp.port | 25 | Defines the SMTP connection port |
-- |mail.smtp.enable | 1 | Defines whether sending email is enabled or not |
--
-- == Sending an email ==
-- Sending an email when an event is posted can be done by using
-- an XML configuration. Basically, the `mail` module uses the event
-- framework provided by AWA. The XML definition looks like:
--
-- <on-event name="user-register">
-- <action>#{userMail.send}</action>
-- <property name="template">/mail/register-user-message.xhtml</property>
-- </on-event>
--
-- With this definition, the mail template `/mail/register-user-message.xhtml`
-- is formatted by using the event and application context when the
-- `user-register` event is posted.
--
-- @include awa-mail-components.ads
-- @include awa-mail-components-recipients.ads
-- @include awa-mail-components-messages.ads
--
-- == Ada Beans ==
-- @include-bean mail.xml
--
package AWA.Mail.Modules is
NAME : constant String := "mail";
type Mail_Module is new AWA.Modules.Module with private;
type Mail_Module_Access is access all Mail_Module'Class;
-- Initialize the mail module.
overriding
procedure Initialize (Plugin : in out Mail_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having
-- read its XML configuration.
overriding
procedure Configure (Plugin : in out Mail_Module;
Props : in ASF.Applications.Config);
-- Create a new mail message.
function Create_Message (Plugin : in Mail_Module)
return AWA.Mail.Clients.Mail_Message_Access;
-- Format and send an email.
procedure Send_Mail (Plugin : in Mail_Module;
Template : in String;
Props : in Util.Beans.Objects.Maps.Map;
Content : in AWA.Events.Module_Event'Class);
-- Get the mail module instance associated with the current application.
function Get_Mail_Module return Mail_Module_Access;
private
type Mail_Module is new AWA.Modules.Module with record
Mailer : AWA.Mail.Clients.Mail_Manager_Access;
end record;
end AWA.Mail.Modules;
|
-----------------------------------------------------------------------
-- awa-mail -- Mail module
-- Copyright (C) 2011, 2012, 2017, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects.Maps;
with ASF.Applications;
with AWA.Modules;
with AWA.Events;
with AWA.Mail.Clients;
-- == Integration ==
-- To be able to use the `mail` module, you will need to add the following
-- line in your GNAT project file:
--
-- with "awa_mail";
--
-- The `Mail_Module` type represents the mail module. An instance
-- of the mail module must be declared and registered when the application
-- is created and initialized. The module instance can be defined
-- as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Mail_Module : aliased AWA.Mail.Modules.Mail_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Mail.Modules.NAME,
-- Module => App.Mail_Module'Access);
--
-- == Configuration ==
-- The `mail` module needs some properties to configure the SMTP
-- server.
--
-- |Configuration | Default | Description |
-- | --------------- | --------- | ----------------------------------------------- |
-- |mail.smtp.host | localhost | Defines the SMTP server host name |
-- |mail.smtp.port | 25 | Defines the SMTP connection port |
-- |mail.smtp.enable | 1 | Defines whether sending email is enabled or not |
--
-- == Sending an email ==
-- Sending an email when an event is posted can be done by using
-- an XML configuration. Basically, the `mail` module uses the event
-- framework provided by AWA. The XML definition looks like:
--
-- <on-event name="user-register">
-- <action>#{userMail.send}</action>
-- <property name="template">/mail/register-user-message.xhtml</property>
-- </on-event>
--
-- With this definition, the mail template `/mail/register-user-message.xhtml`
-- is formatted by using the event and application context when the
-- `user-register` event is posted.
--
-- @include awa-mail-components.ads
-- @include awa-mail-components-recipients.ads
-- @include awa-mail-components-messages.ads
-- @include awa-mail-components-attachments.ads
--
-- == Ada Beans ==
-- @include-bean mail.xml
--
package AWA.Mail.Modules is
NAME : constant String := "mail";
type Mail_Module is new AWA.Modules.Module with private;
type Mail_Module_Access is access all Mail_Module'Class;
-- Initialize the mail module.
overriding
procedure Initialize (Plugin : in out Mail_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having
-- read its XML configuration.
overriding
procedure Configure (Plugin : in out Mail_Module;
Props : in ASF.Applications.Config);
-- Create a new mail message.
function Create_Message (Plugin : in Mail_Module)
return AWA.Mail.Clients.Mail_Message_Access;
-- Format and send an email.
procedure Send_Mail (Plugin : in Mail_Module;
Template : in String;
Props : in Util.Beans.Objects.Maps.Map;
Content : in AWA.Events.Module_Event'Class);
-- Get the mail module instance associated with the current application.
function Get_Mail_Module return Mail_Module_Access;
private
type Mail_Module is new AWA.Modules.Module with record
Mailer : AWA.Mail.Clients.Mail_Manager_Access;
end record;
end AWA.Mail.Modules;
|
Update for documentation
|
Update for documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
672248f359300fa1f5e36f6ed9fc8a46f6104014
|
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.Contexts.Flash;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ADO.Utils;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Events.Action_Method;
package body AWA.Workspaces.Beans is
use ASF.Applications;
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- 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_Bean (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
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_welcome_message",
Messages.INFO);
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Send_Invitation (Bean);
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_invitation_sent",
Messages.INFO);
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;
-- ------------------------------
-- 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 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
:= (1 => 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
pragma Unreferenced (Outcome);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
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.Contexts.Flash;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ADO.Utils;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Events.Action_Method;
package body AWA.Workspaces.Beans is
use ASF.Applications;
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- 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_Bean (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
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_welcome_message",
Messages.INFO);
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Send_Invitation (Bean);
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_invitation_sent",
Messages.INFO);
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;
-- ------------------------------
-- 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;
begin
Bean.Module.Create_Workspace (WS);
end Create;
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
:= (1 => 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
pragma Unreferenced (Outcome);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
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;
|
Update to use the new Create_Workspace procedure
|
Update to use the new Create_Workspace procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7294e43aea869c4b655827cf5cd2b82d849244f4
|
mat/src/mat-expressions.ads
|
mat/src/mat-expressions.ads
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- 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;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME,
N_CONDITION, N_THREAD);
type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Context : in Context_Type) return Boolean;
private
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Thread : MAT.Types.Target_Thread_Ref;
when others =>
null;
end case;
end record;
function Is_Selected (Node : in Node_Type;
Context : in Context_Type) return Boolean;
type Expression_Type is tagged record
Node : Node_Type_Access;
end record;
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- 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;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME,
N_CONDITION, N_THREAD);
type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Context : in Context_Type) return Boolean;
private
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Thread : MAT.Types.Target_Thread_Ref;
when others =>
null;
end case;
end record;
function Is_Selected (Node : in Node_Type;
Context : in Context_Type) return Boolean;
type Expression_Type is tagged record
Node : Node_Type_Access;
end record;
end MAT.Expressions;
|
Define the Create_Time operation
|
Define the Create_Time operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
1e0754d6c481ac99e41333662e1850bb9cd0032b
|
regtests/asf-applications-views-tests.adb
|
regtests/asf-applications-views-tests.adb
|
-----------------------------------------------------------------------
-- asf-applications-views-tests - Unit tests for ASF.Applications.Views
-- Copyright (C) 2009, 2010, 2011, 2012, 2014, 2015, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with ASF.Applications.Main;
with ASF.Applications.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Servlets.Faces;
with ASF.Converters.Dates;
with ASF.Server;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with Util.Files;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use Ada.Strings.Unbounded;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- ------------------------------
-- Test loading of facelet file
-- ------------------------------
procedure Test_Load_Facelet (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class,
Name => ASF.Converters.Dates.Date_Converter_Access);
App : aliased Applications.Main.Application;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
App_Factory : Applications.Main.Application_Factory;
Dir : constant String := "regtests/files";
Path : constant String := Util.Tests.Get_Path (Dir);
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
List : Util.Beans.Basic.Readonly_Bean_Access;
List_Bean : Util.Beans.Objects.Object;
Form : Util.Beans.Basic.Readonly_Bean_Access;
Form_Bean : Util.Beans.Objects.Object;
C : ASF.Converters.Dates.Date_Converter_Access;
Container : ASF.Server.Container;
begin
List := Applications.Tests.Create_Form_List;
List_Bean := Util.Beans.Objects.To_Object (List);
Form := Applications.Tests.Create_Form_Bean;
Form_Bean := Util.Beans.Objects.To_Object (Form);
Conf.Load_Properties ("regtests/view.properties");
Conf.Set ("view.dir", Path);
App.Initialize (Conf, App_Factory);
App.Register_Application ("/");
App.Add_Servlet ("faces", Faces'Unchecked_Access);
App.Add_Mapping ("*.xhtml", "faces");
C := ASF.Converters.Dates.Create_Date_Converter (Date => ASF.Converters.Dates.DEFAULT,
Time => ASF.Converters.Dates.DEFAULT,
Format => ASF.Converters.Dates.TIME,
Locale => "en",
Pattern => "");
App.Add_Converter ("date-default-converter", C.all'Access);
App.Set_Global ("function", "Test_Load_Facelet");
App.Set_Global ("date", "2011-12-03 03:04:05.23");
Container.Register_Application ("/asfunit", App'Unchecked_Access);
Container.Start;
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Reply : aliased ASF.Responses.Mockup.Response;
Content : Unbounded_String;
begin
Req.Set_Method ("GET");
Req.Set_Request_URI ("/asfunit/" & View_Name);
Req.Set_Parameter ("file-name", To_String (T.Name));
Req.Set_Header ("file", To_String (T.Name));
Req.Set_Attribute ("list", List_Bean);
Req.Set_Attribute ("form", Form_Bean);
Container.Service (Req, Reply);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Reply.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
Free (C);
end Test_Load_Facelet;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : Test) return Util.Tests.Message_String is
begin
return Util.Tests.Format ("Test " & To_String (T.Name));
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "regtests/result/views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn"
then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String ("views/" & Simple);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
-----------------------------------------------------------------------
-- asf-applications-views-tests - Unit tests for ASF.Applications.Views
-- Copyright (C) 2009, 2010, 2011, 2012, 2014, 2015, 2018, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with ASF.Applications.Main;
with ASF.Applications.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Servlets.Faces;
with ASF.Converters.Dates;
with ASF.Server;
with Ada.Directories;
with Ada.Unchecked_Deallocation;
with Util.Files;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use Ada.Strings.Unbounded;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- ------------------------------
-- Test loading of facelet file
-- ------------------------------
procedure Test_Load_Facelet (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class,
Name => ASF.Converters.Dates.Date_Converter_Access);
App : aliased Applications.Main.Application;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
App_Factory : Applications.Main.Application_Factory;
Dir : constant String := "regtests/files";
Path : constant String := Util.Tests.Get_Path (Dir);
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
List : Util.Beans.Basic.Readonly_Bean_Access;
List_Bean : Util.Beans.Objects.Object;
Form : Util.Beans.Basic.Readonly_Bean_Access;
Form_Bean : Util.Beans.Objects.Object;
C : ASF.Converters.Dates.Date_Converter_Access;
Container : ASF.Server.Container;
begin
List := Applications.Tests.Create_Form_List;
List_Bean := Util.Beans.Objects.To_Object (List);
Form := Applications.Tests.Create_Form_Bean;
Form_Bean := Util.Beans.Objects.To_Object (Form);
Conf.Load_Properties ("regtests/view.properties");
Conf.Set ("view.dir", Path);
App.Initialize (Conf, App_Factory);
App.Register_Application ("/");
App.Add_Servlet ("faces", Faces'Unchecked_Access);
App.Add_Mapping ("*.xhtml", "faces");
C := ASF.Converters.Dates.Create_Date_Converter (Date => ASF.Converters.Dates.DEFAULT,
Time => ASF.Converters.Dates.DEFAULT,
Format => ASF.Converters.Dates.TIME,
Locale => "en",
Pattern => "");
App.Add_Converter ("date-default-converter", C.all'Access);
App.Set_Global ("function", "Test_Load_Facelet");
App.Set_Global ("date", "2011-12-03 03:04:05.23");
Container.Register_Application ("/asfunit", App'Unchecked_Access);
Container.Start;
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Reply : aliased ASF.Responses.Mockup.Response;
Content : Unbounded_String;
begin
Req.Set_Method ("GET");
Req.Set_Request_URI ("/asfunit/" & View_Name);
Req.Set_Parameter ("file-name", To_String (T.Name));
Req.Set_Header ("file", To_String (T.Name));
Req.Set_Attribute ("list", List_Bean);
Req.Set_Attribute ("form", Form_Bean);
Container.Service (Req, Reply);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Reply.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
Free (C);
end Test_Load_Facelet;
-- ------------------------------
-- Test case name
-- ------------------------------
overriding
function Name (T : Test) return Util.Tests.Message_String is
begin
return Util.Tests.Format ("Test " & To_String (T.Name));
end Name;
-- ------------------------------
-- Perform the test.
-- ------------------------------
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn"
then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String ("views/" & Simple);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
Fix wrong use of Get_Test_Path
|
Fix wrong use of Get_Test_Path
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
931407994a6cb4f331f524f0d8d5d26645bbdfdf
|
awa/src/awa-applications-configs.adb
|
awa/src/awa-applications-configs.adb
|
-----------------------------------------------------------------------
-- awa-applications-configs -- Read application configuration files
-- 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 Util.Log.Loggers;
with ASF.Contexts.Faces;
with ASF.Applications.Main.Configs;
with Security.Policies;
with AWA.Events.Configs;
with AWA.Services.Contexts;
package body AWA.Applications.Configs is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications.Configs");
-- ------------------------------
-- XML reader configuration. By instantiating this generic package, the XML parser
-- gets initialized to read the configuration for servlets, filters, managed beans,
-- permissions, events and other configuration elements.
-- ------------------------------
package body Reader_Config is
App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access;
package Bean_Config is
new ASF.Applications.Main.Configs.Reader_Config (Reader, App_Access,
Context.all'Access,
Override_Context);
package Event_Config is
new AWA.Events.Configs.Reader_Config (Reader => Reader,
Manager => App.Events'Unchecked_Access,
Context => Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Event_Config);
end Reader_Config;
-- ------------------------------
-- Read the application configuration file and configure the application
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String;
Context : in EL.Contexts.Default.Default_Context_Access;
Override_Context : in Boolean) is
Reader : Util.Serialize.IO.XML.Parser;
Ctx : AWA.Services.Contexts.Service_Context;
Sec : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager;
begin
Log.Info ("Reading application configuration file {0}", File);
Ctx.Set_Context (App'Unchecked_Access, null);
declare
package Config is new Reader_Config (Reader, App'Unchecked_Access, Context,
Override_Context);
pragma Warnings (Off, Config);
begin
Sec.Prepare_Config (Reader);
-- Initialize the parser with the module configuration mappers (if any).
Initialize_Parser (App, Reader);
if Log.Get_Level >= Util.Log.DEBUG_LEVEL then
Util.Serialize.IO.Dump (Reader, Log);
end if;
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end;
exception
when others =>
Log.Error ("Error while reading {0}", File);
raise;
end Read_Configuration;
end AWA.Applications.Configs;
|
-----------------------------------------------------------------------
-- awa-applications-configs -- Read application configuration files
-- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Command_Line;
with Ada.Directories;
with Ada.Strings.Unbounded;
with Util.Files;
with Util.Log.Loggers;
with ASF.Contexts.Faces;
with ASF.Applications.Main.Configs;
with Security.Policies;
with AWA.Events.Configs;
with AWA.Services.Contexts;
package body AWA.Applications.Configs is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications.Configs");
-- ------------------------------
-- XML reader configuration. By instantiating this generic package, the XML parser
-- gets initialized to read the configuration for servlets, filters, managed beans,
-- permissions, events and other configuration elements.
-- ------------------------------
package body Reader_Config is
App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access;
package Bean_Config is
new ASF.Applications.Main.Configs.Reader_Config (Reader, App_Access,
Context.all'Access,
Override_Context);
package Event_Config is
new AWA.Events.Configs.Reader_Config (Reader => Reader,
Manager => App.Events'Unchecked_Access,
Context => Context.all'Access);
pragma Warnings (Off, Bean_Config);
pragma Warnings (Off, Event_Config);
end Reader_Config;
-- ------------------------------
-- Read the application configuration file and configure the application
-- ------------------------------
procedure Read_Configuration (App : in out Application'Class;
File : in String;
Context : in EL.Contexts.Default.Default_Context_Access;
Override_Context : in Boolean) is
Reader : Util.Serialize.IO.XML.Parser;
Ctx : AWA.Services.Contexts.Service_Context;
Sec : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager;
begin
Log.Info ("Reading application configuration file {0}", File);
Ctx.Set_Context (App'Unchecked_Access, null);
declare
package Config is new Reader_Config (Reader, App'Unchecked_Access, Context,
Override_Context);
pragma Warnings (Off, Config);
begin
Sec.Prepare_Config (Reader);
-- Initialize the parser with the module configuration mappers (if any).
Initialize_Parser (App, Reader);
if Log.Get_Level >= Util.Log.DEBUG_LEVEL then
Util.Serialize.IO.Dump (Reader, Log);
end if;
-- Read the configuration file and record managed beans, navigation rules.
Reader.Parse (File);
end;
exception
when others =>
Log.Error ("Error while reading {0}", File);
raise;
end Read_Configuration;
-- ------------------------------
-- Get the configuration path for the application name.
-- The configuration path is search from:
-- o the current directory,
-- o the 'config' directory,
-- o the Dynamo installation directory in share/dynamo
-- ------------------------------
function Get_Config_Path (Name : in String) return String is
use Ada.Strings.Unbounded;
use Ada.Directories;
Command : constant String := Ada.Command_Line.Command_Name;
Path : constant String := Ada.Directories.Containing_Directory (Command);
Dir : constant String := Containing_Directory (Path);
Paths : Ada.Strings.Unbounded.Unbounded_String;
begin
Append (Paths, ".;");
Append (Paths, Util.Files.Compose (Dir, "config"));
Append (Paths, ";");
Append (Paths, Util.Files.Compose (Dir, "share/dynamo/" & Name));
return Util.Files.Find_File_Path (Name & ".properties", To_String (Paths));
end Get_Config_Path;
end AWA.Applications.Configs;
|
Implement the Get_Config_Path function
|
Implement the Get_Config_Path function
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6dce5df2b353808f9d11113d4856bc75c6af2f4b
|
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.
-----------------------------------------------------------------------
-- == 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 Permission_Index is new Natural;
-- 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;
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.
-----------------------------------------------------------------------
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
--
package Security.Permissions is
Invalid_Name : exception;
type Permission_Index is new Natural;
-- 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;
end Security.Permissions;
|
Move the documentation in Security package
|
Move the documentation in Security package
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
b5e7768fa93739f949588041ad9b1b4cb23e3d0c
|
src/util-serialize-tools.adb
|
src/util-serialize-tools.adb
|
-----------------------------------------------------------------------
-- util-serialize-tools -- Tools to Serialize objects in various formats
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Mappers.Record_Mapper;
package body Util.Serialize.Tools is
type Object_Field is (FIELD_NAME, FIELD_VALUE);
type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class;
type Object_Mapper_Context is record
Map : Object_Map_Access;
Name : Util.Beans.Objects.Object;
end record;
type Object_Mapper_Context_Access is access all Object_Mapper_Context;
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_VALUE =>
Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value);
Into.Name := Util.Beans.Objects.Null_Object;
end case;
end Set_Member;
package Object_Mapper is new
Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context,
Element_Type_Access => Object_Mapper_Context_Access,
Fields => Object_Field,
Set_Member => Set_Member);
JSON_Mapping : aliased Object_Mapper.Mapper;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b>
-- JSON stream. Use the <b>Name</b> as the name of the JSON object.
-- -----------------------
procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream;
Name : in String;
Map : in Util.Beans.Objects.Maps.Map) is
use type Ada.Containers.Count_Type;
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Output.Start_Entity (Name => "");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Name));
Output.Write_Attribute (Name => "value",
Value => Value);
Output.End_Entity (Name => "");
end Write;
begin
if Map.Length > 0 then
declare
Iter : Util.Beans.Objects.Maps.Cursor := Map.First;
begin
Output.Start_Array (Name => Name,
Length => Map.Length);
while Util.Beans.Objects.Maps.Has_Element (Iter) loop
Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access);
Util.Beans.Objects.Maps.Next (Iter);
end loop;
Output.End_Array;
end;
end if;
end To_JSON;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into an XML stream.
-- Returns the JSON string that contains a serialization of the object maps.
-- -----------------------
function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is
use type Ada.Containers.Count_Type;
begin
if Map.Length = 0 then
return "";
end if;
declare
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Output.Initialize (Size => 10000);
Output.Start_Document;
To_JSON (Output, "params", Map);
Output.End_Document;
return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Output));
end;
end To_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values. The object map passed in <b>Map</b> can contain existing values.
-- They will be overriden by the JSON values.
-- -----------------------
procedure From_JSON (Content : in String;
Map : in out Util.Beans.Objects.Maps.Map) is
Parser : Util.Serialize.IO.JSON.Parser;
Context : aliased Object_Mapper_Context;
begin
if Content'Length > 0 then
Context.Map := Map'Unchecked_Access;
Parser.Add_Mapping ("/params", JSON_Mapping'Access);
Object_Mapper.Set_Context (Parser, Context'Unchecked_Access);
Parser.Parse_String (Content);
end if;
end From_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values.
-- Returns the object map that was restored.
-- -----------------------
function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is
Result : Util.Beans.Objects.Maps.Map;
begin
From_JSON (Content, Result);
return Result;
end From_JSON;
begin
JSON_Mapping.Add_Mapping ("name", FIELD_NAME);
JSON_Mapping.Add_Mapping ("value", FIELD_VALUE);
end Util.Serialize.Tools;
|
-----------------------------------------------------------------------
-- util-serialize-tools -- Tools to Serialize objects in various formats
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Mappers.Record_Mapper;
package body Util.Serialize.Tools is
type Object_Field is (FIELD_NAME, FIELD_VALUE);
type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class;
type Object_Mapper_Context is record
Map : Object_Map_Access;
Name : Util.Beans.Objects.Object;
end record;
type Object_Mapper_Context_Access is access all Object_Mapper_Context;
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_VALUE =>
Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value);
Into.Name := Util.Beans.Objects.Null_Object;
end case;
end Set_Member;
package Object_Mapper is new
Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context,
Element_Type_Access => Object_Mapper_Context_Access,
Fields => Object_Field,
Set_Member => Set_Member);
JSON_Mapping : aliased Object_Mapper.Mapper;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b>
-- JSON stream. Use the <b>Name</b> as the name of the JSON object.
-- -----------------------
procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream;
Name : in String;
Map : in Util.Beans.Objects.Maps.Map) is
use type Ada.Containers.Count_Type;
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Output.Start_Entity (Name => "");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Name));
Output.Write_Attribute (Name => "value",
Value => Value);
Output.End_Entity (Name => "");
end Write;
begin
if Map.Length > 0 then
declare
Iter : Util.Beans.Objects.Maps.Cursor := Map.First;
begin
Output.Start_Array (Name => Name);
while Util.Beans.Objects.Maps.Has_Element (Iter) loop
Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access);
Util.Beans.Objects.Maps.Next (Iter);
end loop;
Output.End_Array (Name => Name);
end;
end if;
end To_JSON;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into an XML stream.
-- Returns the JSON string that contains a serialization of the object maps.
-- -----------------------
function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is
use type Ada.Containers.Count_Type;
begin
if Map.Length = 0 then
return "";
end if;
declare
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Output.Initialize (Size => 10000);
Output.Start_Document;
To_JSON (Output, "params", Map);
Output.End_Document;
return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Output));
end;
end To_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values. The object map passed in <b>Map</b> can contain existing values.
-- They will be overriden by the JSON values.
-- -----------------------
procedure From_JSON (Content : in String;
Map : in out Util.Beans.Objects.Maps.Map) is
Parser : Util.Serialize.IO.JSON.Parser;
Context : aliased Object_Mapper_Context;
begin
if Content'Length > 0 then
Context.Map := Map'Unchecked_Access;
Parser.Add_Mapping ("/params", JSON_Mapping'Access);
Object_Mapper.Set_Context (Parser, Context'Unchecked_Access);
Parser.Parse_String (Content);
end if;
end From_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values.
-- Returns the object map that was restored.
-- -----------------------
function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is
Result : Util.Beans.Objects.Maps.Map;
begin
From_JSON (Content, Result);
return Result;
end From_JSON;
begin
JSON_Mapping.Add_Mapping ("name", FIELD_NAME);
JSON_Mapping.Add_Mapping ("value", FIELD_VALUE);
end Util.Serialize.Tools;
|
Fix To_JSON after changes on the Start_Array and End_Array operations
|
Fix To_JSON after changes on the Start_Array and End_Array operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ac9039ff8ce0fff3b4bfdd59d37756b3232b2382
|
src/util-streams-files.ads
|
src/util-streams-files.ads
|
-----------------------------------------------------------------------
-- util-streams-files -- File Stream utilities
-- Copyright (C) 2010, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Streams.Stream_IO;
package Util.Streams.Files is
-- -----------------------
-- File stream
-- -----------------------
-- The <b>File_Stream</b> is an output/input stream that reads or writes
-- into a file-based stream.
type File_Stream is limited new Output_Stream and Input_Stream with private;
-- Open the file and initialize the stream for reading or writing.
procedure Open (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "");
-- Create the file and initialize the stream for writing.
procedure Create (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "");
-- Close the stream.
overriding
procedure Close (Stream : in out File_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out File_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out File_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type File_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
File : Ada.Streams.Stream_IO.File_Type;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out File_Stream);
end Util.Streams.Files;
|
-----------------------------------------------------------------------
-- util-streams-files -- File Stream utilities
-- Copyright (C) 2010, 2013, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Streams.Stream_IO;
-- === File streams ===
-- The <tt>Util.Streams.Files</tt> package provides input and output streams that access
-- files on top of the Ada <tt>Stream_IO</tt> standard package.
package Util.Streams.Files is
-- -----------------------
-- File stream
-- -----------------------
-- The <b>File_Stream</b> is an output/input stream that reads or writes
-- into a file-based stream.
type File_Stream is limited new Output_Stream and Input_Stream with private;
-- Open the file and initialize the stream for reading or writing.
procedure Open (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "");
-- Create the file and initialize the stream for writing.
procedure Create (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "");
-- Close the stream.
overriding
procedure Close (Stream : in out File_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out File_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out File_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type File_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
File : Ada.Streams.Stream_IO.File_Type;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out File_Stream);
end Util.Streams.Files;
|
Document the streams framework
|
Document the streams framework
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1477d683866afff78db1de0768e09056c2398a56
|
src/wiki-streams-text_io.adb
|
src/wiki-streams-text_io.adb
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Wiki.Helpers;
package body Wiki.Streams.Text_IO is
-- ------------------------------
-- Open the file and prepare to read the input stream.
-- ------------------------------
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form);
end Open;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Input_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Input_Stream) is
begin
Stream.Close;
end Finalize;
-- ------------------------------
-- Read the input stream and fill the `Into` buffer until either it is full or
-- we reach the end of line. Returns in `Last` the last valid position in the
-- `Into` buffer. When there is no character to read, return True in
-- the `Eof` indicator.
-- ------------------------------
overriding
procedure Read (Input : in out File_Input_Stream;
Into : in out Wiki.Strings.WString;
Last : out Natural;
Eof : out Boolean) is
Available : Boolean;
Pos : Natural := Into'First;
Char : Wiki.Strings.WChar;
begin
Eof := False;
while Pos <= Into'Last loop
Ada.Wide_Wide_Text_IO.Get_Immediate (Input.File, Char, Available);
Into (Pos) := Char;
Pos := Pos + 1;
exit when Char = Helpers.LF or Char = Helpers.CR;
end loop;
Last := Pos - 1;
exception
when Ada.IO_Exceptions.End_Error =>
Last := Pos - 1;
Eof := True;
end Read;
-- ------------------------------
-- Open the file and prepare to write the output stream.
-- ------------------------------
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last);
Stream.Stdout := False;
end Open;
-- ------------------------------
-- Create the file and prepare to write the output stream.
-- ------------------------------
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last);
Stream.Stdout := False;
end Create;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Output_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Write the string to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Content);
else
Ada.Wide_Wide_Text_IO.Put (Content);
end if;
end Write;
-- ------------------------------
-- Write a single character to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Char);
else
Ada.Wide_Wide_Text_IO.Put (Char);
end if;
end Write;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Output_Stream) is
begin
Stream.Close;
end Finalize;
end Wiki.Streams.Text_IO;
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 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.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Wiki.Helpers;
package body Wiki.Streams.Text_IO is
-- ------------------------------
-- Open the file and prepare to read the input stream.
-- ------------------------------
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form);
Stream.Stdin := False;
end Open;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Input_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Input_Stream) is
begin
Stream.Close;
end Finalize;
-- ------------------------------
-- Read the input stream and fill the `Into` buffer until either it is full or
-- we reach the end of line. Returns in `Last` the last valid position in the
-- `Into` buffer. When there is no character to read, return True in
-- the `Eof` indicator.
-- ------------------------------
overriding
procedure Read (Input : in out File_Input_Stream;
Into : in out Wiki.Strings.WString;
Last : out Natural;
Eof : out Boolean) is
Available : Boolean;
Pos : Natural := Into'First;
Char : Wiki.Strings.WChar;
begin
Eof := False;
while Pos <= Into'Last loop
if Input.Stdin then
Ada.Wide_Wide_Text_IO.Get_Immediate (Char, Available);
else
Ada.Wide_Wide_Text_IO.Get_Immediate (Input.File, Char, Available);
end if;
Into (Pos) := Char;
Pos := Pos + 1;
exit when Char = Helpers.LF or Char = Helpers.CR;
end loop;
Last := Pos - 1;
exception
when Ada.IO_Exceptions.End_Error =>
Last := Pos - 1;
Eof := True;
end Read;
-- ------------------------------
-- Open the file and prepare to write the output stream.
-- ------------------------------
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last);
Stream.Stdout := False;
end Open;
-- ------------------------------
-- Create the file and prepare to write the output stream.
-- ------------------------------
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last);
Stream.Stdout := False;
end Create;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Output_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Write the string to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Content);
else
Ada.Wide_Wide_Text_IO.Put (Content);
end if;
end Write;
-- ------------------------------
-- Write a single character to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Char);
else
Ada.Wide_Wide_Text_IO.Put (Char);
end if;
end Write;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Output_Stream) is
begin
Stream.Close;
end Finalize;
end Wiki.Streams.Text_IO;
|
Update File_Input_Stream to use the default stdin file when Open is not called
|
Update File_Input_Stream to use the default stdin file when Open is not called
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
66e68fa6f5eecf97979fd655a97802e4d839cfd5
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009 - 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Blogs.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Modules.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Questions.Tests;
with AWA.Counters.Modules.Tests;
with AWA.Workspaces.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
with AWA.Wikis.Tests;
with AWA.Commands.Tests;
with ADO.Drivers;
with Servlet.Server;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Commands.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Modules.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Tests.Add_Tests (Ret);
AWA.Wikis.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Workspaces.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Counters.Modules.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
ADO.Drivers.Initialize;
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
Application.Start;
-- if Props.Exists ("test.server") then
-- declare
-- WS : ASF.Server.Web.AWS_Container;
-- begin
-- Application.Add_Converter (Name => "dateConverter",
-- Converter => Date_Converter'Access);
-- Application.Add_Converter (Name => "smartDateConverter",
-- Converter => Rel_Date_Converter'Access);
--
-- WS.Register_Application ("/asfunit", Application.all'Access);
--
-- WS.Start;
-- delay 6000.0;
-- end;
-- end if;
Servlet.Server.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009 - 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Blogs.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Modules.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Questions.Tests;
with AWA.Counters.Modules.Tests;
with AWA.Workspaces.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with ASF.Converters.Sizes;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
with AWA.Wikis.Tests;
with AWA.Commands.Tests;
with ADO.Drivers;
with Servlet.Server;
with Security.Auth;
with Security.Auth.Fake;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Size_Converter : aliased ASF.Converters.Sizes.Size_Converter;
Tests : aliased Util.Tests.Test_Suite;
function OAuth_Provider_Factory (Name : in String) return Security.Auth.Manager_Access is
begin
return new Security.Auth.Fake.Manager;
end OAuth_Provider_Factory;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
Security.Auth.Set_Default_Factory (OAuth_Provider_Factory'Access);
AWA.Commands.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Modules.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Tests.Add_Tests (Ret);
AWA.Wikis.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Workspaces.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Counters.Modules.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
ADO.Drivers.Initialize;
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
Application.Start;
-- if Props.Exists ("test.server") then
-- declare
-- WS : ASF.Server.Web.AWS_Container;
-- begin
-- Application.Add_Converter (Name => "dateConverter",
-- Converter => Date_Converter'Access);
-- Application.Add_Converter (Name => "smartDateConverter",
-- Converter => Rel_Date_Converter'Access);
--
-- WS.Register_Application ("/asfunit", Application.all'Access);
--
-- WS.Start;
-- delay 6000.0;
-- end;
-- end if;
Servlet.Server.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
Add OAuth_Provider_Factory function and create a fake OAuth provider Setup the OAuth_Provider_Factory for the unit tests
|
Add OAuth_Provider_Factory function and create a fake OAuth provider
Setup the OAuth_Provider_Factory for the unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ce7747d088d473d0901d8b1fb37489da115a6e41
|
src/natools-time_statistics-generic_timers.adb
|
src/natools-time_statistics-generic_timers.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Time_Statistics.Generic_Timers is
------------------
-- Manual Timer --
------------------
not overriding procedure Start (Timer : in out Manual_Timer) is
begin
Timer.Start_Time := Now;
Timer.Running := True;
end Start;
not overriding procedure Stop (Timer : in out Manual_Timer) is
begin
Timer.Backend.Add (Timer.Start_Time - Now);
Timer.Running := False;
end Stop;
not overriding procedure Cancel (Timer : in out Manual_Timer) is
begin
Timer.Running := False;
end Cancel;
---------------------
-- Automatic Timer --
---------------------
not overriding procedure Cancel (Timer : in out Auto_Timer) is
begin
Timer.Reported := True;
end Cancel;
overriding procedure Initialize (Object : in out Auto_Timer) is
begin
Object.Start_Time := Now;
Object.Reported := False;
end Initialize;
overriding procedure Finalize (Object : in out Auto_Timer) is
begin
if not Object.Reported then
Object.Backend.Add (Object.Start_Time - Now);
Object.Reported := True;
end if;
end Finalize;
end Natools.Time_Statistics.Generic_Timers;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Time_Statistics.Generic_Timers is
------------------
-- Manual Timer --
------------------
not overriding procedure Start (Timer : in out Manual_Timer) is
begin
Timer.Start_Time := Now;
Timer.Running := True;
end Start;
not overriding procedure Stop (Timer : in out Manual_Timer) is
begin
Timer.Backend.Add (Now - Timer.Start_Time);
Timer.Running := False;
end Stop;
not overriding procedure Cancel (Timer : in out Manual_Timer) is
begin
Timer.Running := False;
end Cancel;
---------------------
-- Automatic Timer --
---------------------
not overriding procedure Cancel (Timer : in out Auto_Timer) is
begin
Timer.Reported := True;
end Cancel;
overriding procedure Initialize (Object : in out Auto_Timer) is
begin
Object.Start_Time := Now;
Object.Reported := False;
end Initialize;
overriding procedure Finalize (Object : in out Auto_Timer) is
begin
if not Object.Reported then
Object.Backend.Add (Now - Object.Start_Time);
Object.Reported := True;
end if;
end Finalize;
end Natools.Time_Statistics.Generic_Timers;
|
fix stupid sign mistake
|
time_statistics-generic_timers: fix stupid sign mistake
|
Ada
|
isc
|
faelys/natools
|
42fbde62585f6ba3eb4f4fcba69d6fb2bcc462c8
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.ads
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.ads
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Util.Properties;
with AWS.SMTP;
-- The <b>AWA.Mail.Clients.AWS_SMTP</b> package provides an implementation of the
-- mail client interfaces on top of AWS SMTP client API.
package AWA.Mail.Clients.AWS_SMTP is
NAME : constant String := "smtp";
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>Mail_Message</b> represents an abstract mail message that can be initialized
-- before being sent.
type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with private;
type AWS_Mail_Message_Access is access all AWS_Mail_Message'Class;
-- Set the <tt>From</tt> part of the message.
overriding
procedure Set_From (Message : in out AWS_Mail_Message;
Name : in String;
Address : in String);
-- Add a recipient for the message.
overriding
procedure Add_Recipient (Message : in out AWS_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String);
-- Set the subject of the message.
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String);
-- Set the body of the message.
overriding
procedure Set_Body (Message : in out AWS_Mail_Message;
Content : in String);
-- Send the email message.
overriding
procedure Send (Message : in out AWS_Mail_Message);
-- Deletes the mail message.
overriding
procedure Finalize (Message : in out AWS_Mail_Message);
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type AWS_Mail_Manager is new Mail_Manager with private;
type AWS_Mail_Manager_Access is access all AWS_Mail_Manager'Class;
-- Create a SMTP based mail manager and configure it according to the properties.
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access;
-- Create a new mail message.
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access;
private
type Recipients_Access is access all AWS.SMTP.Recipients;
type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with record
Manager : AWS_Mail_Manager_Access;
From : AWS.SMTP.E_Mail_Data;
Subject : Ada.Strings.Unbounded.Unbounded_String;
Content : Ada.Strings.Unbounded.Unbounded_String;
To : Recipients_Access := null;
end record;
type AWS_Mail_Manager is new Mail_Manager with record
Self : AWS_Mail_Manager_Access;
Server : AWS.SMTP.Receiver;
Enable : Boolean := True;
end record;
end AWA.Mail.Clients.AWS_SMTP;
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Util.Properties;
with AWS.SMTP;
with AWS.SMTP.Authentication.Plain;
-- The <b>AWA.Mail.Clients.AWS_SMTP</b> package provides an implementation of the
-- mail client interfaces on top of AWS SMTP client API.
package AWA.Mail.Clients.AWS_SMTP is
NAME : constant String := "smtp";
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>Mail_Message</b> represents an abstract mail message that can be initialized
-- before being sent.
type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with private;
type AWS_Mail_Message_Access is access all AWS_Mail_Message'Class;
-- Set the <tt>From</tt> part of the message.
overriding
procedure Set_From (Message : in out AWS_Mail_Message;
Name : in String;
Address : in String);
-- Add a recipient for the message.
overriding
procedure Add_Recipient (Message : in out AWS_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String);
-- Set the subject of the message.
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String);
-- Set the body of the message.
overriding
procedure Set_Body (Message : in out AWS_Mail_Message;
Content : in String);
-- Send the email message.
overriding
procedure Send (Message : in out AWS_Mail_Message);
-- Deletes the mail message.
overriding
procedure Finalize (Message : in out AWS_Mail_Message);
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type AWS_Mail_Manager is new Mail_Manager with private;
type AWS_Mail_Manager_Access is access all AWS_Mail_Manager'Class;
-- Create a SMTP based mail manager and configure it according to the properties.
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access;
-- Create a new mail message.
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access;
private
type Recipients_Access is access all AWS.SMTP.Recipients;
type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with record
Manager : AWS_Mail_Manager_Access;
From : AWS.SMTP.E_Mail_Data;
Subject : Ada.Strings.Unbounded.Unbounded_String;
Content : Ada.Strings.Unbounded.Unbounded_String;
To : Recipients_Access := null;
end record;
type AWS_Mail_Manager is new Mail_Manager with record
Self : AWS_Mail_Manager_Access;
Server : AWS.SMTP.Receiver;
Creds : aliased AWS.SMTP.Authentication.Plain.Credential;
Enable : Boolean := True;
Secure : Boolean := False;
Auth : Boolean := False;
end record;
end AWA.Mail.Clients.AWS_SMTP;
|
Add credention support and SSL support for mail
|
Add credention support and SSL support for mail
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
628a123778156b9de067bc7d4817c38229989c4d
|
src/util-streams-pipes.ads
|
src/util-streams-pipes.ads
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Processes;
-- The <b>Util.Streams.Pipes</b> package defines a pipe stream to or from a process.
-- The process is created and launched by the <b>Open</b> operation. The pipe allows
-- to read or write to the process through the <b>Read</b> and <b>Write</b> operation.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Pipe_Stream is new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Pipe_Stream);
end Util.Streams.Pipes;
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 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.Finalization;
with Util.Processes;
-- The <b>Util.Streams.Pipes</b> package defines a pipe stream to or from a process.
-- The process is created and launched by the <b>Open</b> operation. The pipe allows
-- to read or write to the process through the <b>Read</b> and <b>Write</b> operation.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Pipe_Stream);
end Util.Streams.Pipes;
|
Fix compilation error with GNAT 2015
|
Fix compilation error with GNAT 2015
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
89acbc495d4cf27ae375e49a782f77fa344b7dd4
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
-----------------------------------------------------------------------
-- 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 AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with ADO.Sessions;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.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);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
Ctx : constant Services.Contexts.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);
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Ctx.Start;
Page.Set_Wiki (Into);
Page.Save (DB);
Ctx.Commit;
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
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 AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with ADO.Sessions;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.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);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
Ctx : constant Services.Contexts.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);
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Ctx.Start;
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Page.Save (DB);
Ctx.Commit;
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
end AWA.Wikis.Modules;
|
Set the wiki page Is_Public member according to the Wiki_Space Is_Public when we create the wiki page
|
Set the wiki page Is_Public member according to the Wiki_Space
Is_Public when we create the wiki page
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d6ecbb984bb236e5dfec4426c09d3fb1d73f330c
|
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
|
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with ADO.Sessions;
with AWA.Events;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with Security.Permissions;
-- == Events ==
-- The <tt>wikis</tt> exposes a number of events which are posted when some action
-- are performed at the service level.
--
-- === wiki-create-page ===
-- This event is posted when a new wiki page is created.
--
-- === wiki-create-content ===
-- This event is posted when a new wiki page content is created. Each time a wiki page is
-- modified, a new wiki page content is created and this event is posted.
--
package AWA.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create");
package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete");
package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update");
package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view");
-- Define the permissions.
package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create");
package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete");
package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update");
-- Event posted when a new wiki page is created.
package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page");
-- Event posted when a new wiki content is created.
package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content");
package Wiki_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class);
subtype Listener is Wiki_Lifecycle.Listener;
-- The configuration parameter that defines a list of wiki page ID to copy when a new
-- wiki space is created.
PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list";
-- ------------------------------
-- Module wikis
-- ------------------------------
type Wiki_Module is new AWA.Modules.Module with private;
type Wiki_Module_Access is access all Wiki_Module'Class;
-- Initialize the wikis module.
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the wikis module.
function Get_Wiki_Module return Wiki_Module_Access;
-- Create the wiki space.
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Save the wiki space.
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Load the wiki space.
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier);
-- Create the wiki page into the wiki space.
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save the wiki page.
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Load the wiki page and its content.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier);
-- Load the wiki page and its content from the wiki space Id and the page name.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String);
-- Create a new wiki content for the wiki page.
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
private
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier);
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
type Wiki_Module is new AWA.Modules.Module with null record;
end AWA.Wikis.Modules;
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with ADO.Sessions;
with AWA.Events;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with Security.Permissions;
-- == Events ==
-- The <tt>wikis</tt> exposes a number of events which are posted when some action
-- are performed at the service level.
--
-- === wiki-create-page ===
-- This event is posted when a new wiki page is created.
--
-- === wiki-create-content ===
-- This event is posted when a new wiki page content is created. Each time a wiki page is
-- modified, a new wiki page content is created and this event is posted.
--
package AWA.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create");
package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete");
package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update");
package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view");
-- Define the permissions.
package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create");
package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete");
package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update");
-- Event posted when a new wiki page is created.
package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page");
-- Event posted when a new wiki content is created.
package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content");
package Wiki_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class);
subtype Listener is Wiki_Lifecycle.Listener;
-- The configuration parameter that defines a list of wiki page ID to copy when a new
-- wiki space is created.
PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list";
-- ------------------------------
-- Module wikis
-- ------------------------------
type Wiki_Module is new AWA.Modules.Module with private;
type Wiki_Module_Access is access all Wiki_Module'Class;
-- Initialize the wikis module.
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the wikis module.
function Get_Wiki_Module return Wiki_Module_Access;
-- Create the wiki space.
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Save the wiki space.
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Load the wiki space.
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier);
-- Create the wiki page into the wiki space.
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save the wiki page.
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Delete the wiki page as well as all its versions.
procedure Delete (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Load the wiki page and its content.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier);
-- Load the wiki page and its content from the wiki space Id and the page name.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String);
-- Create a new wiki content for the wiki page.
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
private
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier);
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
type Wiki_Module is new AWA.Modules.Module with null record;
end AWA.Wikis.Modules;
|
Declare the Delete procedure to delete a wiki page
|
Declare the Delete procedure to delete a wiki page
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
00cff5bb79e643a3870b858068caf5783c5ee6d7
|
src/security-controllers-roles.adb
|
src/security-controllers-roles.adb
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Mappers.Record_Mapper;
package body Security.Controllers.Roles is
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
-- ------------------------------
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is
use type Security.Principal_Access;
P : constant Security.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
for I in Handler.Roles'Range loop
-- if P.Has_Role (Handler.Roles (I)) then
return True;
-- end if;
end loop;
end if;
return False;
end Has_Permission;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Permissions.Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Manager;
Config_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Controllers.Roles;
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Mappers.Record_Mapper;
package body Security.Controllers.Roles is
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
-- ------------------------------
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
use type Security.Principal_Access;
P : constant Security.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
for I in Handler.Roles'Range loop
-- if P.Has_Role (Handler.Roles (I)) then
return True;
-- end if;
end loop;
end if;
return False;
end Has_Permission;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Permissions.Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Manager;
Config_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Controllers.Roles;
|
Add permission parameter
|
Add permission parameter
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
c71e4478959fbb921ee633d8a43406797e0ee4c1
|
src/gen-artifacts-query.adb
|
src/gen-artifacts-query.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-query -- Query artifact for Code Generator
-- 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 Ada.Directories;
with Gen.Utils;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Util.Log.Loggers;
with Util.Encoders.HMAC.SHA1;
-- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of
-- data structures returned by queries.
package body Gen.Artifacts.Query is
use Ada.Strings.Unbounded;
use Gen.Model;
use Gen.Model.Tables;
use Gen.Model.Queries;
use type DOM.Core.Node;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
-- ------------------------------
procedure Initialize (Handler : in Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node);
procedure Register_Columns (Table : in out Query_Definition);
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node);
Hash : Unbounded_String;
-- ------------------------------
-- Register the column definition in the table
-- ------------------------------
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Model.Get_Attribute (Column, "name");
C : constant Column_Definition_Access := new Column_Definition;
begin
C.Node := Column;
C.Number := Table.Members.Get_Count;
Table.Members.Append (C);
C.Type_Name := To_Unbounded_String (Get_Normalized_Type (Column, "type"));
C.Is_Inserted := False;
C.Is_Updated := False;
C.Not_Null := False;
C.Unique := False;
-- Construct the hash for this column mapping.
Append (Hash, ",type=");
Append (Hash, C.Type_Name);
Append (Hash, ",name=");
Append (Hash, Name);
end Register_Column;
-- ------------------------------
-- Register all the columns defined in the table
-- ------------------------------
procedure Register_Columns (Table : in out Query_Definition) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Column);
begin
Log.Debug ("Register columns from query {0}", Table.Name);
Iterate (Table, Table.Node, "property");
end Register_Columns;
-- ------------------------------
-- Register a new class definition in the model.
-- ------------------------------
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Model.Get_Attribute (Node, "name");
begin
Query.Node := Node;
Query.Set_Table_Name (Query.Get_Attribute ("name"));
if Name /= "" then
Query.Name := Name;
else
Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path));
end if;
-- Construct the hash for this column mapping.
Append (Hash, "class=");
Append (Hash, Query.Name);
Log.Debug ("Register query {0} with type {0}", Query.Name, Query.Type_Name);
Register_Columns (Query);
end Register_Mapping;
-- ------------------------------
-- Register a new query.
-- ------------------------------
procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node) is
C : constant Column_Definition_Access := new Column_Definition;
begin
C.Node := Node;
C.Number := Query.Queries.Get_Count;
Query.Queries.Append (C);
end Register_Query;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate_Mapping is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition,
Process => Register_Mapping);
procedure Iterate_Query is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition,
Process => Register_Query);
Table : constant Query_Definition_Access := new Query_Definition;
Pkg : constant Unbounded_String := Gen.Model.Get_Attribute (Node, "package");
begin
Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path));
Table.Pkg_Name := Pkg;
Iterate_Mapping (Query_Definition (Table.all), Node, "class");
Iterate_Query (Query_Definition (Table.all), Node, "query");
if Length (Table.Pkg_Name) = 0 then
Context.Error ("Missing or empty package attribute");
else
Model.Register_Query (Table);
end if;
Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash));
Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries",
Data => To_String (Hash));
end Register_Mapping;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
begin
Log.Debug ("Initializing query artifact for the configuration");
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping");
end Initialize;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (Handler : in Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
begin
Log.Debug ("Preparing the model for query");
if Model.Has_Packages then
Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE);
Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE);
end if;
end Prepare;
end Gen.Artifacts.Query;
|
-----------------------------------------------------------------------
-- gen-artifacts-query -- Query artifact for Code Generator
-- 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 Ada.Directories;
with Gen.Utils;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Util.Log.Loggers;
with Util.Encoders.HMAC.SHA1;
-- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of
-- data structures returned by queries.
package body Gen.Artifacts.Query is
use Ada.Strings.Unbounded;
use Gen.Model;
use Gen.Model.Tables;
use Gen.Model.Queries;
use type DOM.Core.Node;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
-- ------------------------------
procedure Initialize (Handler : in Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node);
procedure Register_Columns (Table : in out Query_Definition);
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node);
Hash : Unbounded_String;
-- ------------------------------
-- Register the column definition in the table
-- ------------------------------
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Model.Get_Attribute (Column, "name");
C : constant Column_Definition_Access := new Column_Definition;
begin
C.Node := Column;
C.Number := Table.Members.Get_Count;
Table.Members.Append (C);
C.Type_Name := To_Unbounded_String (Get_Normalized_Type (Column, "type"));
C.Is_Inserted := False;
C.Is_Updated := False;
C.Not_Null := False;
C.Unique := False;
-- Construct the hash for this column mapping.
Append (Hash, ",type=");
Append (Hash, C.Type_Name);
Append (Hash, ",name=");
Append (Hash, Name);
end Register_Column;
-- ------------------------------
-- Register all the columns defined in the table
-- ------------------------------
procedure Register_Columns (Table : in out Query_Definition) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Column);
begin
Log.Debug ("Register columns from query {0}", Table.Name);
Iterate (Table, Table.Node, "property");
end Register_Columns;
-- ------------------------------
-- Register a new class definition in the model.
-- ------------------------------
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Model.Get_Attribute (Node, "name");
begin
Query.Node := Node;
Query.Set_Table_Name (Query.Get_Attribute ("name"));
if Name /= "" then
Query.Name := Name;
else
Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path));
end if;
-- Construct the hash for this column mapping.
Append (Hash, "class=");
Append (Hash, Query.Name);
Log.Debug ("Register query {0} with type {0}", Query.Name, Query.Type_Name);
Register_Columns (Query);
end Register_Mapping;
-- ------------------------------
-- Register a new query.
-- ------------------------------
procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node) is
C : constant Column_Definition_Access := new Column_Definition;
begin
C.Node := Node;
C.Number := Query.Queries.Get_Count;
Query.Queries.Append (C);
end Register_Query;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate_Mapping is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition,
Process => Register_Mapping);
procedure Iterate_Query is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition,
Process => Register_Query);
Table : constant Query_Definition_Access := new Query_Definition;
Pkg : constant Unbounded_String := Gen.Model.Get_Attribute (Node, "package");
begin
Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path));
Table.Pkg_Name := Pkg;
Table.Node := Node;
Iterate_Mapping (Query_Definition (Table.all), Node, "class");
Iterate_Query (Query_Definition (Table.all), Node, "query");
if Length (Table.Pkg_Name) = 0 then
Context.Error ("Missing or empty package attribute");
else
Model.Register_Query (Table);
end if;
Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash));
Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries",
Data => To_String (Hash));
end Register_Mapping;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
begin
Log.Debug ("Initializing query artifact for the configuration");
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping");
end Initialize;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (Handler : in Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
begin
Log.Debug ("Preparing the model for query");
if Model.Has_Packages then
Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE);
Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE);
end if;
end Prepare;
end Gen.Artifacts.Query;
|
Fix crash when an XML query does not specify a class mapping
|
Fix crash when an XML query does not specify a class mapping
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
d356564999c004cc400b62cb9621a65fd230f042
|
src/mysql/mysql.ads
|
src/mysql/mysql.ads
|
-----------------------------------------------------------------------
-- ADO Mysql -- Mysql Interface
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Mysql is
end Mysql;
|
-----------------------------------------------------------------------
-- ADO Mysql -- Mysql Interface
-- Copyright (C) 2009, 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.
-----------------------------------------------------------------------
package Mysql is
pragma Pure;
end Mysql;
|
Make the package Pure
|
Make the package Pure
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
ec43002b1643904b6542cbe2e3127b46146190cc
|
examples/functions_example.adb
|
examples/functions_example.adb
|
-- Functions_Example
-- A example of using the Ada 2012 interface to Lua for functions / closures etc
-- Copyright (c) 2015, James Humphry - see LICENSE.md for terms
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Characters.Latin_1;
with Lua; use Lua;
with Lua.Libs;
with Lua.Util; use Lua.Util;
with Example_AdaFunctions;
procedure Functions_Example is
L : Lua_State;
Success : Thread_Status;
R : Lua_Reference;
LF : Character renames Ada.Characters.Latin_1.LF;
Coroutine_Source : String := "" &
"function co (x) " & LF &
" for i = 1, x do " & LF &
" yield(i) " & LF &
" end " & LF &
" return -1 " & LF &
" end " & LF &
"";
begin
Put_Line("A simple example of using Lua and Ada functions together");
Put("Lua version: ");
Put(Item => L.Version, Aft => 0, Exp => 0);
New_Line; New_Line;
Put_Line("Loading chunk: function f (x) return 2*x end");
Success := L.LoadString("function f (x) return 2*x end");
Put_Line("Load" & (if Success /= OK then " not" else "") & " successful.");
L.Call(0, 0);
Put_Line("Compiled chunk.");
Put("Result of calling f (3): ");
L.PushInteger(3);
L.Call_Function(name => "f", nargs => 1, nresults => 1);
Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line;
New_Line;
Put_Line("Saving a reference to the top of the stack and clearing it.");
R := Ref(L);
L.Pop(L.GetTop);
Print_Stack(L);
Put_Line("Retrieving reference...");
L.Get(R);
Print_Stack(L);
New_Line;
Put_Line("Loading IO library and running example Lua file");
Libs.Require_Standard_Library(L, LIbs.IO_Lib);
Success := L.LoadFile("examples/example_lua.lua");
Put_Line("Load" & (if Success /= OK then " not" else "") & " successful.");
if Success = OK then
L.Call(0, 0);
Put_Line("Compiled chunk. Result of calling triangle (5):");
L.PushNumber(5.0);
L.Call_Function(name => "triangle", nargs => 1, nresults => 0);
end if;
New_Line;
L.Pop(L.GetTop);
Put_Line("Registering an AdaFunction foobar in Lua");
L.Register("foobar", AdaFunction'(Example_AdaFunctions.Foobar'Access));
Success := L.LoadString("baz = foobar(5.0)");
Put_Line("Loading code snippet 'baz = foobar(5.0)'" &
(if Success /= OK then " not" else "") & " successful.");
Put_Line("Calling 'baz = foobar(5.0)' from Lua");
L.Call(0, 0);
Put("baz = ");
L.GetGlobal("baz");
Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line;
New_Line;
L.Pop(L.GetTop);
Put_Line("Checking foobar can be retrieved");
L.GetGlobal("foobar");
if not L.IsAdaFunction(-1) then
Put_Line("Error - foobar does not contain an AdaFunction?");
end if;
if L.ToAdaFunction(-1) = AdaFunction'(Example_AdaFunctions.Foobar'Access) then
Put_Line("AdaFunction foobar retrieved successfully from Lua");
else
Put_Line("AdaFunction foobar was NOT retrieved from Lua");
end if;
New_Line;
L.Pop(L.GetTop);
Put_Line("Registering an AdaFunction multret in Lua");
L.Register("multret", AdaFunction'(Example_AdaFunctions.Multret'Access));
Put_Line("Calling 'multret(5)' from Lua");
L.PushInteger(5);
L.Call_Function(name => "multret", nargs => 1, nresults => MultRet_Sentinel);
Print_Stack(L);
New_Line;
L.Pop(L.GetTop);
Put_Line("Registering an AdaFunction closure (with upvalue 2.0) in Lua");
L.PushNumber(2.0);
L.PushAdaClosure(AdaFunction'(Example_AdaFunctions.Closure'Access), 1);
L.SetGlobal("closure");
Put_Line("Calling 'closure(3.5)' from Lua");
L.PushNumber(3.5);
L.Call_Function(name => "closure", nargs => 1, nresults => MultRet_Sentinel);
Print_Stack(L);
New_Line;
L.Pop(L.GetTop);
Put_Line("Now to look at using coroutines");
Libs.Add_Yield_Function(L);
Put_Line("Loading coroutine source: ");
Put_Line(Coroutine_Source);
Success := L.LoadString(Coroutine_Source);
Put_Line("Load" & (if Success /= OK then " not" else "") & " successful.");
L.Call(0, 0);
Put_Line("Compiled coroutine code.");
declare
Coroutine : Lua_Thread := L.NewThread;
Coroutine_Status : Thread_Status;
begin
Put_Line("New thread created");
Put_Line("Resuming coroutine with parameter 3 in this thread:");
Coroutine.GetGlobal("co");
Coroutine.PushInteger(3);
Coroutine_Status := Coroutine.resume(L, 1);
Put("Coroutine status : " & Thread_Status'Image(Coroutine_Status));
Put(" Result: "); Put(Coroutine.ToNumber(-1)); New_Line;
while Coroutine_Status = YIELD loop
Coroutine_Status := Coroutine.resume(L, 1);
Put("Coroutine status : " & Thread_Status'Image(Coroutine_Status));
Put(" Result: "); Put(Coroutine.ToNumber(-1)); New_Line;
end loop;
end;
New_Line;
L.Pop(L.GetTop);
declare
S : Lua_Reference := R;
begin
Put_Line("Retrieving a copy of reference saved earlier...");
L.Get(S);
Print_Stack(L);
end;
Put_Line("Retrieving reference saved earlier...");
L.Get(R);
Print_Stack(L);
New_Line;
end Functions_Example;
|
-- Functions_Example
-- A example of using the Ada 2012 interface to Lua for functions / closures etc
-- Copyright (c) 2015, James Humphry - see LICENSE.md for terms
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Characters.Latin_1;
with Lua; use Lua;
with Lua.Libs;
with Lua.Util; use Lua.Util;
with Example_AdaFunctions;
procedure Functions_Example is
L : Lua_State;
Success : Thread_Status;
R : Lua_Reference;
LF : Character renames Ada.Characters.Latin_1.LF;
Coroutine_Source : String := "" &
"function co (x) " & LF &
" for i = 1, x do " & LF &
" yield(i) " & LF &
" end " & LF &
" return -1 " & LF &
" end " & LF &
"";
begin
Put_Line("A simple example of using Lua and Ada functions together");
Put("Lua version: ");
Put(Item => L.Version, Aft => 0, Exp => 0);
New_Line; New_Line;
Put_Line("Loading chunk: function f (x) return 2*x end");
Success := L.LoadString("function f (x) return 2*x end");
Put_Line("Load" & (if Success /= OK then " not" else "") & " successful.");
L.Call(0, 0);
Put_Line("Compiled chunk.");
Put("Result of calling f (3): ");
L.PushInteger(3);
L.Call_Function(name => "f", nargs => 1, nresults => 1);
Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line;
New_Line;
Put_Line("Saving a reference to the top of the stack and clearing it.");
R := Ref(L);
L.Pop(L.GetTop);
Print_Stack(L);
Put_Line("Retrieving reference...");
L.Get(R);
Print_Stack(L);
New_Line;
Put_Line("Loading IO library and running example Lua file");
Libs.Require_Standard_Library(L, LIbs.IO_Lib);
Success := L.LoadFile("examples/example_lua.lua");
Put_Line("Load" & (if Success /= OK then " not" else "") & " successful.");
if Success = OK then
L.Call(0, 0);
Put_Line("Compiled chunk. Result of calling triangle (5):");
L.PushNumber(5.0);
L.Call_Function(name => "triangle", nargs => 1, nresults => 0);
end if;
New_Line;
L.Pop(L.GetTop);
Put_Line("Registering an AdaFunction foobar in Lua");
L.Register("foobar", AdaFunction'(Example_AdaFunctions.Foobar'Access));
Success := L.LoadString("baz = foobar(5.0)");
Put_Line("Loading code snippet 'baz = foobar(5.0)'" &
(if Success /= OK then " not" else "") & " successful.");
Put_Line("Calling 'baz = foobar(5.0)' from Lua");
L.Call(0, 0);
Put("baz = ");
L.GetGlobal("baz");
Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line;
New_Line;
L.Pop(L.GetTop);
Put_Line("Checking foobar can be retrieved");
L.GetGlobal("foobar");
if not L.IsAdaFunction(-1) then
Put_Line("Error - foobar does not contain an AdaFunction?");
end if;
if L.ToAdaFunction(-1) = AdaFunction'(Example_AdaFunctions.Foobar'Access) then
Put_Line("AdaFunction foobar retrieved successfully from Lua");
else
Put_Line("AdaFunction foobar was NOT retrieved from Lua");
end if;
New_Line;
L.Pop(L.GetTop);
Put_Line("Registering an AdaFunction multret in Lua");
L.Register("multret", AdaFunction'(Example_AdaFunctions.Multret'Access));
Put_Line("Calling 'multret(5)' from Lua");
L.PushInteger(5);
L.Call_Function(name => "multret", nargs => 1, nresults => MultRet_Sentinel);
Print_Stack(L);
New_Line;
L.Pop(L.GetTop);
Put_Line("Registering an AdaFunction closure (with upvalue 2.0) in Lua");
L.PushNumber(2.0);
L.PushAdaClosure(AdaFunction'(Example_AdaFunctions.Closure'Access), 1);
L.SetGlobal("closure");
Put_Line("Calling 'closure(3.5)' from Lua");
L.PushNumber(3.5);
L.Call_Function(name => "closure", nargs => 1, nresults => MultRet_Sentinel);
Print_Stack(L);
New_Line;
L.Pop(L.GetTop);
Put_Line("Now to look at using coroutines");
Libs.Add_Yield_Function(L);
Put_Line("Loading coroutine source: ");
Put_Line(Coroutine_Source);
Success := L.LoadString(Coroutine_Source);
Put_Line("Load" & (if Success /= OK then " not" else "") & " successful.");
L.Call(0, 0);
Put_Line("Compiled coroutine code.");
declare
Coroutine : Lua_Thread := L.NewThread;
Coroutine_Status : Thread_Status;
begin
Put_Line("New thread created");
Put_Line("Resuming coroutine with parameter 3 in this thread:");
Coroutine.GetGlobal("co");
Coroutine.PushInteger(3);
Coroutine_Status := Coroutine.resume(L, 1);
Put("Coroutine status : " & Thread_Status'Image(Coroutine_Status));
Put(" Result: "); Put(Coroutine.ToNumber(-1)); New_Line;
L.Pop(1); -- argument no longer needed in this example
while Coroutine_Status = YIELD loop
Coroutine_Status := Coroutine.resume(from => L, nargs => 0);
Put("Coroutine status : " & Thread_Status'Image(Coroutine_Status));
Put(" Result: "); Put(Coroutine.ToNumber(-1)); New_Line;
end loop;
end;
New_Line;
L.Pop(L.GetTop);
declare
S : Lua_Reference := R;
begin
Put_Line("Retrieving a copy of reference saved earlier...");
L.Get(S);
Print_Stack(L);
end;
Put_Line("Retrieving reference saved earlier...");
L.Get(R);
Print_Stack(L);
New_Line;
end Functions_Example;
|
Correct example usage of coroutine
|
Correct example usage of coroutine
In the example for using coroutines, the coroutine was only accepting a
value the first time, so it is superfluous to keep passing it to the
Lua code.
|
Ada
|
mit
|
jhumphry/aLua
|
21862c486bd120f36287e772118c60447c7157a7
|
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;
private with Util.Concurrent.Counters;
private with Util.Beans.Objects.Maps;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Ada.Strings.Unbounded.Unbounded_String;
function "+" (S : String) return Value renames To_Unbounded_String;
function "-" (S : Value) return String renames To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name, Item : Value));
type Name_Array is array (Natural range <>) of Value;
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array;
-- 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;
type Manager_Factory is access function return Manager_Access;
-- 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 Value) 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, Item : Value)) is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
procedure Delete (Self : in Manager; Obj : in out Manager_Access)
is abstract;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is abstract;
end Interface_P;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access);
-- 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;
private with Util.Concurrent.Counters;
private with Util.Beans.Objects.Maps;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Ada.Strings.Unbounded.Unbounded_String;
function "+" (S : String) return Value renames To_Unbounded_String;
function "-" (S : Value) return String renames To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name, Item : Value));
type Name_Array is array (Natural range <>) of Value;
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array;
-- 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;
type Manager_Factory is access function return Manager_Access;
-- 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 Value) 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, Item : Value)) is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is abstract;
end Interface_P;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access);
-- 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;
|
Remove the Delete operation because we don't need it
|
Remove the Delete operation because we don't need it
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b74d0ed21adff625bb1048db309f9e1357fa4724
|
src/ado-sessions.ads
|
src/ado-sessions.ads
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Databases;
with ADO.Queries;
with ADO.SQL;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
-- == Session ==
-- The <tt>ADO.Sessions</tt> package defines the control and management of database sessions.
-- The database session is represented by the <tt>Session</tt> or <tt>Master_Session</tt> types.
--
-- @include ado-sessions-factory.ads
--
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return ADO.Databases.Connection_Status;
-- Close the session.
procedure Close (Database : in out Session);
-- Get the database connection.
function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class;
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access constant ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
--
-- type Session_Proxy is limited record
-- Counter : Util.Concurrent.Counters.Counter;
-- Session : Session_Record_Access;
-- Factory : Object_Factory_Access;
-- end record;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Database : ADO.Databases.Master_Connection;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access all ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class;
Message : in String := "");
pragma Inline (Check_Session);
end ADO.Sessions;
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Databases;
with ADO.Queries;
with ADO.SQL;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
-- == Session ==
-- The <tt>ADO.Sessions</tt> package defines the control and management of database sessions.
-- The database session is represented by the <tt>Session</tt> or <tt>Master_Session</tt> types.
--
-- @include ado-sessions-factory.ads
--
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return ADO.Databases.Connection_Status;
-- Close the session.
procedure Close (Database : in out Session);
-- Get the database connection.
function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class;
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition);
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access constant ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
--
-- type Session_Proxy is limited record
-- Counter : Util.Concurrent.Counters.Counter;
-- Session : Session_Record_Access;
-- Factory : Object_Factory_Access;
-- end record;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Database : ADO.Databases.Master_Connection;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access all ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class;
Message : in String := "");
pragma Inline (Check_Session);
end ADO.Sessions;
|
Declare the Load_Schema procedure
|
Declare the Load_Schema procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
431cc35b6163c2aee48e9e51753ce05d04a2ad60
|
src/pc/multiboot.ads
|
src/pc/multiboot.ads
|
-- -*- Mode: Ada -*-
-- Filename : multiboot.ads
-- Description : Provides access to the multiboot information from GRUB
-- Legacy and GRUB 2.
-- Author : Luke A. Guest
-- Created On : Fri Jun 15 14:43:04 2012
-- Licence : See LICENCE in the root directory.
with System;
with Interfaces; use Interfaces;
package Multiboot is
subtype Magic_Values is Unsigned_32;
Magic_Value : constant Magic_Values := 16#2BAD_B002#;
type MB_Info;
----------------------------------------------------------------------------
-- Multiboot information.
----------------------------------------------------------------------------
type Features is
record
Memory : Boolean; -- Bit 0
Boot_Device : Boolean; -- Bit 1
Command_Line : Boolean; -- Bit 2
Modules : Boolean; -- Bit 3
Symbol_Table : Boolean; -- Bit 4 - this is Aout only.
Section_Header_Table : Boolean; -- Bit 5 - this is ELF only.
BIOS_Memory_Map : Boolean; -- Bit 6
Drives : Boolean; -- Bit 7
ROM_Configuration : Boolean; -- Bit 8
Boot_Loader : Boolean; -- Bit 9
APM_Table : Boolean; -- Bit 10
Graphics_Table : Boolean; -- Bit 11
end record;
for Features use
record
Memory at 0 range 0 .. 0;
Boot_Device at 0 range 1 .. 1;
Command_Line at 0 range 2 .. 2;
Modules at 0 range 3 .. 3;
Symbol_Table at 0 range 4 .. 4;
Section_Header_Table at 0 range 5 .. 5;
BIOS_Memory_Map at 0 range 6 .. 6;
Drives at 0 range 7 .. 7;
ROM_Configuration at 1 range 0 .. 0;
Boot_Loader at 1 range 1 .. 1;
APM_Table at 1 range 2 .. 2;
Graphics_Table at 1 range 3 .. 3;
end record;
for Features'Size use 32;
----------------------------------------------------------------------------
-- Boot device information.
----------------------------------------------------------------------------
type Boot_Devices is
record
Drive : Unsigned_8;
Partition_1 : Unsigned_8;
Partition_2 : Unsigned_8;
Partition_3 : Unsigned_8;
end record;
for Boot_Devices use
record
Drive at 0 range 0 .. 7;
Partition_1 at 1 range 0 .. 7;
Partition_2 at 2 range 0 .. 7;
Partition_3 at 3 range 0 .. 7;
end record;
for Boot_Devices'Size use 32;
Invalid_Partition : constant Unsigned_8 := 16#ff#;
----------------------------------------------------------------------------
-- Memory information.
-- These values are in KB
----------------------------------------------------------------------------
type Memory_Info is
record
Upper : Unsigned_32;
Lower : Unsigned_32;
end record;
pragma Convention (C, Memory_Info);
----------------------------------------------------------------------------
-- Loadable module information.
----------------------------------------------------------------------------
type Modules is
record
First : System.Address; -- Address of module start .. end.
Last : System.Address;
Data : System.Address; -- NULL terminated C string.
Reserved : Unsigned_32; -- Should be 0.
end record;
type Modules_Array is array (Natural range <>) of Modules;
pragma Convention (C, Modules_Array);
-- type Modules_Array_Access is access Modules_Array;
-- pragma Convention (C, Modules_Array_Access);
type Modules_Info is
record
Count : Unsigned_32;
First : System.Address;
end record;
----------------------------------------------------------------------------
-- Symbols information.
----------------------------------------------------------------------------
pragma Convention (C, Modules_Info);
type Symbols_Variant is (Aout, ELF);
function Get_Symbols_Variant return Symbols_Variant;
----------------------------------------------------------------------------
-- a.out symbols or ELF sections
--
-- TODO: a.out only - This can be implemented by anyone who wants to use
-- aout.
--
-- From what I can tell from the spec, Addr points to a size followed by
-- an array of a.out nlist structures. This is then followed by a size
-- of a set of strings, then the sizeof (unsigned), then the strings
-- (NULL terminated).
--
-- Table_Size and String_Size are the same as the ones listed above.
----------------------------------------------------------------------------
type Symbols (Variant : Symbols_Variant := ELF) is
record
case Variant is
when Aout =>
Table_Size : Unsigned_32;
String_Size : Unsigned_32;
Aout_Addr : System.Address;
Reserved : Unsigned_32; -- Always 0.
when ELF =>
Number : Unsigned_32;
Size : Unsigned_32;
ELF_Addr : System.Address;
Shndx : Unsigned_32;
end case;
end record;
pragma Convention (C, Symbols);
pragma Unchecked_Union (Symbols);
----------------------------------------------------------------------------
-- Memory map information.
----------------------------------------------------------------------------
type Memory_Type is range Unsigned_32'First .. Unsigned_32'Last;
for Memory_Type'Size use 32;
Memory_Available : constant Memory_Type := 1;
Memory_Reserved : constant Memory_Type := 2;
type Memory_Map_Entry is
record
Size : Unsigned_32;
Base_Address : Long_Long_Integer;
Length_In_Bytes : Long_Long_Integer;
Sort : Memory_Type;
end record;
type Memory_Map_Entry_Access is access Memory_Map_Entry;
type Memory_Map_Info is
record
Length : Unsigned_32;
Addr : Unsigned_32;
end record;
pragma Convention (C, Memory_Map_Info);
----------------------------------------------------------------------------
-- Returns null on failure or if the memory map doesn't exist.
----------------------------------------------------------------------------
function First_Memory_Map_Entry return Memory_Map_Entry_Access;
----------------------------------------------------------------------------
-- Returns null on failure or if we have seen all of the memory map.
----------------------------------------------------------------------------
function Next_Memory_Map_Entry
(Current : Memory_Map_Entry_Access) return Memory_Map_Entry_Access;
----------------------------------------------------------------------------
-- Drives information.
-- TODO: Complete
----------------------------------------------------------------------------
type Drives_Info is
record
Length : Unsigned_32;
Addr : Unsigned_32;
end record;
pragma Convention (C, Drives_Info);
----------------------------------------------------------------------------
-- APM table.
----------------------------------------------------------------------------
type APM_Table is
record
Version : Unsigned_16;
C_Seg : Unsigned_16;
Offset : Unsigned_32;
C_Seg_16 : Unsigned_16;
D_Seg : Unsigned_16;
Flags : Unsigned_16;
C_Seg_Length : Unsigned_16;
C_Seg_16_Length : Unsigned_16;
D_Seg_Length : Unsigned_16;
end record;
pragma Convention (C, APM_Table);
type APM_Table_Access is access APM_Table;
function Get_APM_Table return APM_Table_Access;
----------------------------------------------------------------------------
-- Graphics information.
----------------------------------------------------------------------------
type VBE_Info is
record
Control_Info : Unsigned_32;
Mode_Info : Unsigned_32;
Mode : Unsigned_32;
Interface_Seg : Unsigned_32;
Interface_Off : Unsigned_32;
Interface_Len : Unsigned_32;
end record;
pragma Convention (C, VBE_Info);
type MB_Info is
record
Flags : Features;
Memory : Memory_Info;
Boot_Device : Boot_Devices;
Cmd_Line : System.Address; -- NULL terminated C string.
Modules : Modules_Info;
Syms : Symbols;
Memory_Map : Memory_Map_Info;
Drives : Drives_Info;
Config_Table : System.Address; -- TODO: Points to BIOS table.
Boot_Loader_Name : System.Address; -- NULL terminated C string.
APM : System.Address;
VBE : VBE_Info;
end record;
pragma Convention (C, MB_Info);
-- We need to import the "mbd" symbol...
Info_Address : constant Unsigned_32;
pragma Import (Assembly, Info_Address, "mbd");
Info : constant MB_Info;
-- So we can use the address stored at that location.
for Info'Address use System'To_Address (Info_Address);
pragma Volatile (Info);
pragma Import (C, Info);
----------------------------------------------------------------------------
-- Magic number.
----------------------------------------------------------------------------
Magic : constant Magic_Values;
pragma Warnings (Off);
pragma Import (Assembly, Magic, "magic");
pragma Warnings (On);
end Multiboot;
|
-- -*- Mode: Ada -*-
-- Filename : multiboot.ads
-- Description : Provides access to the multiboot information from GRUB
-- Legacy and GRUB 2.
-- Author : Luke A. Guest
-- Created On : Fri Jun 15 14:43:04 2012
-- Licence : See LICENCE in the root directory.
with System;
with Interfaces; use Interfaces;
package Multiboot is
subtype Magic_Values is Unsigned_32;
Magic_Value : constant Magic_Values := 16#2BAD_B002#;
type MB_Info;
----------------------------------------------------------------------------
-- Multiboot information.
----------------------------------------------------------------------------
type Features is
record
Memory : Boolean; -- Bit 0
Boot_Device : Boolean; -- Bit 1
Command_Line : Boolean; -- Bit 2
Modules : Boolean; -- Bit 3
Symbol_Table : Boolean; -- Bit 4 - this is Aout only.
Section_Header_Table : Boolean; -- Bit 5 - this is ELF only.
BIOS_Memory_Map : Boolean; -- Bit 6
Drives : Boolean; -- Bit 7
ROM_Configuration : Boolean; -- Bit 8
Boot_Loader : Boolean; -- Bit 9
APM_Table : Boolean; -- Bit 10
Graphics_Table : Boolean; -- Bit 11
end record;
for Features use
record
Memory at 0 range 0 .. 0;
Boot_Device at 0 range 1 .. 1;
Command_Line at 0 range 2 .. 2;
Modules at 0 range 3 .. 3;
Symbol_Table at 0 range 4 .. 4;
Section_Header_Table at 0 range 5 .. 5;
BIOS_Memory_Map at 0 range 6 .. 6;
Drives at 0 range 7 .. 7;
ROM_Configuration at 1 range 0 .. 0;
Boot_Loader at 1 range 1 .. 1;
APM_Table at 1 range 2 .. 2;
Graphics_Table at 1 range 3 .. 3;
end record;
for Features'Size use 32;
----------------------------------------------------------------------------
-- Boot device information.
----------------------------------------------------------------------------
type Boot_Devices is
record
Drive : Unsigned_8;
Partition_1 : Unsigned_8;
Partition_2 : Unsigned_8;
Partition_3 : Unsigned_8;
end record;
for Boot_Devices use
record
Drive at 0 range 0 .. 7;
Partition_1 at 1 range 0 .. 7;
Partition_2 at 2 range 0 .. 7;
Partition_3 at 3 range 0 .. 7;
end record;
for Boot_Devices'Size use 32;
Invalid_Partition : constant Unsigned_8 := 16#ff#;
----------------------------------------------------------------------------
-- Memory information.
-- These values are in KB
----------------------------------------------------------------------------
type Memory_Info is
record
Upper : Unsigned_32;
Lower : Unsigned_32;
end record;
pragma Convention (C, Memory_Info);
----------------------------------------------------------------------------
-- Loadable module information.
----------------------------------------------------------------------------
type Modules is
record
First : System.Address; -- Address of module start .. end.
Last : System.Address;
Data : System.Address; -- NULL terminated C string.
Reserved : Unsigned_32; -- Should be 0.
end record;
type Modules_Array is array (Natural range <>) of Modules;
pragma Convention (C, Modules_Array);
-- type Modules_Array_Access is access Modules_Array;
-- pragma Convention (C, Modules_Array_Access);
type Modules_Info is
record
Count : Unsigned_32;
First : System.Address;
end record;
----------------------------------------------------------------------------
-- Symbols information.
----------------------------------------------------------------------------
pragma Convention (C, Modules_Info);
type Symbols_Variant is (Aout, ELF);
function Get_Symbols_Variant return Symbols_Variant;
----------------------------------------------------------------------------
-- a.out symbols or ELF sections
--
-- TODO: a.out only - This can be implemented by anyone who wants to use
-- aout.
--
-- From what I can tell from the spec, Addr points to a size followed by
-- an array of a.out nlist structures. This is then followed by a size
-- of a set of strings, then the sizeof (unsigned), then the strings
-- (NULL terminated).
--
-- Table_Size and String_Size are the same as the ones listed above.
----------------------------------------------------------------------------
type Symbols (Variant : Symbols_Variant := ELF) is
record
case Variant is
when Aout =>
Table_Size : Unsigned_32;
String_Size : Unsigned_32;
Aout_Addr : System.Address;
Reserved : Unsigned_32; -- Always 0.
when ELF =>
Number : Unsigned_32;
Size : Unsigned_32;
ELF_Addr : System.Address;
Shndx : Unsigned_32;
end case;
end record;
pragma Convention (C, Symbols);
pragma Unchecked_Union (Symbols);
----------------------------------------------------------------------------
-- Memory map information.
----------------------------------------------------------------------------
type Memory_Type is range Unsigned_32'First .. Unsigned_32'Last;
for Memory_Type'Size use 32;
Memory_Available : constant Memory_Type := 1;
Memory_Reserved : constant Memory_Type := 2;
type Memory_Map_Entry is
record
Size : Unsigned_32;
Base_Address : Long_Long_Integer;
Length_In_Bytes : Long_Long_Integer;
Sort : Memory_Type;
end record;
type Memory_Map_Entry_Access is access Memory_Map_Entry;
type Memory_Map_Info is
record
Length : Unsigned_32;
Addr : Unsigned_32;
end record;
pragma Convention (C, Memory_Map_Info);
----------------------------------------------------------------------------
-- Returns null on failure or if the memory map doesn't exist.
----------------------------------------------------------------------------
function First_Memory_Map_Entry return Memory_Map_Entry_Access;
----------------------------------------------------------------------------
-- Returns null on failure or if we have seen all of the memory map.
----------------------------------------------------------------------------
function Next_Memory_Map_Entry
(Current : Memory_Map_Entry_Access) return Memory_Map_Entry_Access;
----------------------------------------------------------------------------
-- Drives information.
-- TODO: Complete
----------------------------------------------------------------------------
type Drives_Info is
record
Length : Unsigned_32;
Addr : Unsigned_32;
end record;
pragma Convention (C, Drives_Info);
----------------------------------------------------------------------------
-- APM table.
----------------------------------------------------------------------------
type APM_Table is
record
Version : Unsigned_16;
C_Seg : Unsigned_16;
Offset : Unsigned_32;
C_Seg_16 : Unsigned_16;
D_Seg : Unsigned_16;
Flags : Unsigned_16;
C_Seg_Length : Unsigned_16;
C_Seg_16_Length : Unsigned_16;
D_Seg_Length : Unsigned_16;
end record;
pragma Convention (C, APM_Table);
type APM_Table_Access is access APM_Table;
function Get_APM_Table return APM_Table_Access;
----------------------------------------------------------------------------
-- Graphics information.
----------------------------------------------------------------------------
type VBE_Info is
record
Control_Info : Unsigned_32;
Mode_Info : Unsigned_32;
Mode : Unsigned_32;
Interface_Seg : Unsigned_32;
Interface_Off : Unsigned_32;
Interface_Len : Unsigned_32;
end record;
pragma Convention (C, VBE_Info);
type MB_Info is
record
Flags : Features;
Memory : Memory_Info;
Boot_Device : Boot_Devices;
Cmd_Line : System.Address; -- NULL terminated C string.
Modules : Modules_Info;
Syms : Symbols;
Memory_Map : Memory_Map_Info;
Drives : Drives_Info;
Config_Table : System.Address; -- TODO: Points to BIOS table.
Boot_Loader_Name : System.Address; -- NULL terminated C string.
APM : System.Address;
VBE : VBE_Info;
end record;
pragma Convention (C, MB_Info);
-- We need to import the "mbd" symbol...
Info_Address : constant Unsigned_32;
pragma Import (Assembly, Info_Address, "mbd");
Info : constant MB_Info;
-- So we can use the address stored at that location.
for Info'Address use System'To_Address (Info_Address);
pragma Volatile (Info);
pragma Import (C, Info);
----------------------------------------------------------------------------
-- Magic number.
----------------------------------------------------------------------------
Magic : constant Magic_Values;
pragma Import (Assembly, Magic, "magic");
end Multiboot;
|
Remove warning pragma, no longer required.
|
Remove warning pragma, no longer required.
|
Ada
|
cc0-1.0
|
Lucretia/bare_bones
|
1d8514b7c4dd56e6f06c170c11682ca979ae4853
|
regtests/util-files-tests.adb
|
regtests/util-files-tests.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/os-none",
Compose_Path ("src;regtests", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
end Util.Files.Tests;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File_Missing'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/os-none",
Compose_Path ("src;regtests", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
end Util.Files.Tests;
|
Fix a test case that was not executed
|
Fix a test case that was not executed
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
f5f2226dbeeb816967e15394bc51ffe83aced06a
|
regtests/util-files-tests.adb
|
regtests/util-files-tests.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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 System;
with Ada.Directories;
with Util.Systems.Constants;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File_Missing'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Delete_Tree",
Test_Delete_Tree'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/sys/processes/os-none",
Compose_Path ("src;regtests;src/sys/processes", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
function Sys_Symlink (Target : in System.Address; Link : in System.Address) return Integer
with Import => True, Convention => C,
Link_Name => Util.Systems.Constants.SYMBOL_PREFIX & "symlink";
pragma Weak_External (Sys_Symlink);
-- ------------------------------
-- Test the Delete_Tree operation.
-- ------------------------------
procedure Test_Delete_Tree (T : in out Test) is
use type System.Address;
Path : constant String := Util.Tests.Get_Test_Path ("test-delete-tree");
begin
if Ada.Directories.Exists (Path) then
Delete_Tree (Path);
end if;
-- Create a directory tree with symlink links that point to a non-existing file.
Ada.Directories.Create_Directory (Path);
for I in 1 .. 10 loop
declare
P : constant String := Compose (Path, Util.Strings.Image (I));
S : String (1 .. P'Length + 3);
R : Integer;
begin
Ada.Directories.Create_Directory (P);
S (1 .. P'Length) := P;
S (P'Length + 1) := '/';
S (P'Length + 2) := 'A';
S (S'Last) := ASCII.NUL;
for J in 1 .. 5 loop
Ada.Directories.Create_Path (Compose (P, Util.Strings.Image (J)));
end loop;
if Sys_Symlink'Address /= System.Null_Address then
R := Sys_Symlink (S'Address, S'Address);
end if;
end;
end loop;
T.Assert (Ada.Directories.Exists (Path), "Directory must exist");
-- Ada.Directories.Delete_Tree (Path) fails to delete the tree.
Delete_Tree (Path);
T.Assert (not Ada.Directories.Exists (Path), "Directory must have been deleted");
end Test_Delete_Tree;
end Util.Files.Tests;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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 System;
with Ada.Directories;
with Util.Systems.Constants;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File_Missing'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Delete_Tree",
Test_Delete_Tree'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/sys/processes/os-none",
Compose_Path ("src;regtests;src/sys/processes", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
function Sys_Symlink (Target : in System.Address; Link : in System.Address) return Integer
with Import => True, Convention => C,
Link_Name => Util.Systems.Constants.SYMBOL_PREFIX & "symlink";
pragma Weak_External (Sys_Symlink);
-- ------------------------------
-- Test the Delete_Tree operation.
-- ------------------------------
procedure Test_Delete_Tree (T : in out Test) is
use type System.Address;
Path : constant String := Util.Tests.Get_Test_Path ("test-delete-tree");
begin
if Ada.Directories.Exists (Path) then
Delete_Tree (Path);
end if;
-- Create a directory tree with symlink links that point to a non-existing file.
Ada.Directories.Create_Directory (Path);
for I in 1 .. 10 loop
declare
P : constant String := Compose (Path, Util.Strings.Image (I));
S : String (1 .. P'Length + 3);
R : Integer;
begin
Ada.Directories.Create_Directory (P);
S (1 .. P'Length) := P;
S (P'Length + 1) := '/';
S (P'Length + 2) := 'A';
S (S'Last) := ASCII.NUL;
for J in 1 .. 5 loop
Ada.Directories.Create_Path (Compose (P, Util.Strings.Image (J)));
end loop;
if Sys_Symlink'Address /= System.Null_Address then
R := Sys_Symlink (S'Address, S'Address);
Util.Tests.Assert_Equals (T, 0, R, "symlink creation failed");
end if;
end;
end loop;
T.Assert (Ada.Directories.Exists (Path), "Directory must exist");
-- Ada.Directories.Delete_Tree (Path) fails to delete the tree.
Delete_Tree (Path);
T.Assert (not Ada.Directories.Exists (Path), "Directory must have been deleted");
end Test_Delete_Tree;
end Util.Files.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f9a9a9ca7eea63a5de87153ee2ad64d24bc3d5bb
|
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 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;
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;
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;
Param_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;
|
Add Param_Char member in the Parser
|
Add Param_Char member in the Parser
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
5241e96f604f08d15b8fde19a8a7d27f20152813
|
src/orka/implementation/orka-terminals.adb
|
src/orka/implementation/orka-terminals.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.Calendar.Formatting;
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Ada.Text_IO;
package body Orka.Terminals is
Style_Codes : constant array (Style) of Natural :=
(Default => 0,
Bold => 1,
Dark => 2,
Italic => 3,
Underline => 4,
Blink => 5,
Reversed => 7,
Cross_Out => 9);
Foreground_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 30,
Red => 31,
Green => 32,
Yellow => 33,
Blue => 34,
Magenta => 35,
Cyan => 36,
White => 37);
Background_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 40,
Red => 41,
Green => 42,
Yellow => 43,
Blue => 44,
Magenta => 45,
Cyan => 46,
White => 47);
package L renames Ada.Characters.Latin_1;
package SF renames Ada.Strings.Fixed;
Reset : constant String := L.ESC & "[0m";
function Sequence (Code : Natural) return String is
Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both);
begin
return (if Code /= 0 then L.ESC & "[" & Image & "m" else "");
end Sequence;
function Colorize (Text : String; Foreground, Background : Color := Default;
Attribute : Style := Default) return String is
FG : constant String := Sequence (Foreground_Color_Codes (Foreground));
BG : constant String := Sequence (Background_Color_Codes (Background));
ST : constant String := Sequence (Style_Codes (Attribute));
begin
return Reset & FG & BG & ST & Text & Reset;
end Colorize;
-----------------------------------------------------------------------------
function Time_Image return String is
use Ada.Calendar;
use Ada.Calendar.Formatting;
Hour : Hour_Number;
Minute : Minute_Number;
Second : Second_Number;
Sub_Second : Second_Duration;
begin
Split (Seconds (Clock), Hour, Minute, Second, Sub_Second);
declare
-- Remove first character (space) from ' hhmmss' image and then pad it to six digits
Image1 : constant String := Natural'Image (Hour * 1e4 + Minute * 1e2 + Second);
Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0');
-- Insert ':' characters to get 'hh:mm:ss'
Image3 : constant String := SF.Insert (Image2, 5, ":");
Image4 : constant String := SF.Insert (Image3, 3, ":");
-- Take image without first character (space) and then pad it to six digits
Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6));
Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0');
begin
return Image4 & "." & Image6;
end;
end Time_Image;
package Duration_IO is new Ada.Text_IO.Fixed_IO (Duration);
type String_Access is not null access String;
Suffices : constant array (1 .. 3) of String_Access
:= (new String'("s"),
new String'("ms"),
new String'("us"));
Last_Suffix : constant String_Access := Suffices (Suffices'Last);
function Image (Value : Duration) return String is
Result : String := "-9999.999";
Number : Duration := Value;
Suffix : String_Access := Suffices (Suffices'First);
begin
for S of Suffices loop
Suffix := S;
exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix;
Number := Number * 1e3;
end loop;
begin
Duration_IO.Put (Result, Item => Number, Aft => 3);
exception
when others =>
return Number'Image & " " & Suffix.all;
end;
return Result & " " & Suffix.all;
end Image;
function Trim (Value : String) return String is (SF.Trim (Value, Ada.Strings.Both));
function Strip_Line_Term (Value : String) return String is
Last_Index : Natural := Value'Last;
begin
for Index in reverse Value'Range loop
exit when Value (Index) not in L.LF | L.CR;
Last_Index := Last_Index - 1;
end loop;
return Value (Value'First .. Last_Index);
end Strip_Line_Term;
end Orka.Terminals;
|
-- 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.Calendar.Formatting;
with Ada.Characters.Latin_1;
with Ada.Real_Time;
with Ada.Strings.Fixed;
with Ada.Text_IO;
package body Orka.Terminals is
Style_Codes : constant array (Style) of Natural :=
(Default => 0,
Bold => 1,
Dark => 2,
Italic => 3,
Underline => 4,
Blink => 5,
Reversed => 7,
Cross_Out => 9);
Foreground_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 30,
Red => 31,
Green => 32,
Yellow => 33,
Blue => 34,
Magenta => 35,
Cyan => 36,
White => 37);
Background_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 40,
Red => 41,
Green => 42,
Yellow => 43,
Blue => 44,
Magenta => 45,
Cyan => 46,
White => 47);
package L renames Ada.Characters.Latin_1;
package SF renames Ada.Strings.Fixed;
Reset : constant String := L.ESC & "[0m";
function Sequence (Code : Natural) return String is
Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both);
begin
return (if Code /= 0 then L.ESC & "[" & Image & "m" else "");
end Sequence;
function Colorize (Text : String; Foreground, Background : Color := Default;
Attribute : Style := Default) return String is
FG : constant String := Sequence (Foreground_Color_Codes (Foreground));
BG : constant String := Sequence (Background_Color_Codes (Background));
ST : constant String := Sequence (Style_Codes (Attribute));
begin
return Reset & FG & BG & ST & Text & Reset;
end Colorize;
-----------------------------------------------------------------------------
Time_Zero : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Days_Since_Zero : Natural := 0;
function Time_Image return String is
use Ada.Real_Time;
use Ada.Calendar.Formatting;
Hour : Hour_Number;
Minute : Minute_Number;
Second : Second_Number;
Sub_Second : Second_Duration;
Seconds_Since_Zero : Duration := To_Duration (Clock - Time_Zero);
begin
if Seconds_Since_Zero > Ada.Calendar.Day_Duration'Last then
Seconds_Since_Zero := Seconds_Since_Zero - Ada.Calendar.Day_Duration'Last;
Days_Since_Zero := Days_Since_Zero + 1;
end if;
Split (Seconds_Since_Zero, Hour, Minute, Second, Sub_Second);
declare
-- Remove first character (space) from ' hhmmss' image and then pad it to six digits
Image1 : constant String := Natural'Image
((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second);
Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0');
-- Insert ':' characters to get 'hh:mm:ss'
Image3 : constant String := SF.Insert (Image2, 5, ":");
Image4 : constant String := SF.Insert (Image3, 3, ":");
-- Take image without first character (space) and then pad it to six digits
Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6));
Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0');
begin
return Image4 & "." & Image6;
end;
end Time_Image;
package Duration_IO is new Ada.Text_IO.Fixed_IO (Duration);
type String_Access is not null access String;
Suffices : constant array (1 .. 3) of String_Access
:= (new String'("s"),
new String'("ms"),
new String'("us"));
Last_Suffix : constant String_Access := Suffices (Suffices'Last);
function Image (Value : Duration) return String is
Result : String := "-9999.999";
Number : Duration := Value;
Suffix : String_Access := Suffices (Suffices'First);
begin
for S of Suffices loop
Suffix := S;
exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix;
Number := Number * 1e3;
end loop;
begin
Duration_IO.Put (Result, Item => Number, Aft => 3);
exception
when others =>
return Number'Image & " " & Suffix.all;
end;
return Result & " " & Suffix.all;
end Image;
function Trim (Value : String) return String is (SF.Trim (Value, Ada.Strings.Both));
function Strip_Line_Term (Value : String) return String is
Last_Index : Natural := Value'Last;
begin
for Index in reverse Value'Range loop
exit when Value (Index) not in L.LF | L.CR;
Last_Index := Last_Index - 1;
end loop;
return Value (Value'First .. Last_Index);
end Strip_Line_Term;
end Orka.Terminals;
|
Use monotonic time instead of wallclock time in logs
|
orka: Use monotonic time instead of wallclock time in logs
Valid range is [0, 4 days + 4 hours). If time since program start-up is
at least 100 hours, then only the last 2 digits of the hours will be
displayed.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
59db15408ada6c6e1a543b1cf9b70de26a20c4ea
|
src/sys/http/util-http-clients-mockups.adb
|
src/sys/http/util-http-clients-mockups.adb
|
-----------------------------------------------------------------------
-- util-http-clients-mockups -- HTTP Clients
-- Copyright (C) 2011, 2012, 2017, 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.Files;
with Util.Http.Mockups;
package body Util.Http.Clients.Mockups is
use Ada.Strings.Unbounded;
Manager : aliased File_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
-- ------------------------------
-- Set the path of the file that contains the response for the next
-- <b>Do_Get</b> and <b>Do_Post</b> calls.
-- ------------------------------
procedure Set_File (Path : in String) is
begin
Manager.File := To_Unbounded_String (Path);
end Set_File;
procedure Create (Manager : in File_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new Util.Http.Mockups.Mockup_Request;
end Create;
overriding
procedure Do_Get (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Http, URI);
Rep : constant Util.Http.Mockups.Mockup_Response_Access
:= new Util.Http.Mockups.Mockup_Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Delegate := Rep.all'Access;
Util.Files.Read_File (Path => To_String (Manager.File),
Into => Content,
Max_Size => 100000);
Rep.Set_Body (To_String (Content));
Rep.Set_Status (SC_OK);
end Do_Get;
overriding
procedure Do_Head (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Http, URI);
Rep : constant Util.Http.Mockups.Mockup_Response_Access
:= new Util.Http.Mockups.Mockup_Response;
begin
Reply.Delegate := Rep.all'Access;
Rep.Set_Body ("");
Rep.Set_Status (SC_OK);
end Do_Head;
overriding
procedure Do_Post (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Post;
overriding
procedure Do_Put (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Put;
overriding
procedure Do_Patch (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Patch;
overriding
procedure Do_Delete (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Delete;
overriding
procedure Do_Options (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Options;
-- ------------------------------
-- Set the timeout for the connection.
-- ------------------------------
overriding
procedure Set_Timeout (Manager : in File_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
pragma Unreferenced (Manager, Http, Timeout);
begin
null;
end Set_Timeout;
end Util.Http.Clients.Mockups;
|
-----------------------------------------------------------------------
-- util-http-clients-mockups -- HTTP Clients
-- Copyright (C) 2011, 2012, 2017, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Files;
with Util.Http.Mockups;
package body Util.Http.Clients.Mockups is
use Ada.Strings.Unbounded;
Manager : aliased File_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
-- ------------------------------
-- Set the path of the file that contains the response for the next
-- <b>Do_Get</b> and <b>Do_Post</b> calls.
-- ------------------------------
procedure Set_File (Path : in String) is
begin
Manager.File := To_Unbounded_String (Path);
end Set_File;
procedure Create (Manager : in File_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new Util.Http.Mockups.Mockup_Request;
end Create;
overriding
procedure Do_Get (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Http, URI);
Rep : constant Util.Http.Mockups.Mockup_Response_Access
:= new Util.Http.Mockups.Mockup_Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Delegate := Rep.all'Access;
Util.Files.Read_File (Path => To_String (Manager.File),
Into => Content,
Max_Size => 100000);
Rep.Set_Body (To_String (Content));
Rep.Set_Status (SC_OK);
end Do_Get;
overriding
procedure Do_Head (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager, Http, URI);
Rep : constant Util.Http.Mockups.Mockup_Response_Access
:= new Util.Http.Mockups.Mockup_Response;
begin
Reply.Delegate := Rep.all'Access;
Rep.Set_Body ("");
Rep.Set_Status (SC_OK);
end Do_Head;
overriding
procedure Do_Post (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Post;
overriding
procedure Do_Put (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Put;
overriding
procedure Do_Patch (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Data);
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Patch;
overriding
procedure Do_Delete (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Delete;
overriding
procedure Do_Options (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
begin
Manager.Do_Get (Http, URI, Reply);
end Do_Options;
-- ------------------------------
-- Set the timeout for the connection.
-- ------------------------------
overriding
procedure Set_Timeout (Manager : in File_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
pragma Unreferenced (Manager, Http, Timeout);
begin
null;
end Set_Timeout;
end Util.Http.Clients.Mockups;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
4512fa9f6e62988414d4fc8436b2a3164658e750
|
awa/src/awa-blogs-beans.adb
|
awa/src/awa-blogs-beans.adb
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Blogs.Services;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ASF.Events.Faces.Actions;
package body AWA.Blogs.Beans is
use Ada.Strings.Unbounded;
BLOG_ID_PARAMETER : constant String := "blog_id";
POST_ID_PARAMETER : constant String := "post_id";
function Get_Parameter (Name : in String) return ADO.Identifier;
-- ------------------------------
-- Get the parameter identified by the given name and return it as an identifier.
-- Returns NO_IDENTIFIER if the parameter does not exist or is not valid.
-- ------------------------------
function Get_Parameter (Name : in String) return ADO.Identifier is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return ADO.NO_IDENTIFIER;
else
return ADO.Identifier'Value (P);
end if;
exception
when others =>
return ADO.NO_IDENTIFIER;
end Get_Parameter;
-- ------------------------------
-- 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
return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name);
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;
package Create_Blog_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean,
Method => Create_Blog,
Name => "create");
Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Create_Blog_Binding.Proxy'Access);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Blog_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Blog_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create a new blog.
-- ------------------------------
procedure Create_Blog (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager;
Result : ADO.Identifier;
begin
Manager.Create_Blog (Workspace_Id => 0,
Title => Bean.Get_Name,
Result => Result);
Outcome := To_Unbounded_String ("success");
exception
when Services.Not_Found =>
Outcome := To_Unbounded_String ("failure");
ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message");
end Create_Blog;
-- ------------------------------
-- Create the Blog_Bean bean instance.
-- ------------------------------
function Create_Blog_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use type ADO.Identifier;
Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER);
Object : constant Blog_Bean_Access := new Blog_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
begin
if Blog_Id > 0 then
Object.Load (Session, Blog_Id);
end if;
Object.Module := Module;
return Object.all'Access;
end Create_Blog_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Create_Post (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
use type ADO.Identifier;
Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager;
Result : ADO.Identifier;
Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER);
Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER);
begin
if Post_Id < 0 then
Manager.Create_Post (Blog_Id => Blog_Id,
Title => Bean.Post.Get_Title,
URI => Bean.Post.Get_Uri,
Text => Bean.Post.Get_Text,
Result => Result);
else
Manager.Update_Post (Post_Id => Post_Id,
Title => Bean.Post.Get_Title,
Text => Bean.Post.Get_Text);
end if;
Outcome := To_Unbounded_String ("success");
exception
when Services.Not_Found =>
Outcome := To_Unbounded_String ("failure");
ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message");
end Create_Post;
package Create_Post_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean,
Method => Create_Post,
Name => "create");
package Save_Post_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean,
Method => Create_Post,
Name => "save");
Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Create_Post_Binding.Proxy'Access,
2 => Save_Post_Binding.Proxy'Access);
-- ------------------------------
-- 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 Name = POST_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id));
else
return From.Post.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.Identifier (Util.Beans.Objects.To_Integer (Value));
elsif Name = POST_ID_ATTR then
From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value));
elsif Name = POST_TEXT_ATTR then
From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_TITLE_ATTR then
From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_URI_ATTR then
From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Post_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Post_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Post_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use type ADO.Identifier;
Object : constant Post_Bean_Access := new Post_Bean;
Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER);
begin
if Post_Id > 0 then
declare
Session : ADO.Sessions.Session := Module.Get_Session;
begin
Object.Post.Load (Session, Post_Id);
Object.Title := Object.Post.Get_Title;
Object.Text := Object.Post.Get_Text;
Object.URI := Object.Post.Get_Uri;
end;
end if;
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.Module.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 Admin_Post_List_Bean bean instance.
-- ------------------------------
function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Blogs.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER);
begin
if Blog_Id > 0 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'Access, Session);
AWA.Blogs.Models.List (Object.all, Session, Query);
end if;
return Object.all'Access;
end Create_Admin_Post_List_Bean;
-- ------------------------------
-- Create the Blog_List_Bean bean instance.
-- ------------------------------
function Create_Blog_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Blogs.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean;
Session : ADO.Sessions.Session := 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'Access, Session);
AWA.Blogs.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Blog_List_Bean;
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Blogs.Services;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ASF.Events.Faces.Actions;
package body AWA.Blogs.Beans is
use Ada.Strings.Unbounded;
BLOG_ID_PARAMETER : constant String := "blog_id";
POST_ID_PARAMETER : constant String := "post_id";
function Get_Parameter (Name : in String) return ADO.Identifier;
-- ------------------------------
-- Get the parameter identified by the given name and return it as an identifier.
-- Returns NO_IDENTIFIER if the parameter does not exist or is not valid.
-- ------------------------------
function Get_Parameter (Name : in String) return ADO.Identifier is
use type ASF.Contexts.Faces.Faces_Context_Access;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Ctx = null then
return ADO.NO_IDENTIFIER;
else
declare
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return ADO.NO_IDENTIFIER;
else
return ADO.Identifier'Value (P);
end if;
end;
end if;
exception
when others =>
return ADO.NO_IDENTIFIER;
end Get_Parameter;
-- ------------------------------
-- 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
return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name);
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;
package Create_Blog_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean,
Method => Create_Blog,
Name => "create");
Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Create_Blog_Binding.Proxy'Access);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Blog_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Blog_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create a new blog.
-- ------------------------------
procedure Create_Blog (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager;
Result : ADO.Identifier;
begin
Manager.Create_Blog (Workspace_Id => 0,
Title => Bean.Get_Name,
Result => Result);
Outcome := To_Unbounded_String ("success");
exception
when Services.Not_Found =>
Outcome := To_Unbounded_String ("failure");
ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message");
end Create_Blog;
-- ------------------------------
-- Create the Blog_Bean bean instance.
-- ------------------------------
function Create_Blog_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use type ADO.Identifier;
Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER);
Object : constant Blog_Bean_Access := new Blog_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
begin
if Blog_Id > 0 then
Object.Load (Session, Blog_Id);
end if;
Object.Module := Module;
return Object.all'Access;
end Create_Blog_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Create_Post (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
use type ADO.Identifier;
Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager;
Result : ADO.Identifier;
Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER);
Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER);
begin
if Post_Id < 0 then
Manager.Create_Post (Blog_Id => Blog_Id,
Title => Bean.Post.Get_Title,
URI => Bean.Post.Get_Uri,
Text => Bean.Post.Get_Text,
Result => Result);
else
Manager.Update_Post (Post_Id => Post_Id,
Title => Bean.Post.Get_Title,
Text => Bean.Post.Get_Text);
end if;
Outcome := To_Unbounded_String ("success");
exception
when Services.Not_Found =>
Outcome := To_Unbounded_String ("failure");
ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message");
end Create_Post;
package Create_Post_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean,
Method => Create_Post,
Name => "create");
package Save_Post_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean,
Method => Create_Post,
Name => "save");
Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Create_Post_Binding.Proxy'Access,
2 => Save_Post_Binding.Proxy'Access);
-- ------------------------------
-- 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 Name = POST_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id));
else
return From.Post.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.Identifier (Util.Beans.Objects.To_Integer (Value));
elsif Name = POST_ID_ATTR then
From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value));
elsif Name = POST_TEXT_ATTR then
From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_TITLE_ATTR then
From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_URI_ATTR then
From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Post_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Post_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Post_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use type ADO.Identifier;
Object : constant Post_Bean_Access := new Post_Bean;
Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER);
begin
if Post_Id > 0 then
declare
Session : ADO.Sessions.Session := Module.Get_Session;
begin
Object.Post.Load (Session, Post_Id);
Object.Title := Object.Post.Get_Title;
Object.Text := Object.Post.Get_Text;
Object.URI := Object.Post.Get_Uri;
end;
end if;
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.Module.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 Admin_Post_List_Bean bean instance.
-- ------------------------------
function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Blogs.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER);
begin
if Blog_Id > 0 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'Access, Session);
AWA.Blogs.Models.List (Object.all, Session, Query);
end if;
return Object.all'Access;
end Create_Admin_Post_List_Bean;
-- ------------------------------
-- Create the Blog_List_Bean bean instance.
-- ------------------------------
function Create_Blog_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Blogs.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean;
Session : ADO.Sessions.Session := 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'Access, Session);
AWA.Blogs.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Blog_List_Bean;
end AWA.Blogs.Beans;
|
Check that the faces context is defined before getting parameters
|
Check that the faces context is defined before getting parameters
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
766c1ee5785e6f3b4762ce8e912c17c0033d0599
|
src/util-serialize-io-csv.ads
|
src/util-serialize-io-csv.ads
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Vectors;
with Util.Streams.Texts;
-- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files.
--
-- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files
package Util.Serialize.IO.CSV is
type Row_Type is new Natural;
type Column_Type is new Positive;
-- ------------------------------
-- CSV Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a CSV output stream.
-- The stream object takes care of the CSV escape rules.
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private;
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character);
-- Enable or disable the double quotes by default for strings.
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean);
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new row.
procedure New_Row (Stream : in out Output_Stream);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_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);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the attribute with a null value.
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String);
-- Write the entity value.
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);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write an entity with a null value.
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String);
-- ------------------------------
-- CSV Parser
-- ------------------------------
-- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly
-- in Ada records.
type Parser is new Serialize.IO.Parser with private;
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String;
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type);
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the field separator.
function Get_Field_Separator (Handler : in Parser) return Character;
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
function Get_Comment_Separator (Handler : in Parser) return Character;
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True);
-- Parse the stream using the CSV parser.
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class);
-- Get the current location (file and line) to report an error message.
overriding
function Get_Location (Handler : in Parser) return String;
private
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record
Max_Columns : Column_Type := 1;
Column : Column_Type := 1;
Row : Row_Type := 0;
Separator : Character := ',';
Quote : Boolean := True;
end record;
type Parser is new Util.Serialize.IO.Parser with record
Has_Header : Boolean := True;
Line_Number : Natural := 1;
Row : Row_Type := 0;
Headers : Util.Strings.Vectors.Vector;
Separator : Character := ',';
Comment : Character := ASCII.NUL;
Use_Default_Headers : Boolean := False;
Sink : access Reader'Class;
end record;
end Util.Serialize.IO.CSV;
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Vectors;
with Util.Streams.Texts;
-- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files.
--
-- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files
package Util.Serialize.IO.CSV is
type Row_Type is new Natural;
type Column_Type is new Positive;
-- ------------------------------
-- CSV Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a CSV output stream.
-- The stream object takes care of the CSV escape rules.
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private;
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character);
-- Enable or disable the double quotes by default for strings.
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean);
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new row.
procedure New_Row (Stream : in out Output_Stream);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the attribute with a null value.
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String);
-- Write the entity value.
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write an entity with a null value.
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String);
-- ------------------------------
-- CSV Parser
-- ------------------------------
-- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly
-- in Ada records.
type Parser is new Serialize.IO.Parser with private;
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String;
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type);
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the field separator.
function Get_Field_Separator (Handler : in Parser) return Character;
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
function Get_Comment_Separator (Handler : in Parser) return Character;
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True);
-- Parse the stream using the CSV parser.
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class);
-- Get the current location (file and line) to report an error message.
overriding
function Get_Location (Handler : in Parser) return String;
private
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record
Max_Columns : Column_Type := 1;
Column : Column_Type := 1;
Row : Row_Type := 0;
Separator : Character := ',';
Quote : Boolean := True;
end record;
type Parser is new Util.Serialize.IO.Parser with record
Has_Header : Boolean := True;
Line_Number : Natural := 1;
Row : Row_Type := 0;
Headers : Util.Strings.Vectors.Vector;
Separator : Character := ',';
Comment : Character := ASCII.NUL;
Use_Default_Headers : Boolean := False;
Sink : access Reader'Class;
end record;
end Util.Serialize.IO.CSV;
|
Remove Write_Entity and Write_Attribute on Nullable_String
|
Remove Write_Entity and Write_Attribute on Nullable_String
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
64f09ad6f2bc3ff8416d0c951ab981725408bc0d
|
tools/druss-commands-ping.adb
|
tools/druss-commands-ping.adb
|
-----------------------------------------------------------------------
-- druss-commands-devices -- Print information about the devices
-- 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;
with Bbox.API;
with Druss.Gateways;
with Ada.Strings.Unbounded;
package body Druss.Commands.Ping is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Execute the wifi 'status' command to print the Wifi current status.
-- ------------------------------
procedure Do_Ping (Command : in Command_Type;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type) is
Box : Bbox.API.Client_Type;
procedure Ping_Device (Manager : in Util.Properties.Manager;
Name : in String) is
Link : constant String := Manager.Get (Name & ".link", "");
Id : constant String := Manager.Get (Name & ".id", "");
begin
if Manager.Get (Name & ".active", "") = "0" then
return;
end if;
Box.Post ("hosts/" & Id, "action=ping");
end Ping_Device;
begin
if Ada.Strings.Unbounded.Length (Gateway.Passwd) = 0 then
return;
end if;
Gateway.Refresh;
Box.Set_Server (To_String (Gateway.IP));
Box.Login (To_String (Gateway.Passwd));
Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Ping_Device'Access);
end Do_Ping;
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String);
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String) is
Link : constant String := Manager.Get (Name & ".link", "");
Kind : constant String := Manager.Get (Name & ".devicetype", "");
begin
if Manager.Get (Name & ".active", "") = "0" then
return;
end if;
Console.Start_Row;
Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip);
Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", ""));
Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", ""));
Print_Perf (Console, F_ACTIVE, Manager.Get (Name & ".ping.average", ""));
if Link = "Ethernet" then
Console.Print_Field (F_LINK, Link & " port "
& Manager.Get (Name & ".ethernet.logicalport", ""));
else
Console.Print_Field (F_LINK, Link & " RSSI "
& Manager.Get (Name & ".wireless.rssi0", ""));
end if;
Console.End_Row;
end Print_Device;
begin
Gateway.Refresh;
Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access);
end Box_Status;
begin
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Do_Ping'Access);
delay 5.0;
Console.Start_Title;
Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16);
Console.Print_Title (F_IP_ADDR, "Device IP", 16);
Console.Print_Title (F_HOSTNAME, "Hostname", 28);
Console.Print_Title (F_ACTIVE, "Ping", 15);
Console.Print_Title (F_LINK, "Link", 18);
Console.End_Title;
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access);
end Do_Ping;
-- ------------------------------
-- Execute a ping from the gateway to each device.
-- ------------------------------
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
Command.Do_Ping (Args, Context);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP, "ping: Ask the Bbox to ping the devices");
Console.Notice (N_HELP, "Usage: ping {active | inactive}");
Console.Notice (N_HELP, "");
Console.Notice (N_HELP, " active Ping the active devices only");
Console.Notice (N_HELP, " inative Ping the inactive devices only");
end Help;
end Druss.Commands.Ping;
|
-----------------------------------------------------------------------
-- druss-commands-devices -- Print information about the devices
-- 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;
with Util.Log.Loggers;
with Bbox.API;
with Druss.Gateways;
with Ada.Strings.Unbounded;
package body Druss.Commands.Ping is
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Ping");
-- ------------------------------
-- Execute the wifi 'status' command to print the Wifi current status.
-- ------------------------------
procedure Do_Ping (Command : in Command_Type;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type) is
Box : Bbox.API.Client_Type;
procedure Ping_Device (Manager : in Util.Properties.Manager;
Name : in String) is
Link : constant String := Manager.Get (Name & ".link", "");
Id : constant String := Manager.Get (Name & ".id", "");
begin
-- if Manager.Get (Name & ".active", "") = "0" then
-- return;
-- end if;
Log.Info ("Ping command on {0}", Manager.Get (Name & ".ipaddress", ""));
Box.Post ("hosts/" & Id, "action=ping");
end Ping_Device;
begin
if Ada.Strings.Unbounded.Length (Gateway.Passwd) = 0 then
return;
end if;
Gateway.Refresh;
Box.Set_Server (To_String (Gateway.IP));
Box.Login (To_String (Gateway.Passwd));
Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Ping_Device'Access);
end Do_Ping;
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String);
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String) is
Link : constant String := Manager.Get (Name & ".link", "");
Kind : constant String := Manager.Get (Name & ".devicetype", "");
begin
if Manager.Get (Name & ".active", "") = "0" then
return;
end if;
Console.Start_Row;
Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip);
Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", ""));
Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", ""));
Print_Perf (Console, F_ACTIVE, Manager.Get (Name & ".ping.average", ""));
if Link = "Ethernet" then
Console.Print_Field (F_LINK, Link & " port "
& Manager.Get (Name & ".ethernet.logicalport", ""));
else
Console.Print_Field (F_LINK, Link & " RSSI "
& Manager.Get (Name & ".wireless.rssi0", ""));
end if;
Console.End_Row;
end Print_Device;
begin
Gateway.Refresh;
Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access);
end Box_Status;
begin
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Do_Ping'Access);
delay 5.0;
Console.Start_Title;
Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16);
Console.Print_Title (F_IP_ADDR, "Device IP", 16);
Console.Print_Title (F_HOSTNAME, "Hostname", 28);
Console.Print_Title (F_ACTIVE, "Ping", 15);
Console.Print_Title (F_LINK, "Link", 18);
Console.End_Title;
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access);
end Do_Ping;
-- ------------------------------
-- Execute a ping from the gateway to each device.
-- ------------------------------
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
Command.Do_Ping (Args, Context);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP, "ping: Ask the Bbox to ping the devices");
Console.Notice (N_HELP, "Usage: ping {active | inactive}");
Console.Notice (N_HELP, "");
Console.Notice (N_HELP, " active Ping the active devices only");
Console.Notice (N_HELP, " inative Ping the inactive devices only");
end Help;
end Druss.Commands.Ping;
|
Add some log for the -v option
|
Add some log for the -v option
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
ddfd5fed56f3204e5dc5c1b6749a7da1b1c36436
|
ARM/STM32/drivers/uart_stm32f4/stm32-usarts.ads
|
ARM/STM32/drivers/uart_stm32f4/stm32-usarts.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_usart.h --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief Header file of USARTS HAL module. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides register definitions for the STM32F4 (ARM Cortex M4F)
-- USART from ST Microelectronics.
-- Note that there are board implementation assumptions represented by the
-- private function APB_Clock.
with System;
with HAL.UART; use HAL.UART;
private with STM32_SVD.USART;
package STM32.USARTs is
type Internal_USART is limited private;
type USART (Periph : not null access Internal_USART) is
limited new HAL.UART.UART_Port with private;
procedure Enable (This : in out USART) with
Post => Enabled (This),
Inline;
procedure Disable (This : in out USART) with
Post => not Enabled (This),
Inline;
function Enabled (This : USART) return Boolean with Inline;
procedure Receive (This : USART; Data : out UInt9) with Inline;
-- reads Device.DR into Data
function Current_Input (This : USART) return UInt9 with Inline;
-- returns Device.DR
procedure Transmit (This : in out USART; Data : UInt9) with Inline;
function Tx_Ready (This : USART) return Boolean with Inline;
function Rx_Ready (This : USART) return Boolean with Inline;
type Stop_Bits is (Stopbits_1, Stopbits_2) with Size => 2;
for Stop_Bits use (Stopbits_1 => 0, Stopbits_2 => 2#10#);
procedure Set_Stop_Bits (This : in out USART; To : Stop_Bits);
type Word_Lengths is (Word_Length_8, Word_Length_9);
procedure Set_Word_Length (This : in out USART; To : Word_Lengths);
type Parities is (No_Parity, Even_Parity, Odd_Parity);
procedure Set_Parity (This : in out USART; To : Parities);
subtype Baud_Rates is Word;
procedure Set_Baud_Rate (This : in out USART; To : Baud_Rates);
type Oversampling_Modes is (Oversampling_By_8, Oversampling_By_16);
-- oversampling by 16 is the default
procedure Set_Oversampling_Mode
(This : in out USART;
To : Oversampling_Modes);
type UART_Modes is (Rx_Mode, Tx_Mode, Tx_Rx_Mode);
procedure Set_Mode (This : in out USART; To : UART_Modes);
type Flow_Control is
(No_Flow_Control,
RTS_Flow_Control,
CTS_Flow_Control,
RTS_CTS_Flow_Control);
procedure Set_Flow_Control (This : in out USART; To : Flow_Control);
type USART_Interrupt is
(Parity_Error,
Transmit_Data_Register_Empty,
Transmission_Complete,
Received_Data_Not_Empty,
Idle_Line_Detection,
Line_Break_Detection,
Clear_To_Send,
Error);
procedure Enable_Interrupts
(This : in out USART;
Source : USART_Interrupt)
with
Post => Interrupt_Enabled (This, Source),
Inline;
procedure Disable_Interrupts
(This : in out USART;
Source : USART_Interrupt)
with
Post => not Interrupt_Enabled (This, Source),
Inline;
function Interrupt_Enabled
(This : USART;
Source : USART_Interrupt)
return Boolean
with Inline;
type USART_Status_Flag is
(Parity_Error_Indicated,
Framing_Error_Indicated,
USART_Noise_Error_Indicated,
Overrun_Error_Indicated,
Idle_Line_Detection_Indicated,
Read_Data_Register_Not_Empty,
Transmission_Complete_Indicated,
Transmit_Data_Register_Empty,
Line_Break_Detection_Indicated,
Clear_To_Send_Indicated);
function Status (This : USART; Flag : USART_Status_Flag) return Boolean
with Inline;
procedure Clear_Status (This : in out USART; Flag : USART_Status_Flag)
with Inline;
procedure Enable_DMA_Transmit_Requests (This : in out USART) with
Inline,
Post => DMA_Transmit_Requests_Enabled (This);
procedure Disable_DMA_Transmit_Requests (This : in out USART) with
Inline,
Post => not DMA_Transmit_Requests_Enabled (This);
function DMA_Transmit_Requests_Enabled (This : USART) return Boolean with
Inline;
procedure Enable_DMA_Receive_Requests (This : in out USART) with
Inline,
Post => DMA_Receive_Requests_Enabled (This);
procedure Disable_DMA_Receive_Requests (This : in out USART) with
Inline,
Post => not DMA_Receive_Requests_Enabled (This);
function DMA_Receive_Requests_Enabled (This : USART) return Boolean with
Inline;
procedure Pause_DMA_Transmission (This : in out USART)
renames Disable_DMA_Transmit_Requests;
procedure Resume_DMA_Transmission (This : in out USART) with
Inline,
Post => DMA_Transmit_Requests_Enabled (This) and
Enabled (This);
procedure Pause_DMA_Reception (This : in out USART)
renames Disable_DMA_Receive_Requests;
procedure Resume_DMA_Reception (This : in out USART) with
Inline,
Post => DMA_Receive_Requests_Enabled (This) and
Enabled (This);
function Data_Register_Address (This : USART) return System.Address with
Inline;
-- Returns the address of the USART Data Register. This is exported
-- STRICTLY for the sake of clients driving a USART via DMA. All other
-- clients of this package should use the procedural interfaces Transmit
-- and Receive instead of directly accessing the Data Register!
-- Seriously, don't use this function otherwise.
-----------------------------
-- HAL.UART implementation --
-----------------------------
overriding
function Data_Size (This : USART) return HAL.UART.UART_Data_Size;
overriding
procedure Transmit
(Port : in out USART;
Data : UART_Data_8b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_8b;
overriding
procedure Transmit
(Port : in out USART;
Data : UART_Data_9b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_9b;
overriding
procedure Receive
(Port : in out USART;
Data : out UART_Data_8b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_8b;
overriding
procedure Receive
(Port : in out USART;
Data : out UART_Data_9b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_9b;
private
function APB_Clock (This : USART) return Word with Inline;
-- Returns either APB1 or APB2 clock rate, in Hertz, depending on the
-- USART. For the sake of not making this package board-specific, we assume
-- that we are given a valid USART object at a valid address, AND that the
-- USART devices really are configured such that only 1 and 6 are on APB2.
-- Therefore, if a board has additional USARTs beyond USART6, eg USART8 on
-- the F429I Discovery board, they better conform to that assumption.
-- See Note # 2 in each of Tables 139-141 of the RM on pages 970 - 972.
type Internal_USART is new STM32_SVD.USART.USART2_Peripheral;
type USART (Periph : not null access Internal_USART) is
limited new HAL.UART.UART_Port with null record;
end STM32.USARTs;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_usart.h --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief Header file of USARTS HAL module. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides register definitions for the STM32F4 (ARM Cortex M4F)
-- USART from ST Microelectronics.
-- Note that there are board implementation assumptions represented by the
-- private function APB_Clock.
with System;
with HAL.UART; use HAL.UART;
private with STM32_SVD.USART;
package STM32.USARTs is
type Internal_USART is limited private;
type USART (Periph : not null access Internal_USART) is
limited new HAL.UART.UART_Port with private;
procedure Enable (This : in out USART) with
Post => Enabled (This),
Inline;
procedure Disable (This : in out USART) with
Post => not Enabled (This),
Inline;
function Enabled (This : USART) return Boolean with Inline;
procedure Receive (This : USART; Data : out UInt9) with Inline;
-- reads Device.DR into Data
function Current_Input (This : USART) return UInt9 with Inline;
-- returns Device.DR
procedure Transmit (This : in out USART; Data : UInt9) with Inline;
function Tx_Ready (This : USART) return Boolean with Inline;
function Rx_Ready (This : USART) return Boolean with Inline;
type Stop_Bits is (Stopbits_1, Stopbits_2) with Size => 2;
for Stop_Bits use (Stopbits_1 => 0, Stopbits_2 => 2#10#);
procedure Set_Stop_Bits (This : in out USART; To : Stop_Bits);
type Word_Lengths is (Word_Length_8, Word_Length_9);
procedure Set_Word_Length (This : in out USART; To : Word_Lengths);
type Parities is (No_Parity, Even_Parity, Odd_Parity);
procedure Set_Parity (This : in out USART; To : Parities);
subtype Baud_Rates is Word;
procedure Set_Baud_Rate (This : in out USART; To : Baud_Rates);
type Oversampling_Modes is (Oversampling_By_8, Oversampling_By_16);
-- oversampling by 16 is the default
procedure Set_Oversampling_Mode
(This : in out USART;
To : Oversampling_Modes);
type UART_Modes is (Rx_Mode, Tx_Mode, Tx_Rx_Mode);
procedure Set_Mode (This : in out USART; To : UART_Modes);
type Flow_Control is
(No_Flow_Control,
RTS_Flow_Control,
CTS_Flow_Control,
RTS_CTS_Flow_Control);
procedure Set_Flow_Control (This : in out USART; To : Flow_Control);
type USART_Interrupt is
(Parity_Error,
Transmit_Data_Register_Empty,
Transmission_Complete,
Received_Data_Not_Empty,
Idle_Line_Detection,
Line_Break_Detection,
Clear_To_Send,
Error);
procedure Enable_Interrupts
(This : in out USART;
Source : USART_Interrupt)
with
Post => Interrupt_Enabled (This, Source),
Inline;
procedure Disable_Interrupts
(This : in out USART;
Source : USART_Interrupt)
with
Post => not Interrupt_Enabled (This, Source),
Inline;
function Interrupt_Enabled
(This : USART;
Source : USART_Interrupt)
return Boolean
with Inline;
type USART_Status_Flag is
(Parity_Error_Indicated,
Framing_Error_Indicated,
USART_Noise_Error_Indicated,
Overrun_Error_Indicated,
Idle_Line_Detection_Indicated,
Read_Data_Register_Not_Empty,
Transmission_Complete_Indicated,
Transmit_Data_Register_Empty,
Line_Break_Detection_Indicated,
Clear_To_Send_Indicated);
function Status (This : USART; Flag : USART_Status_Flag) return Boolean
with Inline;
procedure Clear_Status (This : in out USART; Flag : USART_Status_Flag)
with Inline;
procedure Enable_DMA_Transmit_Requests (This : in out USART) with
Inline,
Post => DMA_Transmit_Requests_Enabled (This);
procedure Disable_DMA_Transmit_Requests (This : in out USART) with
Inline,
Post => not DMA_Transmit_Requests_Enabled (This);
function DMA_Transmit_Requests_Enabled (This : USART) return Boolean with
Inline;
procedure Enable_DMA_Receive_Requests (This : in out USART) with
Inline,
Post => DMA_Receive_Requests_Enabled (This);
procedure Disable_DMA_Receive_Requests (This : in out USART) with
Inline,
Post => not DMA_Receive_Requests_Enabled (This);
function DMA_Receive_Requests_Enabled (This : USART) return Boolean with
Inline;
procedure Pause_DMA_Transmission (This : in out USART)
renames Disable_DMA_Transmit_Requests;
procedure Resume_DMA_Transmission (This : in out USART) with
Inline,
Post => DMA_Transmit_Requests_Enabled (This) and
Enabled (This);
procedure Pause_DMA_Reception (This : in out USART)
renames Disable_DMA_Receive_Requests;
procedure Resume_DMA_Reception (This : in out USART) with
Inline,
Post => DMA_Receive_Requests_Enabled (This) and
Enabled (This);
function Data_Register_Address (This : USART) return System.Address with
Inline;
-- Returns the address of the USART Data Register. This is exported
-- STRICTLY for the sake of clients driving a USART via DMA. All other
-- clients of this package should use the procedural interfaces Transmit
-- and Receive instead of directly accessing the Data Register!
-- Seriously, don't use this function otherwise.
-----------------------------
-- HAL.UART implementation --
-----------------------------
overriding
function Data_Size (This : USART) return HAL.UART.UART_Data_Size;
overriding
procedure Transmit
(Port : in out USART;
Data : UART_Data_8b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_8b;
overriding
procedure Transmit
(Port : in out USART;
Data : UART_Data_9b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_9b;
overriding
procedure Receive
(Port : in out USART;
Data : out UART_Data_8b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_8b;
overriding
procedure Receive
(Port : in out USART;
Data : out UART_Data_9b;
Status : out UART_Status;
Timeout : Natural := 1000)
with
Pre'Class => Data_Size (Port) = Data_Size_9b;
private
function APB_Clock (This : USART) return Word with Inline;
-- Returns either APB1 or APB2 clock rate, in Hertz, depending on the
-- USART. For the sake of not making this package board-specific, we assume
-- that we are given a valid USART object at a valid address, AND that the
-- USART devices really are configured such that only 1 and 6 are on APB2.
-- Therefore, if a board has additional USARTs beyond USART6, eg USART8 on
-- the F429I Discovery board, they better conform to that assumption.
-- See Note # 2 in each of Tables 139-141 of the RM on pages 970 - 972.
type Internal_USART is new STM32_SVD.USART.USART2_Peripheral;
type USART (Periph : not null access Internal_USART) is
limited new HAL.UART.UART_Port with null record;
end STM32.USARTs;
|
Fix compilation error in the STM32F4's USART driver.
|
Fix compilation error in the STM32F4's USART driver.
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library
|
f518b2059db922bed02cb76e8edcaad12f5cebde
|
src/natools-web-comment_cookies.adb
|
src/natools-web-comment_cookies.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Parsers;
with Natools.S_Expressions.Printers.Pretty;
package body Natools.Web.Comment_Cookies is
Parameters : constant Natools.S_Expressions.Printers.Pretty.Parameters
:= (Width => 0,
Newline_At => (others => (others => False)),
Space_At => (others => (others => False)),
Tab_Stop => <>,
Indentation => 0,
Indent => <>,
Quoted => S_Expressions.Printers.Pretty.No_Quoted,
Token => S_Expressions.Printers.Pretty.Extended_Token,
Hex_Casing => <>,
Quoted_Escape => <>,
Char_Encoding => <>,
Fallback => S_Expressions.Printers.Pretty.Verbatim,
Newline => S_Expressions.Printers.Pretty.LF);
function Create (A : S_Expressions.Atom)
return S_Expressions.Atom_Refs.Immutable_Reference
renames S_Expressions.Atom_Ref_Constructors.Create;
procedure Set_Atom
(Info : in out Comment_Info;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
function To_Atom (Kind : in Atom_Kind) return S_Expressions.Atom;
procedure Initialize is new S_Expressions.Interpreter_Loop
(Comment_Info, Meaningless_Type, Set_Atom);
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Set_Atom
(Info : in out Comment_Info;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use type S_Expressions.Events.Event;
Kind : Atom_Kind;
begin
if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then
return;
end if;
declare
S_Name : constant String := S_Expressions.To_String (Name);
begin
Kind := Atom_Kind'Value (S_Name);
exception
when Constraint_Error =>
Log (Severities.Error, "Unknown comment atom kind """
& S_Name & '"');
end;
Info.Refs (Kind) := Create (Arguments.Current_Atom);
end Set_Atom;
function To_Atom (Kind : in Atom_Kind) return S_Expressions.Atom is
begin
case Kind is
when Name =>
return (Character'Pos ('N'), Character'Pos ('a'),
Character'Pos ('m'), Character'Pos ('e'));
when Mail =>
return (Character'Pos ('M'), Character'Pos ('a'),
Character'Pos ('i'), Character'Pos ('l'));
when Link =>
return (Character'Pos ('L'), Character'Pos ('n'),
Character'Pos ('n'), Character'Pos ('k'));
when Filter =>
return (Character'Pos ('F'), Character'Pos ('i'),
Character'Pos ('l'), Character'Pos ('t'),
Character'Pos ('e'), Character'Pos ('r'));
end case;
end To_Atom;
-----------------------------------
-- Comment Info Public Interface --
-----------------------------------
function Create
(Name : in S_Expressions.Atom_Refs.Immutable_Reference;
Mail : in S_Expressions.Atom_Refs.Immutable_Reference;
Link : in S_Expressions.Atom_Refs.Immutable_Reference;
Filter : in S_Expressions.Atom_Refs.Immutable_Reference)
return Comment_Info is
begin
return (Refs =>
(Comment_Cookies.Name => Name,
Comment_Cookies.Mail => Mail,
Comment_Cookies.Link => Link,
Comment_Cookies.Filter => Filter));
end Create;
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Comment_Info
is
use type S_Expressions.Events.Event;
Result : Comment_Info := Null_Info;
Event : S_Expressions.Events.Event;
begin
case Expression.Current_Event is
when S_Expressions.Events.Add_Atom =>
for Kind in Result.Refs'Range loop
Result.Refs (Kind) := Create (Expression.Current_Atom);
Expression.Next (Event);
exit when Event /= S_Expressions.Events.Add_Atom;
end loop;
when S_Expressions.Events.Open_List =>
Initialize (Expression, Result, Meaningless_Value);
when S_Expressions.Events.Close_List
| S_Expressions.Events.End_Of_Input
| S_Expressions.Events.Error
=>
null;
end case;
return Result;
end Create;
function Named_Serialization (Info : in Comment_Info)
return S_Expressions.Atom
is
Buffer : aliased S_Expressions.Atom_Buffers.Atom_Buffer;
Printer : S_Expressions.Printers.Pretty.Stream_Printer (Buffer'Access);
begin
Printer.Set_Parameters (Parameters);
Buffer.Preallocate (120);
for Kind in Atom_Kind loop
if not Info.Refs (Kind).Is_Empty then
Printer.Open_List;
Printer.Append_Atom (To_Atom (Kind));
Printer.Append_Atom (Info.Refs (Kind).Query);
Printer.Close_List;
end if;
end loop;
return Buffer.Data;
end Named_Serialization;
function Positional_Serialization (Info : in Comment_Info)
return S_Expressions.Atom
is
Buffer : aliased S_Expressions.Atom_Buffers.Atom_Buffer;
Printer : S_Expressions.Printers.Pretty.Stream_Printer (Buffer'Access);
Last : Atom_Kind;
begin
Printer.Set_Parameters (Parameters);
Buffer.Preallocate (120);
Last := Atom_Kind'Last;
while Info.Refs (Last).Is_Empty loop
if Last = Atom_Kind'First then
return S_Expressions.Null_Atom;
else
Last := Atom_Kind'Pred (Last);
end if;
end loop;
for Kind in Atom_Kind'First .. Last loop
if Info.Refs (Kind).Is_Empty then
Printer.Append_Atom (S_Expressions.Null_Atom);
else
Printer.Append_Atom (Info.Refs (Kind).Query);
end if;
end loop;
return Buffer.Data;
end Positional_Serialization;
-------------------------------
-- Codec DB Public Interface --
-------------------------------
function Decode
(DB : in Codec_DB;
Cookie : in String)
return Comment_Info
is
Cursor : Decoder_Maps.Cursor;
begin
if Cookie'Length = 0 then
return Null_Info;
end if;
Cursor := DB.Dec.Find (Cookie (Cookie'First));
if not Decoder_Maps.Has_Element (Cursor) then
return Null_Info;
end if;
declare
Parser : S_Expressions.Parsers.Memory_Parser
:= S_Expressions.Parsers.Create
(Decoder_Maps.Element (Cursor).all (Cookie));
begin
Parser.Next;
return Create (Parser);
end;
end Decode;
function Encode
(DB : in Codec_DB;
Info : in Comment_Info)
return String is
begin
if DB.Enc = null then
raise Program_Error
with "Comment_Cookie.Encode called before Set_Encoder";
end if;
case DB.Serialization is
when Named =>
return DB.Enc.all (Named_Serialization (Info));
when Positional =>
return DB.Enc.all (Positional_Serialization (Info));
end case;
end Encode;
procedure Register
(DB : in out Codec_DB;
Key : in Character;
Filter : in not null Decoder) is
begin
DB.Dec := Decoder_Maps.Include (DB.Dec, Key, Filter);
end Register;
procedure Set_Encoder
(DB : in out Codec_DB;
Filter : in not null Encoder;
Serialization : in Serialization_Kind) is
begin
DB.Enc := Filter;
DB.Serialization := Serialization;
end Set_Encoder;
end Natools.Web.Comment_Cookies;
|
------------------------------------------------------------------------------
-- Copyright (c) 2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Parsers;
with Natools.S_Expressions.Printers.Pretty;
package body Natools.Web.Comment_Cookies is
Parameters : constant Natools.S_Expressions.Printers.Pretty.Parameters
:= (Width => 0,
Newline_At => (others => (others => False)),
Space_At => (others => (others => False)),
Tab_Stop => <>,
Indentation => 0,
Indent => <>,
Quoted => S_Expressions.Printers.Pretty.No_Quoted,
Token => S_Expressions.Printers.Pretty.Extended_Token,
Hex_Casing => <>,
Quoted_Escape => <>,
Char_Encoding => <>,
Fallback => S_Expressions.Printers.Pretty.Verbatim,
Newline => S_Expressions.Printers.Pretty.LF);
function Create (A : S_Expressions.Atom)
return S_Expressions.Atom_Refs.Immutable_Reference
renames S_Expressions.Atom_Ref_Constructors.Create;
procedure Set_Atom
(Info : in out Comment_Info;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
function To_Atom (Kind : in Atom_Kind) return S_Expressions.Atom;
procedure Initialize is new S_Expressions.Interpreter_Loop
(Comment_Info, Meaningless_Type, Set_Atom);
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Set_Atom
(Info : in out Comment_Info;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
use type S_Expressions.Events.Event;
Kind : Atom_Kind;
begin
if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then
return;
end if;
declare
S_Name : constant String := S_Expressions.To_String (Name);
begin
Kind := Atom_Kind'Value (S_Name);
exception
when Constraint_Error =>
Log (Severities.Error, "Unknown comment atom kind """
& S_Name & '"');
end;
Info.Refs (Kind) := Create (Arguments.Current_Atom);
end Set_Atom;
function To_Atom (Kind : in Atom_Kind) return S_Expressions.Atom is
begin
case Kind is
when Name =>
return (Character'Pos ('N'), Character'Pos ('a'),
Character'Pos ('m'), Character'Pos ('e'));
when Mail =>
return (Character'Pos ('M'), Character'Pos ('a'),
Character'Pos ('i'), Character'Pos ('l'));
when Link =>
return (Character'Pos ('L'), Character'Pos ('n'),
Character'Pos ('n'), Character'Pos ('k'));
when Filter =>
return (Character'Pos ('F'), Character'Pos ('i'),
Character'Pos ('l'), Character'Pos ('t'),
Character'Pos ('e'), Character'Pos ('r'));
end case;
end To_Atom;
-----------------------------------
-- Comment Info Public Interface --
-----------------------------------
function Create
(Name : in S_Expressions.Atom_Refs.Immutable_Reference;
Mail : in S_Expressions.Atom_Refs.Immutable_Reference;
Link : in S_Expressions.Atom_Refs.Immutable_Reference;
Filter : in S_Expressions.Atom_Refs.Immutable_Reference)
return Comment_Info is
begin
return (Refs =>
(Comment_Cookies.Name => Name,
Comment_Cookies.Mail => Mail,
Comment_Cookies.Link => Link,
Comment_Cookies.Filter => Filter));
end Create;
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Comment_Info
is
use type S_Expressions.Events.Event;
Result : Comment_Info := Null_Info;
Event : S_Expressions.Events.Event;
begin
case Expression.Current_Event is
when S_Expressions.Events.Add_Atom =>
for Kind in Result.Refs'Range loop
Result.Refs (Kind) := Create (Expression.Current_Atom);
Expression.Next (Event);
exit when Event /= S_Expressions.Events.Add_Atom;
end loop;
when S_Expressions.Events.Open_List =>
Initialize (Expression, Result, Meaningless_Value);
when S_Expressions.Events.Close_List
| S_Expressions.Events.End_Of_Input
| S_Expressions.Events.Error
=>
null;
end case;
return Result;
end Create;
function Named_Serialization (Info : in Comment_Info)
return S_Expressions.Atom
is
Buffer : aliased S_Expressions.Atom_Buffers.Atom_Buffer;
Printer : S_Expressions.Printers.Pretty.Stream_Printer (Buffer'Access);
begin
Printer.Set_Parameters (Parameters);
Buffer.Preallocate (120);
for Kind in Atom_Kind loop
if not Info.Refs (Kind).Is_Empty then
Printer.Open_List;
Printer.Append_Atom (To_Atom (Kind));
Printer.Append_Atom (Info.Refs (Kind).Query);
Printer.Close_List;
end if;
end loop;
return Buffer.Data;
end Named_Serialization;
function Positional_Serialization (Info : in Comment_Info)
return S_Expressions.Atom
is
Buffer : aliased S_Expressions.Atom_Buffers.Atom_Buffer;
Printer : S_Expressions.Printers.Pretty.Stream_Printer (Buffer'Access);
Last : Atom_Kind;
begin
Printer.Set_Parameters (Parameters);
Buffer.Preallocate (120);
Last := Atom_Kind'Last;
while Info.Refs (Last).Is_Empty loop
if Last = Atom_Kind'First then
return S_Expressions.Null_Atom;
else
Last := Atom_Kind'Pred (Last);
end if;
end loop;
for Kind in Atom_Kind'First .. Last loop
if Info.Refs (Kind).Is_Empty then
Printer.Append_Atom (S_Expressions.Null_Atom);
else
Printer.Append_Atom (Info.Refs (Kind).Query);
end if;
end loop;
return Buffer.Data;
end Positional_Serialization;
-------------------------------
-- Codec DB Public Interface --
-------------------------------
function Decode
(DB : in Codec_DB;
Cookie : in String)
return Comment_Info
is
Cursor : Decoder_Maps.Cursor;
begin
if Cookie'Length = 0 then
return Null_Info;
end if;
Cursor := DB.Dec.Find (Cookie (Cookie'First));
if not Decoder_Maps.Has_Element (Cursor) then
return Null_Info;
end if;
declare
use type S_Expressions.Atom;
Parser : S_Expressions.Parsers.Memory_Parser
:= S_Expressions.Parsers.Create
(Decoder_Maps.Element (Cursor).all (Cookie) & (1 => 0));
begin
Parser.Next;
return Create (Parser);
end;
end Decode;
function Encode
(DB : in Codec_DB;
Info : in Comment_Info)
return String is
begin
if DB.Enc = null then
raise Program_Error
with "Comment_Cookie.Encode called before Set_Encoder";
end if;
case DB.Serialization is
when Named =>
return DB.Enc.all (Named_Serialization (Info));
when Positional =>
return DB.Enc.all (Positional_Serialization (Info));
end case;
end Encode;
procedure Register
(DB : in out Codec_DB;
Key : in Character;
Filter : in not null Decoder) is
begin
DB.Dec := Decoder_Maps.Include (DB.Dec, Key, Filter);
end Register;
procedure Set_Encoder
(DB : in out Codec_DB;
Filter : in not null Encoder;
Serialization : in Serialization_Kind) is
begin
DB.Enc := Filter;
DB.Serialization := Serialization;
end Set_Encoder;
end Natools.Web.Comment_Cookies;
|
append a terminator to catch a final S-exp token
|
comment_cookies: append a terminator to catch a final S-exp token
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
a10ab385189c119fdc50bf1ca904ff5e7499e985
|
src/security-policies-urls.ads
|
src/security-policies-urls.ads
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-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>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
--
-- === Checking for permission ===
--
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Id : Permissions.Permission_Index;
Len : Natural) is new Permissions.Permission (Id) with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- 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 URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_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 URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
use Util.Strings;
-- 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;
-- 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 URL_Policy;
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 URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-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>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
--
-- === Checking for permission ===
-- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL.
--
-- URI : constant String := ...;
-- Perm : constant Policies.URLs.URI_Permission (1, URI'Length)
-- := URI_Permission '(1, Len => URI'Length, URI => URI);
-- Result : Boolean;
--
-- Having the security context, we can check the permission:
--
-- Context.Has_Permission (Perm, Result);
--
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Id : Permissions.Permission_Index;
Len : Natural) is new Permissions.Permission (Id) with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- 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 URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_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 URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
use Util.Strings;
-- 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;
-- 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 URL_Policy;
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 URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
087d77e7994bcd0cce51e1bf8754019fd92c0934
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Compare two files on their name and directory.
-- ------------------------------
function "<" (Left, Right : in File_Type) return Boolean is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
if Left = NO_FILE then
return False;
elsif Right = NO_FILE then
return True;
elsif Left.Dir = Right.Dir then
return Left.Name < Right.Name;
elsif Left.Dir = NO_DIRECTORY then
return True;
elsif Right.Dir = NO_DIRECTORY then
return False;
else
return Left.Dir.Path < Right.Dir.Path;
end if;
end "<";
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
use Ada.Strings.Unbounded;
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
else
Result.Path := To_Unbounded_String (Name);
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
-- ------------------------------
procedure Set_Size (Element : in File_Type;
Size : in File_Size) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type) is
begin
Into.Current := Directory;
Into.Files.Clear;
Into.Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Execute the Process procedure on each directory found in the container.
-- ------------------------------
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is
Iter : Directory_Vectors.Cursor := Container.Dirs.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Process (Directory_Vectors.Element (Iter));
Directory_Vectors.Next (Iter);
end loop;
end Each_Directory;
-- ------------------------------
-- Execute the Process procedure on each file found in the container.
-- ------------------------------
overriding
procedure Each_File (Container : in Default_Container;
Process : not null access
procedure (F : in File_Type)) is
Iter : File_Vectors.Cursor := Container.Files.First;
begin
while File_Vectors.Has_Element (Iter) loop
Process (File_Vectors.Element (Iter));
File_Vectors.Next (Iter);
end loop;
end Each_File;
end Babel.Files;
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Compare two files on their name and directory.
-- ------------------------------
function "<" (Left, Right : in File_Type) return Boolean is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
if Left = NO_FILE then
return False;
elsif Right = NO_FILE then
return True;
elsif Left.Dir = Right.Dir then
return Left.Name < Right.Name;
elsif Left.Dir = NO_DIRECTORY then
return True;
elsif Right.Dir = NO_DIRECTORY then
return False;
else
return Left.Dir.Path < Right.Dir.Path;
end if;
end "<";
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
use Ada.Strings.Unbounded;
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
else
Result.Path := To_Unbounded_String (Name);
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Return true if the file is a new file.
-- ------------------------------
function Is_New (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
return Element.Id = NO_IDENTIFIER;
end Is_New;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
-- ------------------------------
procedure Set_Size (Element : in File_Type;
Size : in File_Size) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Return the file size.
-- ------------------------------
function Get_Size (Element : in File_Type) return File_Size is
begin
return Element.Size;
end Get_Size;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type) is
begin
Into.Current := Directory;
Into.Files.Clear;
Into.Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Execute the Process procedure on each directory found in the container.
-- ------------------------------
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is
Iter : Directory_Vectors.Cursor := Container.Dirs.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Process (Directory_Vectors.Element (Iter));
Directory_Vectors.Next (Iter);
end loop;
end Each_Directory;
-- ------------------------------
-- Execute the Process procedure on each file found in the container.
-- ------------------------------
overriding
procedure Each_File (Container : in Default_Container;
Process : not null access
procedure (F : in File_Type)) is
Iter : File_Vectors.Cursor := Container.Files.First;
begin
while File_Vectors.Has_Element (Iter) loop
Process (File_Vectors.Element (Iter));
File_Vectors.Next (Iter);
end loop;
end Each_File;
end Babel.Files;
|
Implement the Is_New and Get_Size operation
|
Implement the Is_New and Get_Size operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
868ca9f26b623b6c70f6360889e20b3af810032c
|
src/wiki-nodes.ads
|
src/wiki-nodes.ads
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
package Wiki.Nodes is
pragma Preelaborate;
subtype Format_Map is Wiki.Documents.Format_Map;
subtype WString is Wide_Wide_String;
type Node_Kind is (N_HEADER,
N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_TAG_END,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag_Type is
(
-- Section 4.1 The root element
HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT =>
Level : Natural := 0;
Header : WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : WString (1 .. Len);
when N_LINK | N_IMAGE =>
Link : Wiki.Attributes.Attribute_List_Type;
when N_QUOTE =>
Quote : WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag_Type;
Attributes : Wiki.Attributes.Attribute_List_Type;
Children : Node_List_Access;
Parent : Node_Type_Access;
when N_TAG_END =>
Tag_End : Html_Tag_Type;
when others =>
null;
end case;
end record;
-- Create a text node.
function Create_Text (Text : in WString) return Node_Type_Access;
type Document is limited private;
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Node_Type_Access);
-- Append a HTML tag start node to the document.
procedure Add_Tag (Document : in out Wiki.Nodes.Document;
Tag : in Html_Tag_Type;
Attributes : in Wiki.Attributes.Attribute_List_Type);
-- procedure Add_Text (Doc : in out Document;
-- Text : in WString);
-- type Renderer is limited interface;
--
-- procedure Render (Engine : in out Renderer;
-- Doc : in Document;
-- Node : in Node_Type) is abstract;
--
-- procedure Iterate (Doc : in Document;
-- Process : access procedure (Doc : in Document; Node : in Node_Type)) is
-- Node : Document_Node_Access := Doc.First;
-- begin
-- while Node /= null loop
-- Process (Doc, Node.Data);
-- Node := Node.Next;
-- end loop;
-- end Iterate;
private
NODE_LIST_BLOCK_SIZE : constant Positive := 20;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block_Access;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
-- Append a node to the node list.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
type Document is limited record
Nodes : Node_List;
Current : Node_Type_Access;
end record;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
package Wiki.Nodes is
pragma Preelaborate;
subtype Format_Map is Wiki.Documents.Format_Map;
subtype WString is Wide_Wide_String;
type Node_Kind is (N_HEADER,
N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_TAG_END,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- The possible HTML tags as described in HTML5 specification.
type Html_Tag_Type is
(
-- Section 4.1 The root element
HTML_TAG,
-- Section 4.2 Document metadata
HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG,
-- Section 4.3 Sections
BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG,
H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG,
HEADER_TAG, FOOTER_TAG,
ADDRESS_TAG,
-- Section 4.4 Grouping content
P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG,
OL_TAG, UL_TAG, LI_TAG,
DL_TAG, DT_TAG, DD_TAG,
FIGURE_TAG, FIGCAPTION_TAG,
DIV_TAG, MAIN_TAG,
-- Section 4.5 Text-level semantics
A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG,
S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG,
DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG,
KBD_TAG, SUB_TAG, SUP_TAG,
I_TAG, B_TAG, U_TAG,
MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG,
RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG,
BR_TAG, WBR_TAG,
-- Section 4.6 Edits
INS_TAG, DEL_TAG,
-- Section 4.7 Embedded content
IMG_TAG,
IFRAME_TAG,
EMBED_TAG,
OBJECT_TAG,
PARAM_TAG,
VIDEO_TAG,
AUDIO_TAG,
SOURCE_TAG,
TRACK_TAG,
MAP_TAG,
AREA_TAG,
-- Section 4.9 Tabular data
TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG,
TBODY_TAG, THEAD_TAG, TFOOT_TAG,
TR_TAG, TD_TAG, TH_TAG,
-- Section 4.10 Forms
FORM_TAG, LABEL_TAG, INPUT_TAG,
BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG,
OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG,
PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG,
-- Section 4.11 Scripting
SCRIPT_TAG, NOSCRIPT_TAG,
TEMPLATE_TAG, CANVAS_TAG,
-- Unknown tags
UNKNOWN_TAG
);
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT =>
Level : Natural := 0;
Header : WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : WString (1 .. Len);
when N_LINK | N_IMAGE =>
Link_Attr : Wiki.Attributes.Attribute_List_Type;
Title : WString (1 .. Len);
when N_QUOTE =>
Quote_Attr : Wiki.Attributes.Attribute_List_Type;
Quote : WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag_Type;
Attributes : Wiki.Attributes.Attribute_List_Type;
Children : Node_List_Access;
Parent : Node_Type_Access;
when N_TAG_END =>
Tag_End : Html_Tag_Type;
when others =>
null;
end case;
end record;
-- Create a text node.
function Create_Text (Text : in WString) return Node_Type_Access;
type Document is limited private;
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Node_Type_Access);
-- Append a HTML tag start node to the document.
procedure Add_Tag (Document : in out Wiki.Nodes.Document;
Tag : in Html_Tag_Type;
Attributes : in Wiki.Attributes.Attribute_List_Type);
-- procedure Add_Text (Doc : in out Document;
-- Text : in WString);
-- type Renderer is limited interface;
--
-- procedure Render (Engine : in out Renderer;
-- Doc : in Document;
-- Node : in Node_Type) is abstract;
--
-- procedure Iterate (Doc : in Document;
-- Process : access procedure (Doc : in Document; Node : in Node_Type)) is
-- Node : Document_Node_Access := Doc.First;
-- begin
-- while Node /= null loop
-- Process (Doc, Node.Data);
-- Node := Node.Next;
-- end loop;
-- end Iterate;
private
NODE_LIST_BLOCK_SIZE : constant Positive := 20;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block_Access;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
-- Append a node to the node list.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
type Document is limited record
Nodes : Node_List;
Current : Node_Type_Access;
end record;
end Wiki.Nodes;
|
Add a Quote_Attr member for N_QUOTE attributes
|
Add a Quote_Attr member for N_QUOTE attributes
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
30e2dda418e75ace24028ef992cfc71565ee92ea
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "1";
raven_version_minor : constant String := "04";
copyright_years : constant String := "2015-2018";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.28";
default_pgsql : constant String := "10";
default_php : constant String := "7.2";
default_python3 : constant String := "3.7";
default_ruby : constant String := "2.5";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc7";
compiler_version : constant String := "7.3.0";
previous_compiler : constant String := "7.2.0";
binutils_version : constant String := "2.30";
previous_binutils : constant String := "2.29.1";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "1";
raven_version_minor : constant String := "04";
copyright_years : constant String := "2015-2018";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.28";
default_pgsql : constant String := "10";
default_php : constant String := "7.2";
default_python3 : constant String := "3.7";
default_ruby : constant String := "2.5";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc8";
compiler_version : constant String := "8.2.0";
previous_compiler : constant String := "7.3.0";
binutils_version : constant String := "2.31.1";
previous_binutils : constant String := "2.30";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
Use gcc8, binutils 2.31.1
|
Use gcc8, binutils 2.31.1
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
0618e907efcae03baf8afed256b5d38519f25f68
|
awa/plugins/awa-tags/src/awa-tags-beans.adb
|
awa/plugins/awa-tags/src/awa-tags-beans.adb
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
with AWA.Tags.Models;
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;
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;
-- ------------------------------
-- 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;
|
Implement the Get_Tags and Load_Tags operations
|
Implement the Get_Tags and Load_Tags operations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6d13d182ce2877abaf36f97e34d44e8ad5c3cdb3
|
mat/src/memory/mat-memory.ads
|
mat/src/memory/mat-memory.ads
|
-----------------------------------------------------------------------
-- Memory - Memory slot
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded;
with ELF;
with MAT.Types;
with MAT.Frames;
with Interfaces;
package MAT.Memory is
type Allocation is record
Size : MAT.Types.Target_Size;
Frame : Frames.Frame_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
end record;
-- Statistics about memory allocation.
type Memory_Info is record
Total_Size : MAT.Types.Target_Size := 0;
Alloc_Count : Natural := 0;
Min_Slot_Size : MAT.Types.Target_Size := 0;
Max_Slot_Size : MAT.Types.Target_Size := 0;
Min_Addr : MAT.Types.Target_Addr := 0;
Max_Addr : MAT.Types.Target_Addr := 0;
end record;
-- Description of a memory region.
type Region_Info is record
Start_Addr : MAT.Types.Target_Addr := 0;
End_Addr : MAT.Types.Target_Addr := 0;
Size : MAT.Types.Target_Size := 0;
Flags : ELF.Elf32_Word := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
end record;
use type MAT.Types.Target_Addr;
package Allocation_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Allocation);
subtype Allocation_Map is Allocation_Maps.Map;
subtype Allocation_Cursor is Allocation_Maps.Cursor;
-- Define a map of <tt>Memory_Info</tt> keyed by the thread Id.
-- Such map allows to give the list of threads and a summary of their allocation.
use type MAT.Types.Target_Thread_Ref;
package Memory_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref,
Element_Type => Memory_Info);
subtype Memory_Info_Map is Memory_Info_Maps.Map;
subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor;
type Frame_Info is record
Thread : MAT.Types.Target_Thread_Ref;
Memory : Memory_Info;
end record;
-- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address
-- that performed the memory allocation directly or indirectly.
package Frame_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Frame_Info);
subtype Frame_Info_Map is Frame_Info_Maps.Map;
subtype Frame_Info_Cursor is Frame_Info_Maps.Cursor;
package Region_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_TYpe => Region_Info);
subtype Region_Info_Map is Region_Info_Maps.Map;
subtype Region_Info_Cursor is Region_Info_Maps.Cursor;
private
end MAT.Memory;
|
-----------------------------------------------------------------------
-- Memory - Memory slot
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded;
with ELF;
with MAT.Types;
with MAT.Frames;
with Interfaces;
package MAT.Memory is
type Allocation is record
Size : MAT.Types.Target_Size;
Frame : Frames.Frame_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
end record;
-- Statistics about memory allocation.
type Memory_Info is record
Total_Size : MAT.Types.Target_Size := 0;
Alloc_Count : Natural := 0;
Min_Slot_Size : MAT.Types.Target_Size := 0;
Max_Slot_Size : MAT.Types.Target_Size := 0;
Min_Addr : MAT.Types.Target_Addr := 0;
Max_Addr : MAT.Types.Target_Addr := 0;
end record;
-- Description of a memory region.
type Region_Info is record
Start_Addr : MAT.Types.Target_Addr := 0;
End_Addr : MAT.Types.Target_Addr := 0;
Size : MAT.Types.Target_Size := 0;
Flags : ELF.Elf32_Word := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
end record;
use type MAT.Types.Target_Addr;
package Allocation_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Allocation);
subtype Allocation_Map is Allocation_Maps.Map;
subtype Allocation_Cursor is Allocation_Maps.Cursor;
-- Define a map of <tt>Memory_Info</tt> keyed by the thread Id.
-- Such map allows to give the list of threads and a summary of their allocation.
use type MAT.Types.Target_Thread_Ref;
package Memory_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref,
Element_Type => Memory_Info);
subtype Memory_Info_Map is Memory_Info_Maps.Map;
subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor;
type Frame_Info is record
Thread : MAT.Types.Target_Thread_Ref;
Memory : Memory_Info;
end record;
-- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address
-- that performed the memory allocation directly or indirectly.
package Frame_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Frame_Info);
subtype Frame_Info_Map is Frame_Info_Maps.Map;
subtype Frame_Info_Cursor is Frame_Info_Maps.Cursor;
package Region_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Info);
subtype Region_Info_Map is Region_Info_Maps.Map;
subtype Region_Info_Cursor is Region_Info_Maps.Cursor;
private
end MAT.Memory;
|
Fix typo
|
Fix typo
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
7626e226ce87540547f492f3468d095dcec6958a
|
src/util-properties.adb
|
src/util-properties.adb
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- with Util.Properties.Factories;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded.Text_IO;
with Interfaces.C.Strings;
with Ada.Unchecked_Deallocation;
package body Util.Properties is
use Ada.Text_IO;
use Ada.Strings.Unbounded.Text_IO;
use Interface_P;
use Util.Beans.Objects;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Interface_P.Manager'Class,
Name => Interface_P.Manager_Access);
type Property_Map is new Interface_P.Manager with record
Props : Util.Beans.Objects.Maps.Map_Bean;
end record;
type Property_Map_Access is access all Property_Map;
-- 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 Property_Map;
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 Property_Map;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
overriding
function Exists (Self : in Property_Map;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Property_Map; Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Property_Map;
Process : access procedure (Name, Item : Value));
-- Deep copy of properties stored in 'From' to 'To'.
overriding
function Create_Copy (Self : in Property_Map)
return Interface_P.Manager_Access;
overriding
function Get_Names (Self : in Property_Map;
Prefix : in String) return Name_Array;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- ------------------------------
-- 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 Property_Map;
Name : in String) return Util.Beans.Objects.Object is
begin
return From.Props.Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
overriding
procedure Set_Value (From : in out Property_Map;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
From.Props.Set_Value (Name, Value);
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
overriding
function Exists (Self : in Property_Map;
Name : in String)
return Boolean is
begin
return Self.Props.Contains (Name);
end Exists;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
overriding
procedure Remove (Self : in out Property_Map; Name : in Value) is
begin
null;
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Property_Map;
Process : access procedure (Name, Item : Value)) is
begin
null;
end Iterate;
-- Deep copy of properties stored in 'From' to 'To'.
overriding
function Create_Copy (Self : in Property_Map)
return Interface_P.Manager_Access is
Result : Property_Map_Access := new Property_Map;
begin
Result.Props := Self.Props;
return Result.all'Access;
end Create_Copy;
overriding
function Get_Names (Self : in Property_Map;
Prefix : in String) return Name_Array is
N : Name_Array (1 .. 0);
begin
return N;
end Get_Names;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Impl = null then
return Util.Beans.Objects.Null_Object;
else
return From.Impl.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Check_And_Create_Impl (From);
From.Impl.Set_Value (Name, Value);
end Set_Value;
function Exists (Self : in Manager'Class;
Name : in String) return Boolean is
begin
-- There is not yet an implementation, no property
return Self.Impl /= null and then Self.Impl.Exists (Name);
end Exists;
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean is
begin
-- There is not yet an implementation, no property
return Self.Impl /= null and then Self.Impl.Exists (-Name);
end Exists;
function Get (Self : in Manager'Class;
Name : in String) return Value is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return Value (To_Unbounded_String (Self.Impl.Get_Value (Name)));
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return Value is
begin
return Self.Get (-Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return To_String (Self.Impl.Get_Value (Name));
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
return To_String (Self.Get_Value (-Name));
end Get;
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String is
begin
if Exists (Self, Name) then
return Get (Self, Name);
else
return Default;
end if;
end Get;
procedure Check_And_Create_Impl (Self : in out Manager) is
begin
if Self.Impl = null then
-- Util.Properties.Factories.Initialize (Self);
Self.Impl := new Property_Map;
Util.Concurrent.Counters.Increment (Self.Impl.Count);
elsif Util.Concurrent.Counters.Value (Self.Impl.Count) > 1 then
declare
Old : Interface_P.Manager_Access := Self.Impl;
Is_Zero : Boolean;
begin
Self.Impl := Create_Copy (Self.Impl.all);
Util.Concurrent.Counters.Increment (Self.Impl.Count);
Util.Concurrent.Counters.Decrement (Old.Count, Is_Zero);
if Is_Zero then
Free (Old);
end if;
end;
end if;
end Check_And_Create_Impl;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Self.Set_Value (Name, To_Object (Item));
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value) is
begin
Self.Set_Value (Name, To_Object (Item));
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value) is
begin
Self.Set_Value (-Name, To_Object (Item));
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in String) is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property '" & Name & "'";
end if;
Check_And_Create_Impl (Self);
Remove (Self.Impl.all, +Name);
end Remove;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in Value) is
begin
Self.Remove (-Name);
end Remove;
-- ------------------------------
-- 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, Item : Value)) is
begin
if Self.Impl /= null then
Self.Impl.Iterate (Process);
end if;
end Iterate;
-- ------------------------------
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
-- ------------------------------
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array is
begin
if Self.Impl = null then
declare
Empty : Name_Array (1 .. 0);
begin
return Empty;
end;
else
return Get_Names (Self.Impl.all, Prefix);
end if;
end Get_Names;
procedure Adjust (Object : in out Manager) is
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end if;
end Adjust;
procedure Finalize (Object : in out Manager) is
Is_Zero : Boolean;
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Decrement (Object.Impl.Count, Is_Zero);
if Is_Zero then
Free (Object.Impl);
end if;
end if;
end Finalize;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access) is
begin
if Self.Impl = null then
Self.Impl := Impl;
-- Self.Impl.Count := 1;
end if;
end Set_Property_Implementation;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False) is
pragma Unreferenced (Strip);
Line : Unbounded_String;
Pos : Natural;
Len : Natural;
begin
while not End_Of_File (File) loop
Line := Get_Line (File);
Len := Length (Line);
if Len /= 0 and then Element (Line, 1) /= '#' then
Pos := Index (Line, "=");
if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then
Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
elsif Pos > 0 and Prefix'Length = 0 then
Name := Head (Line, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
end if;
end if;
end loop;
Name := Null_Unbounded_String;
Value := Null_Unbounded_String;
end Load_Property;
procedure Load_Properties (Self : in out Manager'Class;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False) is
Name, Value : Unbounded_String;
begin
loop
Load_Property (Name, Value, File, Prefix, Strip);
exit when Name = Null_Unbounded_String;
Set (Self, Name, Value);
end loop;
exception
when End_Error =>
return;
end Load_Properties;
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False) is
F : File_Type;
begin
Open (F, In_File, Path);
Load_Properties (Self, F, Prefix, Strip);
Close (F);
end Load_Properties;
-- ------------------------------
-- Save the properties in the given file path.
-- ------------------------------
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "") is
procedure Save_Property (Name, Item : in Value);
Tmp : constant String := Path & ".tmp";
F : File_Type;
procedure Save_Property (Name, Item : in Value) is
begin
Put (F, Name);
Put (F, "=");
Put (F, Item);
New_Line (F);
end Save_Property;
-- Rename a file (the Ada.Directories.Rename does not allow to use the Unix atomic file rename!)
function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr;
Newpath : in Interfaces.C.Strings.chars_ptr) return Integer;
pragma Import (C, Sys_Rename, "rename");
Old_Path : Interfaces.C.Strings.chars_ptr;
New_Path : Interfaces.C.Strings.chars_ptr;
Result : Integer;
begin
Create (File => F, Name => Tmp);
Self.Iterate (Save_Property'Access);
Close (File => F);
-- Do a system atomic rename of old file in the new file.
-- Ada.Directories.Rename does not allow this.
Old_Path := Interfaces.C.Strings.New_String (Tmp);
New_Path := Interfaces.C.Strings.New_String (Path);
Result := Sys_Rename (Old_Path, New_Path);
Interfaces.C.Strings.Free (Old_Path);
Interfaces.C.Strings.Free (New_Path);
if Result /= 0 then
raise Ada.IO_Exceptions.Use_Error with "Cannot rename file";
end if;
end Save_Properties;
-- ------------------------------
-- 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) is
Names : constant Name_Array := From.Get_Names;
begin
for I in Names'Range loop
declare
Name : Unbounded_String renames Names (I);
begin
if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then
if Strip and Prefix'Length > 0 then
declare
S : constant String := Slice (Name, Prefix'Length + 1, Length (Name));
begin
Self.Set (+(S), From.Get (Name));
end;
else
Self.Set (Name, From.Get (Name));
end if;
end if;
end;
end loop;
end Copy;
end Util.Properties;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- with Util.Properties.Factories;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded.Text_IO;
with Interfaces.C.Strings;
with Ada.Unchecked_Deallocation;
package body Util.Properties is
use Ada.Text_IO;
use Ada.Strings.Unbounded.Text_IO;
use Interface_P;
use Util.Beans.Objects;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Interface_P.Manager'Class,
Name => Interface_P.Manager_Access);
type Property_Map is new Interface_P.Manager with record
Props : Util.Beans.Objects.Maps.Map_Bean;
end record;
type Property_Map_Access is access all Property_Map;
-- 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 Property_Map;
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 Property_Map;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
overriding
function Exists (Self : in Property_Map;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Property_Map; Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Property_Map;
Process : access procedure (Name, Item : Value));
-- Deep copy of properties stored in 'From' to 'To'.
overriding
function Create_Copy (Self : in Property_Map)
return Interface_P.Manager_Access;
overriding
function Get_Names (Self : in Property_Map;
Prefix : in String) return Name_Array;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- ------------------------------
-- 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 Property_Map;
Name : in String) return Util.Beans.Objects.Object is
begin
return From.Props.Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
overriding
procedure Set_Value (From : in out Property_Map;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
From.Props.Set_Value (Name, Value);
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
overriding
function Exists (Self : in Property_Map;
Name : in String)
return Boolean is
begin
return Self.Props.Contains (Name);
end Exists;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
overriding
procedure Remove (Self : in out Property_Map; Name : in Value) is
begin
null;
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Property_Map;
Process : access procedure (Name, Item : Value)) is
begin
null;
end Iterate;
-- Deep copy of properties stored in 'From' to 'To'.
overriding
function Create_Copy (Self : in Property_Map)
return Interface_P.Manager_Access is
Result : Property_Map_Access := new Property_Map;
begin
Result.Props := Self.Props;
return Result.all'Access;
end Create_Copy;
overriding
function Get_Names (Self : in Property_Map;
Prefix : in String) return Name_Array is
N : Name_Array (1 .. 0);
begin
return N;
end Get_Names;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Impl = null then
return Util.Beans.Objects.Null_Object;
else
return From.Impl.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Check_And_Create_Impl (From);
From.Impl.Set_Value (Name, Value);
end Set_Value;
function Exists (Self : in Manager'Class;
Name : in String) return Boolean is
begin
-- There is not yet an implementation, no property
return Self.Impl /= null and then Self.Impl.Exists (Name);
end Exists;
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean is
begin
-- There is not yet an implementation, no property
return Self.Impl /= null and then Self.Impl.Exists (-Name);
end Exists;
function Get (Self : in Manager'Class;
Name : in String) return Value is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return Value (To_Unbounded_String (Self.Impl.Get_Value (Name)));
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return Value is
begin
return Self.Get (-Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return To_String (Self.Impl.Get_Value (Name));
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
return To_String (Self.Get_Value (-Name));
end Get;
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String is
begin
if Exists (Self, Name) then
return Get (Self, Name);
else
return Default;
end if;
end Get;
procedure Check_And_Create_Impl (Self : in out Manager) is
begin
if Self.Impl = null then
Self.Impl := new Property_Map;
Util.Concurrent.Counters.Increment (Self.Impl.Count);
elsif Util.Concurrent.Counters.Value (Self.Impl.Count) > 1 then
declare
Old : Interface_P.Manager_Access := Self.Impl;
Is_Zero : Boolean;
begin
Self.Impl := Create_Copy (Self.Impl.all);
Util.Concurrent.Counters.Increment (Self.Impl.Count);
Util.Concurrent.Counters.Decrement (Old.Count, Is_Zero);
if Is_Zero then
Free (Old);
end if;
end;
end if;
end Check_And_Create_Impl;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Self.Set_Value (Name, To_Object (Item));
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value) is
begin
Self.Set_Value (Name, To_Object (Item));
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value) is
begin
Self.Set_Value (-Name, To_Object (Item));
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in String) is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property '" & Name & "'";
end if;
Check_And_Create_Impl (Self);
Remove (Self.Impl.all, +Name);
end Remove;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in Value) is
begin
Self.Remove (-Name);
end Remove;
-- ------------------------------
-- 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, Item : Value)) is
begin
if Self.Impl /= null then
Self.Impl.Iterate (Process);
end if;
end Iterate;
-- ------------------------------
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
-- ------------------------------
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array is
begin
if Self.Impl = null then
declare
Empty : Name_Array (1 .. 0);
begin
return Empty;
end;
else
return Get_Names (Self.Impl.all, Prefix);
end if;
end Get_Names;
procedure Adjust (Object : in out Manager) is
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end if;
end Adjust;
procedure Finalize (Object : in out Manager) is
Is_Zero : Boolean;
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Decrement (Object.Impl.Count, Is_Zero);
if Is_Zero then
Free (Object.Impl);
end if;
end if;
end Finalize;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False) is
pragma Unreferenced (Strip);
Line : Unbounded_String;
Pos : Natural;
Len : Natural;
begin
while not End_Of_File (File) loop
Line := Get_Line (File);
Len := Length (Line);
if Len /= 0 and then Element (Line, 1) /= '#' then
Pos := Index (Line, "=");
if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then
Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
elsif Pos > 0 and Prefix'Length = 0 then
Name := Head (Line, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
end if;
end if;
end loop;
Name := Null_Unbounded_String;
Value := Null_Unbounded_String;
end Load_Property;
procedure Load_Properties (Self : in out Manager'Class;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False) is
Name, Value : Unbounded_String;
begin
loop
Load_Property (Name, Value, File, Prefix, Strip);
exit when Name = Null_Unbounded_String;
Set (Self, Name, Value);
end loop;
exception
when End_Error =>
return;
end Load_Properties;
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False) is
F : File_Type;
begin
Open (F, In_File, Path);
Load_Properties (Self, F, Prefix, Strip);
Close (F);
end Load_Properties;
-- ------------------------------
-- Save the properties in the given file path.
-- ------------------------------
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "") is
procedure Save_Property (Name, Item : in Value);
Tmp : constant String := Path & ".tmp";
F : File_Type;
procedure Save_Property (Name, Item : in Value) is
begin
Put (F, Name);
Put (F, "=");
Put (F, Item);
New_Line (F);
end Save_Property;
-- Rename a file (the Ada.Directories.Rename does not allow to use the Unix atomic file rename!)
function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr;
Newpath : in Interfaces.C.Strings.chars_ptr) return Integer;
pragma Import (C, Sys_Rename, "rename");
Old_Path : Interfaces.C.Strings.chars_ptr;
New_Path : Interfaces.C.Strings.chars_ptr;
Result : Integer;
begin
Create (File => F, Name => Tmp);
Self.Iterate (Save_Property'Access);
Close (File => F);
-- Do a system atomic rename of old file in the new file.
-- Ada.Directories.Rename does not allow this.
Old_Path := Interfaces.C.Strings.New_String (Tmp);
New_Path := Interfaces.C.Strings.New_String (Path);
Result := Sys_Rename (Old_Path, New_Path);
Interfaces.C.Strings.Free (Old_Path);
Interfaces.C.Strings.Free (New_Path);
if Result /= 0 then
raise Ada.IO_Exceptions.Use_Error with "Cannot rename file";
end if;
end Save_Properties;
-- ------------------------------
-- 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) is
Names : constant Name_Array := From.Get_Names;
begin
for I in Names'Range loop
declare
Name : Unbounded_String renames Names (I);
begin
if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then
if Strip and Prefix'Length > 0 then
declare
S : constant String := Slice (Name, Prefix'Length + 1, Length (Name));
begin
Self.Set (+(S), From.Get (Name));
end;
else
Self.Set (Name, From.Get (Name));
end if;
end if;
end;
end loop;
end Copy;
end Util.Properties;
|
Refactor the Properties implementation (step 2): - Remove Set_Property_Implementation procedure
|
Refactor the Properties implementation (step 2):
- Remove Set_Property_Implementation procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
58e8c426c30d98c589d06ff5a44a967442bbfe41
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
with Wiki.Render.Links;
-- == HTML Renderer ==
-- The <tt>Html_Renderer</tt> allows to render a wiki document into an HTML content.
--
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Wiki.Render.Links.Link_Renderer_Access);
-- Set the render TOC flag that controls the TOC rendering.
procedure Set_Render_TOC (Engine : in out Html_Renderer;
State : in Boolean);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Get the current section number.
function Get_Section_Number (Engine : in Html_Renderer;
Prefix : in Wiki.Strings.WString;
Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString;
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document);
private
procedure Close_Paragraph (Engine : in out Html_Renderer);
procedure Open_Paragraph (Engine : in out Html_Renderer);
type Toc_Number_Array is array (1 .. 6) of Natural;
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Wiki.Render.Links.Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Enable_Render_TOC : Boolean := False;
TOC_Rendered : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
Current_Section : Toc_Number_Array := (others => 0);
Section_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render the table of content.
procedure Render_TOC (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Level : in Natural);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
with Wiki.Render.Links;
-- == HTML Renderer ==
-- The <tt>Html_Renderer</tt> allows to render a wiki document into an HTML content.
--
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Wiki.Render.Links.Link_Renderer_Access);
-- Set the render TOC flag that controls the TOC rendering.
procedure Set_Render_TOC (Engine : in out Html_Renderer;
State : in Boolean);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Get the current section number.
function Get_Section_Number (Engine : in Html_Renderer;
Prefix : in Wiki.Strings.WString;
Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString;
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document);
private
procedure Close_Paragraph (Engine : in out Html_Renderer);
procedure Open_Paragraph (Engine : in out Html_Renderer);
type Toc_Number_Array is array (1 .. 6) of Natural;
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Wiki.Render.Links.Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Enable_Render_TOC : Boolean := False;
TOC_Rendered : Boolean := False;
Current_Level : Natural := 0;
Html_Tag : Wiki.Html_Tag := BODY_TAG;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
Current_Section : Toc_Number_Array := (others => 0);
Section_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render the table of content.
procedure Render_TOC (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Level : in Natural);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Returns true if the HTML element being included is already contained in a paragraph.
-- This include: a, em, strong, small, b, i, u, s, span, ins, del, sub, sup.
function Has_Html_Paragraph (Engine : in Html_Renderer) return Boolean;
end Wiki.Render.Html;
|
Declare the Has_Html_Paragraph function Add Html_Tag member to the Html_Renderer
|
Declare the Has_Html_Paragraph function
Add Html_Tag member to the Html_Renderer
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
1af47f2860de4265e6773524904809af3d1fb8ad
|
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.
-----------------------------------------------------------------------
-- == Permission ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager. An application should declare each permission
-- by instantiating the <tt>Definition</tt> package:
--
-- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace");
--
-- This declares a permission that can be represented by "<tt>create-workspace</tt>" in
-- configuration files. In Ada, the permission is used as follows:
--
-- Perm_Create_Workspace.Permission
--
package Security.Permissions is
Invalid_Name : exception;
type Permission_Index is new Natural;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- The permission root class.
-- Each permission is represented by a <b>Permission_Index</b> number to provide a fast
-- and efficient permission check.
type Permission (Id : Permission_Index) is tagged limited null record;
generic
Name : String;
package Definition is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Definition;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Interfaces;
-- == Permission ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager. An application should declare each permission
-- by instantiating the <tt>Definition</tt> package:
--
-- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace");
--
-- This declares a permission that can be represented by "<tt>create-workspace</tt>" in
-- configuration files. In Ada, the permission is used as follows:
--
-- Perm_Create_Workspace.Permission
--
package Security.Permissions is
Invalid_Name : exception;
-- Max number of permissions supported by the implementation.
MAX_PERMISSION : constant Natural := 256;
type Permission_Index is new Natural range 0 .. MAX_PERMISSION;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- The permission root class.
-- Each permission is represented by a <b>Permission_Index</b> number to provide a fast
-- and efficient permission check.
type Permission (Id : Permission_Index) is tagged limited null record;
generic
Name : String;
package Definition is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Definition;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
type Permission_Index_Set is private;
-- Check if the permission index set contains the given permission index.
function Has_Permission (Set : in Permission_Index_Set;
Index : in Permission_Index) return Boolean;
private
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8;
type Permission_Index_Set is array (1 .. INDEX_SET_SIZE) of Interfaces.Unsigned_8;
end Security.Permissions;
|
Declare Permission_Index_Set type to represent a set of permission indexes Declare the Has_Permission to check if the set contains a given permission index Declare MAX_PERMISSION constant for the implementation limits (256 permissions means 256 instantiations of the Definition package so it should be enough)
|
Declare Permission_Index_Set type to represent a set of permission indexes
Declare the Has_Permission to check if the set contains a given permission index
Declare MAX_PERMISSION constant for the implementation limits
(256 permissions means 256 instantiations of the Definition package so it
should be enough)
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
36820ea264798a253dd377f3d8d46da4e4bb5407
|
src/sys/lzma/util-streams-buffered-lzma.adb
|
src/sys/lzma/util-streams-buffered-lzma.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA streams
-- Copyright (C) 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Lzma.Check;
with Lzma.Container;
with Interfaces.C;
package body Util.Streams.Buffered.Lzma is
use type Interfaces.C.size_t;
use type Base.lzma_ret;
subtype Offset is Ada.Streams.Stream_Element_Offset;
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
overriding
procedure Initialize (Stream : in out Compress_Stream;
Output : in Output_Stream_Access;
Size : in Positive) is
Result : Base.lzma_ret;
begin
Output_Buffer_Stream (Stream).Initialize (Output, Size);
Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access;
Stream.Stream.avail_out := Stream.Buffer'Length;
Result := Container.lzma_easy_encoder (Stream.Stream'Unchecked_Access, 6,
Check.LZMA_CHECK_CRC64);
end Initialize;
-- -----------------------
-- Close the sink.
-- -----------------------
overriding
procedure Close (Stream : in out Compress_Stream) is
begin
Stream.Flush;
Stream.Output.Close;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Compress_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Last_Pos : Ada.Streams.Stream_Element_Offset;
Encoded : Boolean := False;
Result : Base.lzma_ret;
begin
loop
if Stream.Stream.avail_in = 0 then
Stream.Stream.next_in := Buffer (Buffer'First)'Unrestricted_Access;
Stream.Stream.avail_in := Interfaces.C.size_t (Buffer'Length);
Encoded := True;
end if;
Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_RUN);
-- Write the output data when the buffer is full or we reached the end of stream.
if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then
Last_Pos := Stream.Buffer'First + Stream.Buffer'Length
- Offset (Stream.Stream.avail_out) - 1;
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access;
Stream.Stream.avail_out := Stream.Buffer'Length;
end if;
exit when Result /= Base.LZMA_OK or (Stream.Stream.avail_in = 0 and Encoded);
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Compress_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset;
Result : Base.lzma_ret;
begin
Stream.Stream.next_in := null;
Stream.Stream.avail_in := 0;
loop
Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_FINISH);
if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then
Last_Pos := Stream.Buffer'First + Stream.Buffer'Length
- Offset (Stream.Stream.avail_out) - 1;
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access;
Stream.Stream.avail_out := Stream.Buffer'Length;
end if;
exit when Result /= Base.LZMA_OK;
end loop;
end Flush;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Compress_Stream) is
begin
null;
end Finalize;
end Util.Streams.Buffered.Lzma;
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA streams
-- Copyright (C) 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Lzma.Check;
with Lzma.Container;
with Interfaces.C;
with Ada.IO_Exceptions;
package body Util.Streams.Buffered.Lzma is
use type Interfaces.C.size_t;
use type Base.lzma_ret;
subtype size_t is Interfaces.C.size_t;
subtype Offset is Ada.Streams.Stream_Element_Offset;
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
overriding
procedure Initialize (Stream : in out Compress_Stream;
Output : access Output_Stream'Class;
Size : in Positive) is
Result : Base.lzma_ret;
begin
Output_Buffer_Stream (Stream).Initialize (Output, Size);
Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access;
Stream.Stream.avail_out := Stream.Buffer'Length;
Result := Container.lzma_easy_encoder (Stream.Stream'Unchecked_Access, 6,
Check.LZMA_CHECK_CRC64);
if Result /= Base.LZMA_OK then
raise Ada.IO_Exceptions.Device_Error with "Cannot initialize compressor";
end if;
end Initialize;
-- -----------------------
-- Close the sink.
-- -----------------------
overriding
procedure Close (Stream : in out Compress_Stream) is
begin
Stream.Flush;
Output_Buffer_Stream (Stream).Close;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Compress_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Last_Pos : Ada.Streams.Stream_Element_Offset;
Encoded : Boolean := False;
Result : Base.lzma_ret;
begin
loop
if Stream.Stream.avail_in = 0 then
Stream.Stream.next_in := Buffer (Buffer'First)'Unrestricted_Access;
Stream.Stream.avail_in := size_t (Buffer'Length);
Encoded := True;
end if;
Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_RUN);
-- Write the output data when the buffer is full or we reached the end of stream.
if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then
Last_Pos := Stream.Buffer'First + Stream.Buffer'Length
- Offset (Stream.Stream.avail_out) - 1;
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access;
Stream.Stream.avail_out := Stream.Buffer'Length;
end if;
exit when Result /= Base.LZMA_OK or (Stream.Stream.avail_in = 0 and Encoded);
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Compress_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset;
Result : Base.lzma_ret;
begin
Stream.Stream.next_in := null;
Stream.Stream.avail_in := 0;
loop
Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_FINISH);
if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then
Last_Pos := Stream.Buffer'First + Stream.Buffer'Length
- Offset (Stream.Stream.avail_out) - 1;
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access;
Stream.Stream.avail_out := Stream.Buffer'Length;
end if;
exit when Result /= Base.LZMA_OK;
end loop;
end Flush;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Compress_Stream) is
begin
Base.lzma_end (Object.Stream'Unchecked_Access);
Output_Buffer_Stream (Object).Finalize;
end Finalize;
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
overriding
procedure Initialize (Stream : in out Decompress_Stream;
Input : access Input_Stream'Class;
Size : in Positive) is
Result : Base.lzma_ret;
begin
Input_Buffer_Stream (Stream).Initialize (Input, Size);
Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access;
Stream.Stream.avail_in := 0;
Result := Container.lzma_stream_decoder (Stream.Stream'Unchecked_Access,
Long_Long_Integer'Last,
Container.LZMA_CONCATENATED);
if Result /= Base.LZMA_OK then
raise Ada.IO_Exceptions.Device_Error with "Cannot initialize decompressor";
end if;
end Initialize;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Read (Stream : in out Decompress_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
use type Base.lzma_action;
Result : Base.lzma_ret;
begin
Stream.Stream.next_out := Into (Into'First)'Unrestricted_Access;
Stream.Stream.avail_out := Into'Length;
loop
if Stream.Stream.avail_in = 0 and not Stream.Is_Eof
and Stream.Action = Base.LZMA_RUN
then
Stream.Fill;
if Stream.Write_Pos >= Stream.Read_Pos then
Stream.Stream.avail_in := size_t (Stream.Write_Pos - Stream.Read_Pos);
Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access;
else
Stream.Stream.avail_in := 0;
Stream.Stream.next_in := null;
Stream.Action := Base.LZMA_FINISH;
end if;
end if;
Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Stream.Action);
if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then
Last := Into'First + Into'Length
- Offset (Stream.Stream.avail_out) - 1;
return;
end if;
if Result /= Base.LZMA_OK then
raise Ada.IO_Exceptions.Data_Error with "Decompression error";
end if;
end loop;
end Read;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Decompress_Stream) is
begin
Base.lzma_end (Object.Stream'Unchecked_Access);
Input_Buffer_Stream (Object).Finalize;
end Finalize;
end Util.Streams.Buffered.Lzma;
|
Implement operations for Decompress_Stream to decompress LZMA streams
|
Implement operations for Decompress_Stream to decompress LZMA streams
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
fc71fec4760cce58a1483c182073f7261fb760c2
|
openal-context.adb
|
openal-context.adb
|
with Ada.IO_Exceptions;
with Interfaces.C;
with Interfaces.C.Strings;
with System;
package body OpenAL.Context is
package C renames Interfaces.C;
package C_Strings renames Interfaces.C.Strings;
function Open_Device
(Specifier : in String) return Device_t
is
C_Spec : aliased C.char_array := C.To_C (Specifier);
Device : Device_t;
begin
Device.Device_Data := ALC_Thin.Open_Device
(Specifier => C_Spec (C_Spec'First)'Address);
return Device;
end Open_Device;
function Open_Default_Device return Device_t is
Device : Device_t;
begin
Device.Device_Data := ALC_Thin.Open_Device
(Specifier => System.Null_Address);
return Device;
end Open_Default_Device;
function Close_Device
(Device : in Device_t) return Boolean is
begin
return Boolean (ALC_Thin.Close_Device (Device.Device_Data));
end Close_Device;
function Create_Context
(Device : in Device_t) return Context_t is
begin
return Context_t (ALC_Thin.Create_Context
(Device => Device.Device_Data,
Attribute_List => System.Null_Address));
end Create_Context;
function Make_Context_Current
(Context : in Context_t) return Boolean is
begin
return Boolean (ALC_Thin.Make_Context_Current (ALC_Thin.Context_t (Context)));
end Make_Context_Current;
procedure Process_Context
(Context : in Context_t) is
begin
ALC_Thin.Process_Context (ALC_Thin.Context_t (Context));
end Process_Context;
procedure Suspend_Context
(Context : in Context_t) is
begin
ALC_Thin.Suspend_Context (ALC_Thin.Context_t (Context));
end Suspend_Context;
procedure Destroy_Context
(Context : in Context_t) is
begin
ALC_Thin.Destroy_Context (ALC_Thin.Context_t (Context));
end Destroy_Context;
function Get_Current_Context return Context_t is
begin
return Context_t (ALC_Thin.Get_Current_Context);
end Get_Current_Context;
function Get_Context_Device (Context : in Context_t) return Device_t is
Device : Device_t;
begin
Device.Device_Data := ALC_Thin.Get_Contexts_Device (ALC_Thin.Context_t (Context));
return Device;
end Get_Context_Device;
function Is_Extension_Present
(Device : in Device_t;
Name : in String) return Boolean
is
C_Name : aliased C.char_array := C.To_C (Name);
begin
return Boolean (ALC_Thin.Is_Extension_Present
(Device => Device.Device_Data,
Extension_Name => C_Name (C_Name'First)'Address));
end Is_Extension_Present;
--
-- String queries
--
function Get_String
(Device : ALC_Thin.Device_t;
Parameter : ALC_Thin.Enumeration_t) return C_Strings.chars_ptr;
pragma Import (C, Get_String, "alcGetString");
use type ALC_Thin.Device_t;
Null_Device : constant ALC_Thin.Device_t := ALC_Thin.Device_t (System.Null_Address);
function Get_Default_Device_Specifier return String is
begin
return C_Strings.Value
(Get_String
(Device => Null_Device,
Parameter => ALC_Thin.ALC_DEFAULT_DEVICE_SPECIFIER));
end Get_Default_Device_Specifier;
function Get_Device_Specifier
(Device : in Device_t) return String is
begin
if Device.Device_Data = Null_Device then
raise Ada.IO_Exceptions.Device_Error with "invalid device";
end if;
return C_Strings.Value
(Get_String
(Device => Device.Device_Data,
Parameter => ALC_Thin.ALC_DEVICE_SPECIFIER));
end Get_Device_Specifier;
function Get_Extensions
(Device : in Device_t) return String is
begin
if Device.Device_Data = Null_Device then
raise Ada.IO_Exceptions.Device_Error with "invalid device";
end if;
return C_Strings.Value
(Get_String
(Device => Device.Device_Data,
Parameter => ALC_Thin.ALC_EXTENSIONS));
end Get_Extensions;
function Get_Default_Capture_Device_Specifier return String is
begin
return C_Strings.Value
(Get_String
(Device => Null_Device,
Parameter => ALC_Thin.ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER));
end Get_Default_Capture_Device_Specifier;
function Get_Available_Capture_Devices return OpenAL.List.String_Vector_t is
Address : System.Address;
List : OpenAL.List.String_Vector_t;
begin
Address := ALC_Thin.Get_String
(Device => ALC_Thin.Device_t (System.Null_Address),
Token => ALC_Thin.ALC_CAPTURE_DEVICE_SPECIFIER);
OpenAL.List.Address_To_Vector
(Address => Address,
List => List);
return List;
end Get_Available_Capture_Devices;
--
-- Integer queries
--
function Get_Major_Version
(Device : in Device_t) return Natural
is
Value : aliased Natural := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_MAJOR_VERSION,
Size => ALC_Thin.Size_t (Natural'Size / System.Storage_Unit),
Data => Value'Address);
return Value;
end Get_Major_Version;
function Get_Minor_Version
(Device : in Device_t) return Natural
is
Value : aliased Natural := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_MINOR_VERSION,
Size => ALC_Thin.Size_t (Natural'Size / System.Storage_Unit),
Data => Value'Address);
return Value;
end Get_Minor_Version;
function Get_Capture_Samples
(Device : in Device_t) return Natural
is
Value : aliased Natural := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_CAPTURE_SAMPLES,
Size => ALC_Thin.Size_t (Natural'Size / System.Storage_Unit),
Data => Value'Address);
return Value;
end Get_Capture_Samples;
function Get_Frequency
(Device : in Device_t) return Types.Frequency_t
is
Value : aliased Types.Frequency_t := Types.Frequency_t'First;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_FREQUENCY,
Size => ALC_Thin.Size_t (Types.Frequency_t'Size / System.Storage_Unit),
Data => Value'Address);
return Value;
end Get_Frequency;
function Get_Refresh
(Device : in Device_t) return Natural
is
Value : aliased Natural := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_REFRESH,
Size => ALC_Thin.Size_t (Natural'Size / System.Storage_Unit),
Data => Value'Address);
return Value;
end Get_Refresh;
function Get_Synchronous
(Device : in Device_t) return Boolean
is
Value : aliased Natural := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_SYNC,
Size => ALC_Thin.Size_t (Natural'Size / System.Storage_Unit),
Data => Value'Address);
return Boolean'Val (Value);
end Get_Synchronous;
function Get_Mono_Sources
(Device : in Device_t) return Natural
is
Value : aliased Natural := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_MONO_SOURCES,
Size => ALC_Thin.Size_t (Natural'Size / System.Storage_Unit),
Data => Value'Address);
return Value;
end Get_Mono_Sources;
function Get_Stereo_Sources
(Device : in Device_t) return Natural
is
Value : aliased Natural := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_STEREO_SOURCES,
Size => ALC_Thin.Size_t (Natural'Size / System.Storage_Unit),
Data => Value'Address);
return Value;
end Get_Stereo_Sources;
end OpenAL.Context;
|
with Ada.IO_Exceptions;
with Interfaces.C.Strings;
with Interfaces.C;
with OpenAL.Thin;
with System;
package body OpenAL.Context is
package C renames Interfaces.C;
package C_Strings renames Interfaces.C.Strings;
function Open_Device
(Specifier : in String) return Device_t
is
C_Spec : aliased C.char_array := C.To_C (Specifier);
Device : Device_t;
begin
Device.Device_Data := ALC_Thin.Open_Device
(Specifier => C_Spec (C_Spec'First)'Address);
return Device;
end Open_Device;
function Open_Default_Device return Device_t is
Device : Device_t;
begin
Device.Device_Data := ALC_Thin.Open_Device
(Specifier => System.Null_Address);
return Device;
end Open_Default_Device;
function Close_Device
(Device : in Device_t) return Boolean is
begin
return Boolean (ALC_Thin.Close_Device (Device.Device_Data));
end Close_Device;
function Create_Context
(Device : in Device_t) return Context_t is
begin
return Context_t (ALC_Thin.Create_Context
(Device => Device.Device_Data,
Attribute_List => System.Null_Address));
end Create_Context;
function Make_Context_Current
(Context : in Context_t) return Boolean is
begin
return Boolean (ALC_Thin.Make_Context_Current (ALC_Thin.Context_t (Context)));
end Make_Context_Current;
procedure Process_Context
(Context : in Context_t) is
begin
ALC_Thin.Process_Context (ALC_Thin.Context_t (Context));
end Process_Context;
procedure Suspend_Context
(Context : in Context_t) is
begin
ALC_Thin.Suspend_Context (ALC_Thin.Context_t (Context));
end Suspend_Context;
procedure Destroy_Context
(Context : in Context_t) is
begin
ALC_Thin.Destroy_Context (ALC_Thin.Context_t (Context));
end Destroy_Context;
function Get_Current_Context return Context_t is
begin
return Context_t (ALC_Thin.Get_Current_Context);
end Get_Current_Context;
function Get_Context_Device (Context : in Context_t) return Device_t is
Device : Device_t;
begin
Device.Device_Data := ALC_Thin.Get_Contexts_Device (ALC_Thin.Context_t (Context));
return Device;
end Get_Context_Device;
function Is_Extension_Present
(Device : in Device_t;
Name : in String) return Boolean
is
C_Name : aliased C.char_array := C.To_C (Name);
begin
return Boolean (ALC_Thin.Is_Extension_Present
(Device => Device.Device_Data,
Extension_Name => C_Name (C_Name'First)'Address));
end Is_Extension_Present;
--
-- String queries
--
function Get_String
(Device : ALC_Thin.Device_t;
Parameter : ALC_Thin.Enumeration_t) return C_Strings.chars_ptr;
pragma Import (C, Get_String, "alcGetString");
use type ALC_Thin.Device_t;
Null_Device : constant ALC_Thin.Device_t := ALC_Thin.Device_t (System.Null_Address);
function Get_Default_Device_Specifier return String is
begin
return C_Strings.Value
(Get_String
(Device => Null_Device,
Parameter => ALC_Thin.ALC_DEFAULT_DEVICE_SPECIFIER));
end Get_Default_Device_Specifier;
function Get_Device_Specifier
(Device : in Device_t) return String is
begin
if Device.Device_Data = Null_Device then
raise Ada.IO_Exceptions.Device_Error with "invalid device";
end if;
return C_Strings.Value
(Get_String
(Device => Device.Device_Data,
Parameter => ALC_Thin.ALC_DEVICE_SPECIFIER));
end Get_Device_Specifier;
function Get_Extensions
(Device : in Device_t) return String is
begin
if Device.Device_Data = Null_Device then
raise Ada.IO_Exceptions.Device_Error with "invalid device";
end if;
return C_Strings.Value
(Get_String
(Device => Device.Device_Data,
Parameter => ALC_Thin.ALC_EXTENSIONS));
end Get_Extensions;
function Get_Default_Capture_Device_Specifier return String is
begin
return C_Strings.Value
(Get_String
(Device => Null_Device,
Parameter => ALC_Thin.ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER));
end Get_Default_Capture_Device_Specifier;
function Get_Available_Capture_Devices return OpenAL.List.String_Vector_t is
Address : System.Address;
List : OpenAL.List.String_Vector_t;
begin
Address := ALC_Thin.Get_String
(Device => ALC_Thin.Device_t (System.Null_Address),
Token => ALC_Thin.ALC_CAPTURE_DEVICE_SPECIFIER);
OpenAL.List.Address_To_Vector
(Address => Address,
List => List);
return List;
end Get_Available_Capture_Devices;
--
-- Integer queries
--
function Get_Major_Version
(Device : in Device_t) return Natural
is
Value : aliased Thin.Integer_t := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_MAJOR_VERSION,
Size => 1,
Data => Value'Address);
return Natural (Value);
end Get_Major_Version;
function Get_Minor_Version
(Device : in Device_t) return Natural
is
Value : aliased Thin.Integer_t := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_MINOR_VERSION,
Size => 1,
Data => Value'Address);
return Natural (Value);
end Get_Minor_Version;
function Get_Capture_Samples
(Device : in Device_t) return Natural
is
Value : aliased Thin.Integer_t := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_CAPTURE_SAMPLES,
Size => 1,
Data => Value'Address);
return Natural (Value);
end Get_Capture_Samples;
function Get_Frequency
(Device : in Device_t) return Types.Frequency_t
is
Value : aliased Thin.Integer_t := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_FREQUENCY,
Size => 1,
Data => Value'Address);
return Types.Frequency_t (Value);
end Get_Frequency;
function Get_Refresh
(Device : in Device_t) return Natural
is
Value : aliased Thin.Integer_t := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_REFRESH,
Size => 1,
Data => Value'Address);
return Natural (Value);
end Get_Refresh;
function Get_Synchronous
(Device : in Device_t) return Boolean
is
Value : aliased Thin.Integer_t := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_SYNC,
Size => 1,
Data => Value'Address);
return Boolean'Val (Value);
end Get_Synchronous;
function Get_Mono_Sources
(Device : in Device_t) return Natural
is
Value : aliased Thin.Integer_t := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_MONO_SOURCES,
Size => 1,
Data => Value'Address);
return Natural (Value);
end Get_Mono_Sources;
function Get_Stereo_Sources
(Device : in Device_t) return Natural
is
Value : aliased Thin.Integer_t := 0;
begin
ALC_Thin.Get_Integerv
(Device => Device.Device_Data,
Token => ALC_Thin.ALC_STEREO_SOURCES,
Size => 1,
Data => Value'Address);
return Natural (Value);
end Get_Stereo_Sources;
end OpenAL.Context;
|
Adjust how getIntegerv is called (do not use sizes)
|
Adjust how getIntegerv is called (do not use sizes)
|
Ada
|
isc
|
io7m/coreland-openal-ada,io7m/coreland-openal-ada
|
53d3a70fda3b6f6e09795f234310223fb4e2a356
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
-----------------------------------------------------------------------
-- 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 AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Users.Models;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with Ada.Calendar;
with ADO.Sessions;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.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);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
Ctx : constant Services.Contexts.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);
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Ctx.Start;
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Page.Save (DB);
Ctx.Commit;
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
-- ------------------------------
-- Create a new wiki content for the wiki page.
-- ------------------------------
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : AWA.Users.Models.User_Ref := Ctx.Get_User;
begin
-- Check that the user has the create wiki content permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Content.Set_Page (Page);
Content.Set_Create_Date (Ada.Calendar.Clock);
Content.Set_Author (User);
Content.Save (DB);
Page.Set_Content (Content);
Page.Set_Last_Version (Page.Get_Last_Version + 1);
Page.Save (DB);
Ctx.Commit;
end Create_Wiki_Content;
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 AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Users.Models;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with Ada.Calendar;
with ADO.Sessions;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.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);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Set_Create_Date (Ada.Calendar.Clock);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
Ctx : constant Services.Contexts.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);
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Ctx.Start;
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Page.Save (DB);
Ctx.Commit;
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
-- ------------------------------
-- Create a new wiki content for the wiki page.
-- ------------------------------
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : AWA.Users.Models.User_Ref := Ctx.Get_User;
begin
-- Check that the user has the create wiki content permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Content.Set_Page (Page);
Content.Set_Create_Date (Ada.Calendar.Clock);
Content.Set_Author (User);
Content.Save (DB);
Page.Set_Content (Content);
Page.Set_Last_Version (Page.Get_Last_Version + 1);
Page.Save (DB);
Ctx.Commit;
end Create_Wiki_Content;
end AWA.Wikis.Modules;
|
Set the creation date on the wiki space
|
Set the creation date on the wiki space
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
69ea92c960af95c400b38874c22193465333f163
|
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
|
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
|
-----------------------------------------------------------------------
-- awa-storages-services-tests -- Unit tests for storage service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
with AWA.Storages.Beans.Factories;
with AWA.Tests.Helpers.Users;
package body AWA.Storages.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Storages.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save",
Test_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete",
Test_Delete_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean",
Test_Create_Folder'Access);
end Add_Tests;
-- ------------------------------
-- Save something in a storage element and keep track of the store id in the test <b>Id</b>.
-- ------------------------------
procedure Save (T : in out Test) is
Store : AWA.Storages.Models.Storage_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Save (Into => Store,
Path => "Makefile",
Storage => AWA.Storages.Models.DATABASE);
T.Assert (not Store.Is_Null, "Storage object should not be null");
T.Id := Store.Get_Id;
T.Assert (T.Id > 0, "Invalid storage identifier");
end Save;
-- ------------------------------
-- Load the storage element refered to by the test <b>Id</b>.
-- ------------------------------
procedure Load (T : in out Test) is
use type Ada.Streams.Stream_Element_Offset;
Data : ADO.Blob_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Load (From => T.Id, Into => Data);
T.Assert (not Data.Is_Null, "Null blob returned by load");
T.Assert (Data.Value.Len > 100, "Invalid length for the blob data");
end Load;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Load;
end Test_Create_Storage;
-- ------------------------------
-- Test deletion of a storage object
-- ------------------------------
procedure Test_Delete_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Data : ADO.Blob_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Manager.Delete (T.Id);
T.Manager.Load (From => T.Id, Into => Data);
T.Assert (Data.Is_Null, "A non null blob returned by load");
end Test_Delete_Storage;
-- ------------------------------
-- Test creation of a storage folder
-- ------------------------------
procedure Test_Create_Folder (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Folder : AWA.Storages.Beans.Factories.Folder_Bean;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Folder.Set_Name ("Test folder name");
Folder.Module := AWA.Storages.Modules.Get_Storage_Module;
Folder.Save (Outcome);
Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action");
end Test_Create_Folder;
end AWA.Storages.Services.Tests;
|
-----------------------------------------------------------------------
-- awa-storages-services-tests -- Unit tests for storage service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
with AWA.Storages.Beans.Factories;
with AWA.Tests.Helpers.Users;
package body AWA.Storages.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Storages.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save",
Test_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete",
Test_Delete_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean",
Test_Create_Folder'Access);
end Add_Tests;
-- ------------------------------
-- Save something in a storage element and keep track of the store id in the test <b>Id</b>.
-- ------------------------------
procedure Save (T : in out Test) is
Store : AWA.Storages.Models.Storage_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Save (Into => Store,
Path => "Makefile",
Storage => AWA.Storages.Models.DATABASE);
T.Assert (not Store.Is_Null, "Storage object should not be null");
T.Id := Store.Get_Id;
T.Assert (T.Id > 0, "Invalid storage identifier");
end Save;
-- ------------------------------
-- Load the storage element refered to by the test <b>Id</b>.
-- ------------------------------
procedure Load (T : in out Test) is
use type Ada.Streams.Stream_Element_Offset;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
Data : ADO.Blob_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Load (From => T.Id, Mime => Mime, Date => Date, Into => Data);
T.Assert (not Data.Is_Null, "Null blob returned by load");
T.Assert (Data.Value.Len > 100, "Invalid length for the blob data");
end Load;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Load;
end Test_Create_Storage;
-- ------------------------------
-- Test deletion of a storage object
-- ------------------------------
procedure Test_Delete_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Data : ADO.Blob_Ref;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Manager.Delete (T.Id);
T.Manager.Load (From => T.Id, Mime => Mime, Date => Date, Into => Data);
T.Assert (Data.Is_Null, "A non null blob returned by load");
end Test_Delete_Storage;
-- ------------------------------
-- Test creation of a storage folder
-- ------------------------------
procedure Test_Create_Folder (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Folder : AWA.Storages.Beans.Factories.Folder_Bean;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Folder.Set_Name ("Test folder name");
Folder.Module := AWA.Storages.Modules.Get_Storage_Module;
Folder.Save (Outcome);
Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action");
end Test_Create_Folder;
end AWA.Storages.Services.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d0f7167ddb6146cb48dd9f3dc5c66b84ae3e8a79
|
awa/src/awa-users-servlets.adb
|
awa/src/awa-users-servlets.adb
|
-----------------------------------------------------------------------
-- awa-users-servlets -- OpenID verification servlet for user authentication
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Beans.Objects.Records;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Servlets;
with AWA.Users.Services;
with AWA.Users.Modules;
with AWA.Users.Filters;
with AWA.Users.Principals;
package body AWA.Users.Servlets is
-- Name of the session attribute which holds the URI to redirect after authentication.
REDIRECT_ATTRIBUTE : constant String := "awa-redirect";
-- Name of the request attribute that contains the URI to redirect after authentication.
REDIRECT_PARAM : constant String := "redirect";
-- Name of the session attribute which holds information about the active authentication.
OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc";
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Servlets");
-- Make a package to store the Association in the session.
package Association_Bean is new Util.Beans.Objects.Records (Security.Auth.Association);
subtype Association_Access is Association_Bean.Element_Type_Access;
function Get_Provider_URL (Server : in Request_Auth_Servlet;
Request : in ASF.Requests.Request'Class) return String;
function Get_Provider_URL (Server : in Request_Auth_Servlet;
Request : in ASF.Requests.Request'Class) return String is
pragma Unreferenced (Server);
URI : constant String := Request.Get_Path_Info;
begin
if URI'Length = 0 then
return "";
end if;
Log.Info ("OpenID authentication with {0}", URI);
return URI (URI'First + 1 .. URI'Last);
end Get_Provider_URL;
-- ------------------------------
-- Proceed to the OpenID authentication with an OpenID provider.
-- Find the OpenID provider URL and starts the discovery, association phases
-- during which a private key is obtained from the OpenID provider.
-- After OpenID discovery and association, the user will be redirected to
-- the OpenID provider.
-- ------------------------------
overriding
procedure Do_Get (Server : in Request_Auth_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
Name : constant String := Get_Provider_URL (Server, Request);
URL : constant String := Ctx.Get_Init_Parameter ("auth.url." & Name);
begin
Log.Info ("GET: request OpenId authentication to {0} - {1}", Name, URL);
if Name'Length = 0 or URL'Length = 0 then
Response.Set_Status (ASF.Responses.SC_NOT_FOUND);
return;
end if;
declare
Mgr : Security.Auth.Manager;
OP : Security.Auth.End_Point;
Bean : constant Util.Beans.Objects.Object := Association_Bean.Create;
Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean);
Redirect : constant String := Request.Get_Parameter (REDIRECT_PARAM);
begin
Server.Initialize (Name, Mgr);
-- Yadis discovery (get the XRDS file). This step does nothing for OAuth.
Mgr.Discover (URL, OP);
-- Associate to the OpenID provider and get an end-point with a key.
Mgr.Associate (OP, Assoc.all);
-- Save the association in the HTTP session and
-- redirect the user to the OpenID provider.
declare
Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
Session : ASF.Sessions.Session := Request.Get_Session (Create => True);
begin
Log.Info ("Redirect to auth URL: {0}", Auth_URL);
Response.Send_Redirect (Location => Auth_URL);
Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE,
Value => Bean);
if Redirect'Length > 0 then
Session.Set_Attribute (Name => REDIRECT_ATTRIBUTE,
Value => Util.Beans.Objects.To_Object (Redirect));
end if;
end;
end;
end Do_Get;
-- ------------------------------
-- Create a principal object that correspond to the authenticated user identified
-- by the <b>Auth</b> information. The principal will be attached to the session
-- and will be destroyed when the session is closed.
-- ------------------------------
overriding
procedure Create_Principal (Server : in Verify_Auth_Servlet;
Auth : in Security.Auth.Authentication;
Result : out ASF.Principals.Principal_Access) is
pragma Unreferenced (Server);
use AWA.Users.Modules;
use AWA.Users.Services;
Manager : constant User_Service_Access := AWA.Users.Modules.Get_User_Manager;
Principal : AWA.Users.Principals.Principal_Access;
begin
Manager.Authenticate (Auth => Auth,
IpAddr => "",
Principal => Principal);
Result := Principal.all'Access;
end Create_Principal;
-- ------------------------------
-- Get the redirection URL that must be used after the authentication succeeded.
-- ------------------------------
function Get_Redirect_URL (Server : in Verify_Auth_Servlet;
Session : in ASF.Sessions.Session'Class;
Request : in ASF.Requests.Request'Class) return String is
Redir : constant Util.Beans.Objects.Object := Session.Get_Attribute (REDIRECT_ATTRIBUTE);
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
if not Util.Beans.Objects.Is_Null (Redir) then
return Util.Beans.Objects.To_String (Redir);
end if;
declare
Cookies : constant ASF.Cookies.Cookie_Array := Request.Get_Cookies;
begin
for I in Cookies'Range loop
if ASF.Cookies.Get_Name (Cookies (I)) = AWA.Users.Filters.REDIRECT_COOKIE then
return ASF.Cookies.Get_Value (Cookies (I));
end if;
end loop;
end;
return Ctx.Get_Init_Parameter ("openid.success_url");
end Get_Redirect_URL;
-- ------------------------------
-- Verify the authentication result that was returned by the OpenID provider.
-- If the authentication succeeded and the signature was correct, sets a
-- user principals on the session.
-- ------------------------------
procedure Do_Get (Server : in Verify_Auth_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
use type Security.Auth.Auth_Result;
type Auth_Params is new Security.Auth.Parameters with null record;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String is
pragma Unreferenced (Params);
begin
return Request.Get_Parameter (Name);
end Get_Parameter;
Session : ASF.Sessions.Session := Request.Get_Session (Create => False);
Bean : Util.Beans.Objects.Object;
Mgr : Security.Auth.Manager;
Assoc : Association_Access;
Credential : Security.Auth.Authentication;
Params : Auth_Params;
begin
Log.Info ("GET: verify openid authentication");
if not Session.Is_Valid then
Log.Warn ("Session has expired during OpenID authentication process");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Bean := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE);
-- Cleanup the session and drop the association end point.
Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE);
if Util.Beans.Objects.Is_Null (Bean) then
Log.Warn ("Verify openid request without active session");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Assoc := Association_Bean.To_Element_Access (Bean);
Server.Initialize (Security.Auth.Get_Provider (Assoc.all), Mgr);
-- Verify that what we receive through the callback matches the association key.
Mgr.Verify (Assoc.all, Params, Credential);
if Security.Auth.Get_Status (Credential) /= Security.Auth.AUTHENTICATED then
Log.Info ("Authentication has failed");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Log.Info ("Authentication succeeded for {0}", Security.Auth.Get_Email (Credential));
-- Get a user principal and set it on the session.
declare
User : ASF.Principals.Principal_Access;
Redirect : constant String
:= Verify_Auth_Servlet'Class (Server).Get_Redirect_URL (Session, Request);
begin
Verify_Auth_Servlet'Class (Server).Create_Principal (Credential, User);
Session.Set_Principal (User);
Session.Remove_Attribute (REDIRECT_ATTRIBUTE);
Log.Info ("Redirect user to URL: {0}", Redirect);
Response.Send_Redirect (Redirect);
end;
end Do_Get;
end AWA.Users.Servlets;
|
-----------------------------------------------------------------------
-- awa-users-servlets -- OpenID verification servlet for user authentication
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Beans.Objects.Records;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Servlets;
with AWA.Users.Services;
with AWA.Users.Modules;
with AWA.Users.Filters;
with AWA.Users.Principals;
package body AWA.Users.Servlets is
-- Name of the session attribute which holds the URI to redirect after authentication.
REDIRECT_ATTRIBUTE : constant String := "awa-redirect";
-- Name of the request attribute that contains the URI to redirect after authentication.
REDIRECT_PARAM : constant String := "redirect";
-- Name of the session attribute which holds information about the active authentication.
OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc";
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Servlets");
-- Make a package to store the Association in the session.
package Association_Bean is new Util.Beans.Objects.Records (Security.Auth.Association);
subtype Association_Access is Association_Bean.Element_Type_Access;
function Get_Provider_URL (Server : in Request_Auth_Servlet;
Request : in ASF.Requests.Request'Class) return String;
function Get_Provider_URL (Server : in Request_Auth_Servlet;
Request : in ASF.Requests.Request'Class) return String is
pragma Unreferenced (Server);
URI : constant String := Request.Get_Path_Info;
begin
if URI'Length = 0 then
return "";
end if;
Log.Info ("OpenID authentication with {0}", URI);
return URI (URI'First + 1 .. URI'Last);
end Get_Provider_URL;
-- ------------------------------
-- Proceed to the OpenID authentication with an OpenID provider.
-- Find the OpenID provider URL and starts the discovery, association phases
-- during which a private key is obtained from the OpenID provider.
-- After OpenID discovery and association, the user will be redirected to
-- the OpenID provider.
-- ------------------------------
overriding
procedure Do_Get (Server : in Request_Auth_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
Name : constant String := Get_Provider_URL (Server, Request);
URL : constant String := Ctx.Get_Init_Parameter ("auth.url." & Name);
begin
Log.Info ("GET: request OpenId authentication to {0} - {1}", Name, URL);
if Name'Length = 0 or URL'Length = 0 then
Response.Set_Status (ASF.Responses.SC_NOT_FOUND);
return;
end if;
declare
Mgr : Security.Auth.Manager;
OP : Security.Auth.End_Point;
Bean : constant Util.Beans.Objects.Object := Association_Bean.Create;
Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean);
Redirect : constant String := Request.Get_Parameter (REDIRECT_PARAM);
begin
Server.Initialize (Name, Mgr);
-- Yadis discovery (get the XRDS file). This step does nothing for OAuth.
Mgr.Discover (URL, OP);
-- Associate to the OpenID provider and get an end-point with a key.
Mgr.Associate (OP, Assoc.all);
-- Save the association in the HTTP session and
-- redirect the user to the OpenID provider.
declare
Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
Session : ASF.Sessions.Session := Request.Get_Session (Create => True);
begin
Log.Info ("Redirect to auth URL: {0}", Auth_URL);
Response.Send_Redirect (Location => Auth_URL);
Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE,
Value => Bean);
if Redirect'Length > 0 then
Session.Set_Attribute (Name => REDIRECT_ATTRIBUTE,
Value => Util.Beans.Objects.To_Object (Redirect));
end if;
end;
end;
end Do_Get;
-- ------------------------------
-- Create a principal object that correspond to the authenticated user identified
-- by the <b>Auth</b> information. The principal will be attached to the session
-- and will be destroyed when the session is closed.
-- ------------------------------
overriding
procedure Create_Principal (Server : in Verify_Auth_Servlet;
Auth : in Security.Auth.Authentication;
Result : out ASF.Principals.Principal_Access) is
pragma Unreferenced (Server);
use AWA.Users.Services;
Manager : constant User_Service_Access := AWA.Users.Modules.Get_User_Manager;
Principal : AWA.Users.Principals.Principal_Access;
begin
Manager.Authenticate (Auth => Auth,
IpAddr => "",
Principal => Principal);
Result := Principal.all'Access;
end Create_Principal;
-- ------------------------------
-- Get the redirection URL that must be used after the authentication succeeded.
-- ------------------------------
function Get_Redirect_URL (Server : in Verify_Auth_Servlet;
Session : in ASF.Sessions.Session'Class;
Request : in ASF.Requests.Request'Class) return String is
Redir : constant Util.Beans.Objects.Object := Session.Get_Attribute (REDIRECT_ATTRIBUTE);
Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
if not Util.Beans.Objects.Is_Null (Redir) then
return Util.Beans.Objects.To_String (Redir);
end if;
declare
Cookies : constant ASF.Cookies.Cookie_Array := Request.Get_Cookies;
begin
for I in Cookies'Range loop
if ASF.Cookies.Get_Name (Cookies (I)) = AWA.Users.Filters.REDIRECT_COOKIE then
return ASF.Cookies.Get_Value (Cookies (I));
end if;
end loop;
end;
return Ctx.Get_Init_Parameter ("openid.success_url");
end Get_Redirect_URL;
-- ------------------------------
-- Verify the authentication result that was returned by the OpenID provider.
-- If the authentication succeeded and the signature was correct, sets a
-- user principals on the session.
-- ------------------------------
procedure Do_Get (Server : in Verify_Auth_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
use type Security.Auth.Auth_Result;
type Auth_Params is new Security.Auth.Parameters with null record;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String is
pragma Unreferenced (Params);
begin
return Request.Get_Parameter (Name);
end Get_Parameter;
Session : ASF.Sessions.Session := Request.Get_Session (Create => False);
Bean : Util.Beans.Objects.Object;
Mgr : Security.Auth.Manager;
Assoc : Association_Access;
Credential : Security.Auth.Authentication;
Params : Auth_Params;
begin
Log.Info ("GET: verify openid authentication");
if not Session.Is_Valid then
Log.Warn ("Session has expired during OpenID authentication process");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Bean := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE);
-- Cleanup the session and drop the association end point.
Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE);
if Util.Beans.Objects.Is_Null (Bean) then
Log.Warn ("Verify openid request without active session");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Assoc := Association_Bean.To_Element_Access (Bean);
Server.Initialize (Security.Auth.Get_Provider (Assoc.all), Mgr);
-- Verify that what we receive through the callback matches the association key.
Mgr.Verify (Assoc.all, Params, Credential);
if Security.Auth.Get_Status (Credential) /= Security.Auth.AUTHENTICATED then
Log.Info ("Authentication has failed");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
return;
end if;
Log.Info ("Authentication succeeded for {0}", Security.Auth.Get_Email (Credential));
-- Get a user principal and set it on the session.
declare
User : ASF.Principals.Principal_Access;
Redirect : constant String
:= Verify_Auth_Servlet'Class (Server).Get_Redirect_URL (Session, Request);
begin
Verify_Auth_Servlet'Class (Server).Create_Principal (Credential, User);
Session.Set_Principal (User);
Session.Remove_Attribute (REDIRECT_ATTRIBUTE);
Log.Info ("Redirect user to URL: {0}", Redirect);
Response.Send_Redirect (Redirect);
end;
end Do_Get;
end AWA.Users.Servlets;
|
Remove unused use clause to fix compilation warning
|
Remove unused use clause to fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
9c5b4029664eb941117a10804a6384cbc91d94f6
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2017, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Storages.Models;
with ADO.Objects;
with ADO.Sessions;
with ADO.Statements;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Stat_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Format_List_Bean",
Handler => AWA.Blogs.Beans.Create_Format_List_Bean'Access);
App.Add_Servlet ("blog-image", Plugin.Image_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX);
begin
Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix));
end Configure;
-- ------------------------------
-- 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;
-- ------------------------------
-- Get the image prefix that was configured for the Blog module.
-- ------------------------------
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString is
begin
return Module.Image_Prefix;
end Get_Image_Prefix;
procedure Publish_Post (Module : in Blog_Module;
Post : in AWA.Blogs.Models.Post_Ref) is
Current_Entity : aliased AWA.Blogs.Models.Post_Ref := Post;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access
:= Current_Entity'Unchecked_Access;
Bean : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC);
Event : AWA.Events.Module_Event;
begin
Event.Set_Event_Kind (Post_Publish_Event.Kind);
Event.Set_Parameter ("summary", Post.Get_Summary);
Event.Set_Parameter ("title", Post.Get_Title);
Event.Set_Parameter ("uri", Post.Get_Uri);
Event.Set_Parameter ("post", Bean);
Event.Set_Parameter ("author", Post.Get_Author.Get_Name);
Module.Send_Event (Event);
end Publish_Post;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Workspaces.Modules.Add_Permission (Session => DB,
User => User,
Entity => Blog,
Workspace => WS.Get_Id,
List => (ACL_Delete_Blog.Permission,
ACL_Update_Post.Permission,
ACL_Create_Post.Permission,
ACL_Delete_Post.Permission));
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Summary : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
use type AWA.Blogs.Models.Post_Status_Type;
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_Summary (Summary);
Post.Set_Create_Date (Ada.Calendar.Clock);
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
-- The post is published, post an event to trigger specific actions.
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Publish_Post (Model, Post);
end if;
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;
Summary : in String;
URI : in String;
Text : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
Published : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if not Publish_Date.Is_Null then
Post.Set_Publish_Date (Publish_Date);
end if;
Published := Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null;
if Published then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Summary (Summary);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
-- The post is published, post an event to trigger specific actions.
if Published then
Publish_Post (Model, Post);
end if;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
-- ------------------------------
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
-- ------------------------------
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Model);
use type AWA.Storages.Models.Storage_Type;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement;
Kind : AWA.Storages.Models.Storage_Type;
begin
if Width = Natural'Last or Height = Natural'Last then
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
elsif Width > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data);
Query.Bind_Param ("width", Width);
elsif Height > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data);
Query.Bind_Param ("height", Height);
else
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
end if;
Query.Bind_Param ("post_id", Post_Id);
Query.Bind_Param ("store_id", Image_Id);
Query.Bind_Param ("user_id", User);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Width := Query.Get_Natural (4);
Height := Query.Get_Natural (5);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (6);
else
null;
end if;
end Load_Image;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2017, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Storages.Models;
with ADO.Objects;
with ADO.Sessions;
with ADO.Statements;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
procedure Publish_Post (Module : in Blog_Module;
Post : in AWA.Blogs.Models.Post_Ref);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Stat_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Format_List_Bean",
Handler => AWA.Blogs.Beans.Create_Format_List_Bean'Access);
App.Add_Servlet ("blog-image", Plugin.Image_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX);
begin
Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix));
end Configure;
-- ------------------------------
-- 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;
-- ------------------------------
-- Get the image prefix that was configured for the Blog module.
-- ------------------------------
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString is
begin
return Module.Image_Prefix;
end Get_Image_Prefix;
procedure Publish_Post (Module : in Blog_Module;
Post : in AWA.Blogs.Models.Post_Ref) is
Current_Entity : aliased AWA.Blogs.Models.Post_Ref := Post;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access
:= Current_Entity'Unchecked_Access;
Bean : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC);
Event : AWA.Events.Module_Event;
begin
Event.Set_Event_Kind (Post_Publish_Event.Kind);
Event.Set_Parameter ("summary", Post.Get_Summary);
Event.Set_Parameter ("title", Post.Get_Title);
Event.Set_Parameter ("uri", Post.Get_Uri);
Event.Set_Parameter ("post", Bean);
Event.Set_Parameter ("author", Post.Get_Author.Get_Name);
Module.Send_Event (Event);
end Publish_Post;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Workspaces.Modules.Add_Permission (Session => DB,
User => User,
Entity => Blog,
Workspace => WS.Get_Id,
List => (ACL_Delete_Blog.Permission,
ACL_Update_Post.Permission,
ACL_Create_Post.Permission,
ACL_Delete_Post.Permission));
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Summary : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
use type AWA.Blogs.Models.Post_Status_Type;
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_Summary (Summary);
Post.Set_Create_Date (Ada.Calendar.Clock);
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
-- The post is published, post an event to trigger specific actions.
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Publish_Post (Model, Post);
end if;
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;
Summary : in String;
URI : in String;
Text : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type) is
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
Published : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if not Publish_Date.Is_Null then
Post.Set_Publish_Date (Publish_Date);
end if;
Published := Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null;
if Published then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Summary (Summary);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
-- The post is published, post an event to trigger specific actions.
if Published then
Publish_Post (Model, Post);
end if;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
-- ------------------------------
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
-- ------------------------------
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Model);
use type AWA.Storages.Models.Storage_Type;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement;
Kind : AWA.Storages.Models.Storage_Type;
begin
if Width = Natural'Last or Height = Natural'Last then
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
elsif Width > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data);
Query.Bind_Param ("width", Width);
elsif Height > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data);
Query.Bind_Param ("height", Height);
else
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
end if;
Query.Bind_Param ("post_id", Post_Id);
Query.Bind_Param ("store_id", Image_Id);
Query.Bind_Param ("user_id", User);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Width := Query.Get_Natural (4);
Height := Query.Get_Natural (5);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (6);
else
null;
end if;
end Load_Image;
end AWA.Blogs.Modules;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
2b9f8b6c79476c01d029026d8a0fee8a16b8cf75
|
regtests/util-files-tests.adb
|
regtests/util-files-tests.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File_Missing'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/os-none",
Compose_Path ("src;regtests", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
end Util.Files.Tests;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File_Missing'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/sys/processes/os-none",
Compose_Path ("src;regtests;src/sys/processes", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
end Util.Files.Tests;
|
Fix the unit test after files are moved to other directories
|
Fix the unit test after files are moved to other directories
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
55649663788dfda94a45f42abdb6817df4e680de
|
src/oto-alc.ads
|
src/oto-alc.ads
|
pragma License (Modified_GPL);
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: Modified GNU GPLv3 or any later as published by Free Software --
-- Foundation (GMGPL, see COPYING file). --
-- --
-- Copyright © 2014 darkestkhan --
------------------------------------------------------------------------------
-- This Program is Free Software: You can redistribute it and/or modify --
-- it under the terms of The GNU General Public License as published by --
-- the Free Software Foundation: either version 3 of the license, or --
-- (at your option) any later version. --
-- --
-- This Program is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
-- GNU General Public License for more details. --
-- --
-- You should have received a copy of the GNU General Public License --
-- along with this program. If not, see <http://www.gnu.org/licenses/>. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
------------------------------------------------------------------------------
with System;
with Oto.Binary;
use Oto;
package Oto.ALC is
---------------------------------------------------------------------------
---------------
-- T Y P E S --
---------------
---------------------------------------------------------------------------
-- Due to the fact that only pointers to device and context are passed
-- we ar going to use System.Address for them.
subtype Context is System.Address;
subtype Device is System.Address;
subtype Bool is Binary.Byte;
subtype Char is Binary.S_Byte;
subtype Double is Long_Float;
subtype Enum is Binary.S_Word;
subtype Int is Integer;
subtype Pointer is System.Address;
subtype Short is Binary.S_Short;
subtype SizeI is Integer;
subtype UByte is Binary.Byte;
subtype UInt is Binary.Word;
subtype UShort is Binary.Short;
---------------------------------------------------------------------------
-----------------------
-- C O N S T A N T S --
-----------------------
---------------------------------------------------------------------------
-- Bool constants.
ALC_FALSE : constant Bool := 0;
ALC_TRUE : constant Bool := 1;
-- Followed by <Int> Hz
ALC_FREQUENCY : constant Enum := 16#1007#;
-- Followed by <Int> Hz
ALC_REFRESH : constant Enum := 16#1008#;
-- Followed by AL_TRUE, AL_FALSE
ALC_SYNC : constant Enum := 16#1009#;
-- Followed by <Int> Num of requested Mono (3D) Sources
ALC_MONO_SOURCES : constant Enum := 16#1010#;
-- Followed by <Int> Num of requested Stereo Sources
ALC_STEREO_SOURCES : constant Enum := 16#1011#;
-- Errors
-- No error
ALC_NO_ERROR : constant Enum := 0;
-- No device
ALC_INVALID_DEVICE : constant Enum := 16#A001#;
-- Invalid context ID
ALC_INVALID_CONTEXT : constant Enum := 16#A002#;
-- Bad enum
ALC_INVALID_ENUM : constant Enum := 16#A003#;
-- Bad value
ALC_INVALID_VALUE : constant Enum := 16#A004#;
-- Out of memory.
ALC_OUT_OF_MEMORY : constant Enum := 16#A005#;
-- The Specifier string for default device
ALC_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#1004#;
ALC_DEVICE_SPECIFIER : constant Enum := 16#1005#;
ALC_EXTENSIONS : constant Enum := 16#1006#;
ALC_MAJOR_VERSION : constant Enum := 16#1000#;
ALC_MINOR_VERSION : constant Enum := 16#1001#;
ALC_ATTRIBUTES_SIZE : constant Enum := 16#1002#;
ALC_ALL_ATTRIBUTES : constant Enum := 16#1003#;
-- Capture extension
ALC_EXT_CAPTURE : constant Enum := 1;
ALC_CAPTURE_DEVICE_SPECIFIER : constant Enum := 16#310#;
ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#311#;
ALC_CAPTURE_SAMPLES : constant Enum := 16#312#;
-- ALC_ENUMERATE_ALL_EXT enums
ALC_ENUMERATE_ALL_EXT : constant Enum := 1;
ALC_DEFAULT_ALL_DEVICES_SPECIFIER : constant Enum := 16#1012#;
ALC_ALL_DEVICES_SPECIFIER : constant Enum := 16#1013#;
---------------------------------------------------------------------------
---------------------------
-- S U B P R O G R A M S --
---------------------------
---------------------------------------------------------------------------
-- Context Management
function Create_Context
( ADevice: in Device;
Attr_List: in Pointer
) return Context;
function Make_Context_Current (AContext: in Context) return Bool;
procedure Process_Context (AContext: in Context);
procedure Suspend_Context (AContext: in Context);
procedure Destroy_Context (AContext: in Context);
function Get_Current_Context return Context;
function Get_Contexts_Device (AContext: in Context) return Device;
-- Device Management
function Open_Device (Device_Name: in String) return Device;
Pragma Inline (Open_Device);
function Close_Device (ADevice: in Device) return Bool;
-- Error support.
-- Obtain the most recent Context error
function Get_Error (ADevice: in Device) return Enum;
-- Extension support.
-- Query for the presence of an extension, and obtain any appropriate
-- function pointers and enum values.
function Is_Extension_Present
( ADevice: in Device;
Ext_Name: in String
) return Bool;
Pragma Inline (Is_Extension_Present);
function Get_Proc_Address
( ADevice: in Device;
Func_Name: in String
) return Pointer;
Pragma Inline (Get_Proc_Address);
function Get_Enum_Value
( ADevice: in Device;
Enum_Name: in String
) return Enum;
Pragma Inline (Get_Enum_Value);
-- Query functions
function Get_String (ADevice: in Device; Param: in Enum) return String;
Pragma Inline (Get_String);
procedure Get_Integer
( ADevice: in Device;
Param: in Enum;
Size: in SizeI;
Data: in Pointer
);
-- Capture functions
function Capture_Open_Device
( Device_Name: in String;
Frequency: in UInt;
Format: in Enum;
Buffer_Size: in SizeI
) return Device;
Pragma Inline (Capture_Open_Device);
function Capture_Close_Device (ADevice: in Device) return Bool;
procedure Capture_Start (ADevice: in Device);
procedure Capture_Stop (ADevice: in Device);
procedure Capture_Samples
( ADevice: in Device;
Buffer: in Pointer;
Samples: in SizeI
);
---------------------------------------------------------------------------
private
---------------------------------------------------------------------------
-------------------
-- I M P O R T S --
-------------------
---------------------------------------------------------------------------
Pragma Import (StdCall, Create_Context, "alcCreateContext");
Pragma Import (StdCall, Make_Context_Current, "alcMakeContextCurrent");
Pragma Import (StdCall, Process_Context, "alcProcessContext");
Pragma Import (StdCall, Suspend_Context, "alcSuspendContext");
Pragma Import (StdCall, Destroy_Context, "alcDestroyContext");
Pragma Import (StdCall, Get_Current_Context, "alcGetCurrentContext");
Pragma Import (StdCall, Get_Contexts_Device, "alcGetContextsDevice");
Pragma Import (StdCall, Close_Device, "alcCloseDevice");
Pragma Import (StdCall, Get_Error, "alcGetError");
Pragma Import (StdCall, Get_Integer, "alcGetIntegerv");
Pragma Import (StdCall, Capture_Close_Device, "alcCaptureCloseDevice");
Pragma Import (StdCall, Capture_Start, "alcCaptureStart");
Pragma Import (StdCall, Capture_Stop, "alcCaptureStop");
Pragma Import (StdCall, Capture_Samples, "alcCaptureSamples");
---------------------------------------------------------------------------
end Oto.ALC;
|
pragma License (Modified_GPL);
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: Modified GNU GPLv3 or any later as published by Free Software --
-- Foundation (GMGPL, see COPYING file). --
-- --
-- Copyright © 2014 darkestkhan --
------------------------------------------------------------------------------
-- This Program is Free Software: You can redistribute it and/or modify --
-- it under the terms of The GNU General Public License as published by --
-- the Free Software Foundation: either version 3 of the license, or --
-- (at your option) any later version. --
-- --
-- This Program is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
-- GNU General Public License for more details. --
-- --
-- You should have received a copy of the GNU General Public License --
-- along with this program. If not, see <http://www.gnu.org/licenses/>. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
------------------------------------------------------------------------------
with System;
with Oto.Binary;
use Oto;
package Oto.ALC is
---------------------------------------------------------------------------
---------------
-- T Y P E S --
---------------
---------------------------------------------------------------------------
-- Due to the fact that only pointers to device and context are passed
-- we ar going to use System.Address for them.
subtype Context is System.Address;
subtype Device is System.Address;
subtype Bool is Binary.Byte;
subtype Char is Binary.S_Byte;
subtype Double is Long_Float;
subtype Enum is Binary.S_Word;
subtype Int is Integer;
subtype Pointer is System.Address;
subtype Short is Binary.S_Short;
subtype SizeI is Integer;
subtype UByte is Binary.Byte;
subtype UInt is Binary.Word;
subtype UShort is Binary.Short;
---------------------------------------------------------------------------
-----------------------
-- C O N S T A N T S --
-----------------------
---------------------------------------------------------------------------
-- Bool constants.
ALC_FALSE : constant Bool := 0;
ALC_TRUE : constant Bool := 1;
-- Followed by <Int> Hz
ALC_FREQUENCY : constant Enum := 16#1007#;
-- Followed by <Int> Hz
ALC_REFRESH : constant Enum := 16#1008#;
-- Followed by AL_TRUE, AL_FALSE
ALC_SYNC : constant Enum := 16#1009#;
-- Followed by <Int> Num of requested Mono (3D) Sources
ALC_MONO_SOURCES : constant Enum := 16#1010#;
-- Followed by <Int> Num of requested Stereo Sources
ALC_STEREO_SOURCES : constant Enum := 16#1011#;
-- Errors
-- No error
ALC_NO_ERROR : constant Enum := 0;
-- No device
ALC_INVALID_DEVICE : constant Enum := 16#A001#;
-- Invalid context ID
ALC_INVALID_CONTEXT : constant Enum := 16#A002#;
-- Bad enum
ALC_INVALID_ENUM : constant Enum := 16#A003#;
-- Bad value
ALC_INVALID_VALUE : constant Enum := 16#A004#;
-- Out of memory.
ALC_OUT_OF_MEMORY : constant Enum := 16#A005#;
-- The Specifier string for default device
ALC_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#1004#;
ALC_DEVICE_SPECIFIER : constant Enum := 16#1005#;
ALC_EXTENSIONS : constant Enum := 16#1006#;
ALC_MAJOR_VERSION : constant Enum := 16#1000#;
ALC_MINOR_VERSION : constant Enum := 16#1001#;
ALC_ATTRIBUTES_SIZE : constant Enum := 16#1002#;
ALC_ALL_ATTRIBUTES : constant Enum := 16#1003#;
-- Capture extension
ALC_EXT_CAPTURE : constant Enum := 1;
ALC_CAPTURE_DEVICE_SPECIFIER : constant Enum := 16#310#;
ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#311#;
ALC_CAPTURE_SAMPLES : constant Enum := 16#312#;
-- ALC_ENUMERATE_ALL_EXT enums
ALC_ENUMERATE_ALL_EXT : constant Enum := 1;
ALC_DEFAULT_ALL_DEVICES_SPECIFIER : constant Enum := 16#1012#;
ALC_ALL_DEVICES_SPECIFIER : constant Enum := 16#1013#;
---------------------------------------------------------------------------
---------------------------
-- S U B P R O G R A M S --
---------------------------
---------------------------------------------------------------------------
-- Context Management
function Create_Context
( ADevice: in Device;
Attr_List: in Pointer
) return Context;
function Make_Context_Current (AContext: in Context) return Bool;
procedure Process_Context (AContext: in Context);
procedure Suspend_Context (AContext: in Context);
procedure Destroy_Context (AContext: in Context);
function Get_Current_Context return Context;
function Get_Contexts_Device (AContext: in Context) return Device;
-- Device Management
function Open_Device (Device_Name: in String) return Device;
Pragma Inline (Open_Device);
function Close_Device (ADevice: in Device) return Bool;
-- Error support.
-- Obtain the most recent Context error
function Get_Error (ADevice: in Device) return Enum;
-- Extension support.
-- Query for the presence of an extension, and obtain any appropriate
-- function pointers and enum values.
function Is_Extension_Present
( ADevice: in Device;
Ext_Name: in String
) return Bool;
Pragma Inline (Is_Extension_Present);
function Get_Proc_Address
( ADevice: in Device;
Func_Name: in String
) return Pointer;
Pragma Inline (Get_Proc_Address);
function Get_Enum_Value
( ADevice: in Device;
Enum_Name: in String
) return Enum;
Pragma Inline (Get_Enum_Value);
-- Query functions
function Get_String (ADevice: in Device; Param: in Enum) return String;
Pragma Inline (Get_String);
procedure Get_Integer
( ADevice: in Device;
Param: in Enum;
Size: in SizeI;
Data: in Pointer
);
-- Capture functions
function Capture_Open_Device
( Device_Name: in String;
Frequency: in UInt;
Format: in Enum;
Buffer_Size: in SizeI
) return Device;
Pragma Inline (Capture_Open_Device);
function Capture_Close_Device (ADevice: in Device) return Bool;
procedure Capture_Start (ADevice: in Device);
procedure Capture_Stop (ADevice: in Device);
procedure Capture_Samples
( ADevice: in Device;
Buffer: in Pointer;
Samples: in SizeI
);
---------------------------------------------------------------------------
-- NOTE: Pointer-To-Function types are not bound.
---------------------------------------------------------------------------
private
---------------------------------------------------------------------------
-------------------
-- I M P O R T S --
-------------------
---------------------------------------------------------------------------
Pragma Import (StdCall, Create_Context, "alcCreateContext");
Pragma Import (StdCall, Make_Context_Current, "alcMakeContextCurrent");
Pragma Import (StdCall, Process_Context, "alcProcessContext");
Pragma Import (StdCall, Suspend_Context, "alcSuspendContext");
Pragma Import (StdCall, Destroy_Context, "alcDestroyContext");
Pragma Import (StdCall, Get_Current_Context, "alcGetCurrentContext");
Pragma Import (StdCall, Get_Contexts_Device, "alcGetContextsDevice");
Pragma Import (StdCall, Close_Device, "alcCloseDevice");
Pragma Import (StdCall, Get_Error, "alcGetError");
Pragma Import (StdCall, Get_Integer, "alcGetIntegerv");
Pragma Import (StdCall, Capture_Close_Device, "alcCaptureCloseDevice");
Pragma Import (StdCall, Capture_Start, "alcCaptureStart");
Pragma Import (StdCall, Capture_Stop, "alcCaptureStop");
Pragma Import (StdCall, Capture_Samples, "alcCaptureSamples");
---------------------------------------------------------------------------
end Oto.ALC;
|
Add NOTE.
|
ALC: Add NOTE.
Signed-off-by: darkestkhan <[email protected]>
|
Ada
|
isc
|
darkestkhan/oto
|
a3e620a7e542fdf5c9aa239482dd510883c56e42
|
src/bbox-api.ads
|
src/bbox-api.ads
|
-----------------------------------------------------------------------
-- 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 Ada.Strings.Unbounded;
with Util.Properties;
with Util.Http.Clients;
package Bbox.API is
type Client_Type is tagged limited private;
-- Set the server IP address.
procedure Set_Server (Client : in out Client_Type;
Server : in String);
-- Login to the server Bbox API with the password.
procedure Login (Client : in out Client_Type;
Password : in String);
-- 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);
-- 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);
-- 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;
private
-- Internal operation to get the URI based on the operation being called.
function Get_URI (Client : in Client_Type;
Operation : in String) return String;
type Client_Type is tagged limited record
Password : Ada.Strings.Unbounded.Unbounded_String;
Server : Ada.Strings.Unbounded.Unbounded_String;
Auth : Ada.Strings.Unbounded.Unbounded_String;
Http : Util.Http.Clients.Client;
end record;
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 Ada.Strings.Unbounded;
with Ada.Calendar;
with Util.Properties;
with Util.Http.Clients;
package Bbox.API is
type Client_Type is tagged limited private;
-- Set the server IP address.
procedure Set_Server (Client : in out Client_Type;
Server : in String);
-- Login to the server Bbox API with the password.
procedure Login (Client : in out Client_Type;
Password : in String);
-- 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);
-- 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);
-- 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);
-- 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;
-- 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));
private
-- Internal operation to get the URI based on the operation being called.
function Get_URI (Client : in Client_Type;
Operation : in String) return String;
type Client_Type is tagged limited record
Password : Ada.Strings.Unbounded.Unbounded_String;
Server : Ada.Strings.Unbounded.Unbounded_String;
Auth : Ada.Strings.Unbounded.Unbounded_String;
Is_Logged : Boolean := False;
Http : Util.Http.Clients.Client;
Token : Ada.Strings.Unbounded.Unbounded_String;
Expires : Ada.Calendar.Time;
end record;
procedure Refresh_Token (Client : in out Client_Type);
end Bbox.API;
|
Declare the Iterate procedure Declare the Post procedure Declare the Refresh_Token private procedure
|
Declare the Iterate procedure
Declare the Post procedure
Declare the Refresh_Token private procedure
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
84ef35874db49e0d5877a372b0bcd13f17883a29
|
src/util-files.adb
|
src/util-files.adb
|
-----------------------------------------------------------------------
-- Util.Files -- Various File Utility Packages
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Fixed;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
with Util.Strings.Tokenizers;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
begin
Util.Strings.Tokenizers.Iterate_Tokens (Content => Path,
Pattern => ";",
Process => Process,
Going => Going);
end Iterate_Path;
-- ------------------------------
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : String;
Paths : String) return String is
use Ada.Directories;
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Index (Paths, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String) return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Unbounded_String;
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
use Ada.Strings.Fixed;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Length (Result) > 0 then
Append (Result, ';');
end if;
Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return To_String (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 or Directory = "." or Directory = "./" then
return Name;
elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\')) then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
end Util.Files;
|
-----------------------------------------------------------------------
-- Util.Files -- Various File Utility Packages
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Fixed;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
with Util.Strings.Tokenizers;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
begin
Util.Strings.Tokenizers.Iterate_Tokens (Content => Path,
Pattern => ";",
Process => Process,
Going => Going);
end Iterate_Path;
-- ------------------------------
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : String;
Paths : String) return String is
use Ada.Directories;
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Index (Paths, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String) return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Unbounded_String;
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
use Ada.Strings.Fixed;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Length (Result) > 0 then
Append (Result, ';');
end if;
Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return To_String (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 or Directory = "." or Directory = "./" then
return Name;
elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\'))
then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
end Util.Files;
|
Fix compilation style warning
|
Fix compilation style warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a0459fab162a885ef38d626e259c43b29f3a40fa
|
mat/src/mat-commands.ads
|
mat/src/mat-commands.ads
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- 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);
end MAT.Commands;
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- 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);
end MAT.Commands;
|
Declare Events_Command procedure
|
Declare Events_Command procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
8dd291bd5746ca3db947df5c77ae9d5e57505192
|
mat/src/mat-consoles.ads
|
mat/src/mat-consoles.ads
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_THREAD,
F_COUNT);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer);
private
type Field_Size_Array is array (Field_Type) of Positive;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_THREAD,
F_COUNT);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer);
private
type Field_Size_Array is array (Field_Type) of Positive;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
Define the Start_Title operation
|
Define the Start_Title operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ba1063c9ee27b2aa7dabffa781df53be7ada55c4
|
src/ado-caches-discrete.ads
|
src/ado-caches-discrete.ads
|
-----------------------------------------------------------------------
-- ado-cache-discrete -- Simple cache management for discrete types
-- 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.Containers;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with ADO.Sessions;
generic
type Element_Type is (<>);
package ADO.Caches.Discrete is
pragma Elaborate_Body;
-- The cache type that maintains a cache of name/value pairs.
type Cache_Type is new ADO.Caches.Cache_Type with private;
-- Expand the name into a target parameter value to be used in the SQL query.
-- The Expander can return a T_NULL when a value is not found or
-- it may also raise some exception.
overriding
function Expand (Instance : in out Cache_Type;
Name : in String) return ADO.Parameters.Parameter;
-- Find the value associated with the given name.
-- Raises the No_Value exception if no such mapping exist.
function Find (Cache : in out Cache_Type;
Name : in String) return Element_Type;
-- Insert the value associated with the given name in the cache.
-- When <tt>Override</tt> is set, override existing values otherwise raise an exception.
procedure Insert (Cache : in out Cache_Type;
Name : in String;
Value : in Element_Type;
Override : in Boolean := False);
-- Delete the value associated with the given name in the cache.
-- Raise the No_Value exception if the value is not found and <tt>Ignore</tt> is not set.
procedure Delete (Cache : in out Cache_Type;
Name : in String;
Ignore : in Boolean := False);
-- Initialize the entity cache by reading the database entity table.
procedure Initialize (Cache : in out Cache_Type;
Session : in out ADO.Sessions.Session'Class);
private
package Cache_Map is new
Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Element_Type,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
protected type Cache_Controller is
-- Find the value associated with the given name.
-- Raises the No_Value exception if no such mapping exist.
function Find (Name : in String) return Element_Type;
-- Insert the value associated with the given name in the cache.
-- When <tt>Override</tt> is set, override existing values otherwise raise an exception.
procedure Insert (Name : in String;
Value : in Element_Type;
Override : in Boolean := False);
-- Delete the value associated with the given name in the cache.
-- Raise the No_Value exception if the value is not found and <tt>Ignore</tt> is not set.
procedure Delete (Name : in String;
Ignore : in Boolean := False);
private
Values : Cache_Map.Map;
end Cache_Controller;
type Cache_Type is new ADO.Caches.Cache_Type with record
Controller : Cache_Controller;
end record;
end ADO.Caches.Discrete;
|
-----------------------------------------------------------------------
-- ado-cache-discrete -- Simple cache management for discrete types
-- 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.Containers;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with ADO.Sessions;
generic
type Element_Type is (<>);
package ADO.Caches.Discrete is
pragma Elaborate_Body;
-- The cache type that maintains a cache of name/value pairs.
type Cache_Type is new ADO.Caches.Cache_Type with private;
type Cache_Type_Access is access all Cache_Type'Class;
-- Expand the name into a target parameter value to be used in the SQL query.
-- The Expander can return a T_NULL when a value is not found or
-- it may also raise some exception.
overriding
function Expand (Instance : in out Cache_Type;
Name : in String) return ADO.Parameters.Parameter;
-- Find the value associated with the given name.
-- Raises the No_Value exception if no such mapping exist.
function Find (Cache : in out Cache_Type;
Name : in String) return Element_Type;
-- Insert the value associated with the given name in the cache.
-- When <tt>Override</tt> is set, override existing values otherwise raise an exception.
procedure Insert (Cache : in out Cache_Type;
Name : in String;
Value : in Element_Type;
Override : in Boolean := False);
-- Delete the value associated with the given name in the cache.
-- Raise the No_Value exception if the value is not found and <tt>Ignore</tt> is not set.
procedure Delete (Cache : in out Cache_Type;
Name : in String;
Ignore : in Boolean := False);
-- Initialize the entity cache by reading the database entity table.
procedure Initialize (Cache : in out Cache_Type;
Session : in out ADO.Sessions.Session'Class);
private
package Cache_Map is new
Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Element_Type,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
protected type Cache_Controller is
-- Find the value associated with the given name.
-- Raises the No_Value exception if no such mapping exist.
function Find (Name : in String) return Element_Type;
-- Insert the value associated with the given name in the cache.
-- When <tt>Override</tt> is set, override existing values otherwise raise an exception.
procedure Insert (Name : in String;
Value : in Element_Type;
Override : in Boolean := False);
-- Delete the value associated with the given name in the cache.
-- Raise the No_Value exception if the value is not found and <tt>Ignore</tt> is not set.
procedure Delete (Name : in String;
Ignore : in Boolean := False);
private
Values : Cache_Map.Map;
end Cache_Controller;
type Cache_Type is new ADO.Caches.Cache_Type with record
Controller : Cache_Controller;
end record;
end ADO.Caches.Discrete;
|
Declare the Cache_Type_Access access type
|
Declare the Cache_Type_Access access type
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
4ad7c6322d8b82c838ac1ba2b63796eae2437d17
|
src/asf-rest-definition.ads
|
src/asf-rest-definition.ads
|
-----------------------------------------------------------------------
-- asf-rest-definition -- REST API Definition
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
generic
type Object_Type is limited private;
URI : String;
package ASF.Rest.Definition is
type Descriptor is new ASF.Rest.Descriptor with record
Handler : access procedure (Object : in out Object_Type;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
end record;
overriding
procedure Dispatch (Handler : in Descriptor;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
-- Definition of an API operation mapped to a given URI pattern and associated with
-- the operation handler.
generic
Handler : access procedure (Object : in out Object_Type;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
Method : Method_Type;
Pattern : String;
Permission : Security.Permissions.Permission_Index;
package Definition is
Instance : aliased Descriptor;
end Definition;
-- Register the list of APIs that have been created by instantiating the <tt>Definition</tt>
-- package. The REST servlet identified by <tt>Name</tt> is searched in the servlet registry
-- and used as the servlet for processing the API requests.
procedure Register (Registry : in out ASF.Servlets.Servlet_Registry;
Name : in String;
ELContext : in EL.Contexts.ELContext'Class);
private
Entries : ASF.Rest.Descriptor_Access;
end ASF.Rest.Definition;
|
-----------------------------------------------------------------------
-- asf-rest-definition -- REST API Definition
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
generic
type Object_Type is limited private;
URI : String;
package ASF.Rest.Definition is
type Descriptor is new ASF.Rest.Descriptor with record
Handler : access procedure (Object : in out Object_Type;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
end record;
overriding
procedure Dispatch (Handler : in Descriptor;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
-- Definition of an API operation mapped to a given URI pattern and associated with
-- the operation handler.
generic
Handler : access procedure (Object : in out Object_Type;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class);
Method : Method_Type := ASF.Rest.GET;
Pattern : String;
Permission : Security.Permissions.Permission_Index := Security.Permissions.NONE;
package Definition is
Instance : aliased Descriptor;
end Definition;
-- Register the list of APIs that have been created by instantiating the <tt>Definition</tt>
-- package. The REST servlet identified by <tt>Name</tt> is searched in the servlet registry
-- and used as the servlet for processing the API requests.
procedure Register (Registry : in out ASF.Servlets.Servlet_Registry;
Name : in String;
ELContext : in EL.Contexts.ELContext'Class);
private
Entries : ASF.Rest.Descriptor_Access;
end ASF.Rest.Definition;
|
Add default values for the generic package Definition
|
Add default values for the generic package Definition
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
bb852ed2c2b001785a064bdef756e121ccca3d74
|
src/security-auth-oauth.adb
|
src/security-auth-oauth.adb
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Assoc_Handle := To_Unbounded_String ("nonce-generator");
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
pragma Unreferenced (Realm);
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
pragma Unreferenced (Realm, OP);
begin
Result.Assoc_Handle := To_Unbounded_String (Security.OAuth.Clients.Create_Nonce (128));
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
Use Create_Nonce for the nonce generation Fix compilation warnings
|
Use Create_Nonce for the nonce generation
Fix compilation warnings
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.