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
|
---|---|---|---|---|---|---|---|---|---|
4783f0e3af3f3141e311a18030186f7f23002cdd
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Users.Modules;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Member_List_Bean",
Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Invitation_Bean",
Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager;
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS);
Workspace := WS;
end Get_Workspace;
-- ------------------------------
-- Send the invitation to the user.
-- ------------------------------
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email));
Ctx.Start;
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (DB, Query, Found);
if not Found then
return;
end if;
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
Module.User_Manager.Create_Access_Key (User, Key, 365 * 86400.0, DB);
Key.Save (DB);
Invitation.Set_Access_Key (Key);
Invitation.Set_Inviter (User);
Invitation.Set_Workspace (WS);
Invitation.Set_Create_Date (Ada.Calendar.Clock);
Invitation.Save (DB);
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Users.Modules;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Member_List_Bean",
Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Invitation_Bean",
Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager;
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS);
Workspace := WS;
end Get_Workspace;
-- ------------------------------
-- Load the invitation from the access key and verify that the key is still valid.
-- ------------------------------
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
begin
Log.Debug ("Loading invitation from key {0}", Key);
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
end Load_Invitation;
-- ------------------------------
-- Send the invitation to the user.
-- ------------------------------
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email));
Ctx.Start;
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (DB, Query, Found);
if not Found then
return;
end if;
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
Module.User_Manager.Create_Access_Key (User, Key, 365 * 86400.0, DB);
Key.Save (DB);
Invitation.Set_Access_Key (Key);
Invitation.Set_Inviter (User);
Invitation.Set_Workspace (WS);
Invitation.Set_Create_Date (Ada.Calendar.Clock);
Invitation.Save (DB);
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
Implement the Load_Invitation procedure to load the invitation based on the access key
|
Implement the Load_Invitation procedure to load the invitation based on the access key
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ddcb0a581c52fde48e76f77c6b89fc8d698e6bb9
|
awa/src/awa-users-beans.adb
|
awa/src/awa-users-beans.adb
|
-----------------------------------------------------------------------
-- awa-users-beans -- ASF Beans for user module
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Principals;
with ASF.Sessions;
with ASF.Events.Faces.Actions;
with ASF.Contexts.Faces;
with ASF.Contexts.Flash;
with ASF.Cookies;
with ASF.Applications.Messages.Factory;
with ASF.Security.Filters;
with AWA.Services.Contexts;
package body AWA.Users.Beans is
use Util.Log;
use AWA.Users.Models;
use ASF.Applications;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Users.Beans");
-- Helper to send a remove cookie in the current response
procedure Remove_Cookie (Name : in String);
-- ------------------------------
-- Action to register a user
-- ------------------------------
procedure Register_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
User : User_Ref;
Email : Email_Ref;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Email.Set_Email (Data.Email);
User.Set_First_Name (Data.First_Name);
User.Set_Last_Name (Data.Last_Name);
User.Set_Password (Data.Password);
Data.Manager.Create_User (User => User,
Email => Email);
Outcome := To_Unbounded_String ("success");
-- Add a message to the flash context so that it will be displayed on the next page.
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "users.message_signup_sent", Messages.INFO);
exception
when Services.User_Exist =>
Outcome := To_Unbounded_String ("failure");
Messages.Factory.Add_Message (Ctx.all, "users.signup_error_message");
end Register_User;
-- ------------------------------
-- Action to verify the user after the registration
-- ------------------------------
procedure Verify_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
Principal : AWA.Users.Principals.Principal_Access;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Data.Manager.Verify_User (Key => To_String (Data.Access_Key),
IpAddr => "",
Principal => Principal);
Data.Set_Session_Principal (Principal);
Outcome := To_Unbounded_String ("success");
-- Add a message to the flash context so that it will be displayed on the next page.
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "users.message_registration_done", Messages.INFO);
exception
when Services.Not_Found =>
Outcome := To_Unbounded_String ("failure");
Messages.Factory.Add_Message (Ctx.all, "users.error_verify_register_key");
end Verify_User;
-- ------------------------------
-- Action to trigger the lost password email process.
-- ------------------------------
procedure Lost_Password (Data : in out Authenticate_Bean;
Outcome : in out 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
Data.Manager.Lost_Password (Email => To_String (Data.Email));
Outcome := To_Unbounded_String ("success");
-- Add a message to the flash context so that it will be displayed on the next page.
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "users.message_lost_password_sent", Messages.INFO);
exception
when Services.Not_Found =>
Messages.Factory.Add_Message (Ctx.all, "users.error_email_not_found");
end Lost_Password;
-- ------------------------------
-- 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) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
Principal : AWA.Users.Principals.Principal_Access;
begin
Data.Manager.Reset_Password (Key => To_String (Data.Access_Key),
Password => To_String (Data.Password),
IpAddr => "",
Principal => Principal);
Data.Set_Session_Principal (Principal);
Outcome := To_Unbounded_String ("success");
-- Add a message to the flash context so that it will be displayed on the next page.
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "users.message_reset_password_done", Messages.INFO);
exception
when Services.Not_Found =>
Messages.Factory.Add_Message (Ctx.all, "users.error_reset_password");
end Reset_Password;
procedure Set_Session_Principal (Data : in Authenticate_Bean;
Principal : in AWA.Users.Principals.Principal_Access) is
pragma Unreferenced (Data);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True);
begin
Session.Set_Principal (Principal.all'Access);
end Set_Session_Principal;
procedure Set_Authenticate_Cookie (Data : in out Authenticate_Bean;
Principal : in AWA.Users.Principals.Principal_Access) is
Cookie : constant String := Data.Manager.Get_Authenticate_Cookie (Principal.Get_Session_Identifier);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (ASF.Security.Filters.AID_COOKIE, Cookie);
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 15 * 86400);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Set_Authenticate_Cookie;
-- ------------------------------
-- Action to authenticate a user (password authentication).
-- ------------------------------
procedure Authenticate_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
Principal : AWA.Users.Principals.Principal_Access;
begin
Data.Manager.Authenticate (Email => To_String (Data.Email),
Password => To_String (Data.Password),
IpAddr => "",
Principal => Principal);
Outcome := To_Unbounded_String ("success");
Data.Set_Session_Principal (Principal);
Data.Set_Authenticate_Cookie (Principal);
exception
when Services.Not_Found =>
Outcome := To_Unbounded_String ("failure");
ASF.Applications.Messages.Factory.Add_Message ("users.login_signup_fail_message");
end Authenticate_User;
-- ------------------------------
-- Helper to send a remove cookie in the current response
-- ------------------------------
procedure Remove_Cookie (Name : in String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Remove_Cookie;
-- ------------------------------
-- Logout the user and closes the session.
-- ------------------------------
procedure Logout_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
use type ASF.Principals.Principal_Access;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := Ctx.Get_Session (Create => False);
begin
Outcome := To_Unbounded_String ("success");
-- If there is no session, we are done.
if not Session.Is_Valid then
return;
end if;
declare
Principal : constant ASF.Principals.Principal_Access := Session.Get_Principal;
begin
if Principal /= null and then Principal.all in AWA.Users.Principals.Principal'Class then
declare
P : constant AWA.Users.Principals.Principal_Access :=
AWA.Users.Principals.Principal'Class (Principal.all)'Access;
begin
Data.Manager.Close_Session (Id => P.Get_Session_Identifier,
Logout => True);
exception
when others =>
Log.Error ("Exception when closing user session...");
end;
end if;
Session.Invalidate;
end;
-- Remove the session cookie.
Remove_Cookie (ASF.Security.Filters.SID_COOKIE);
Remove_Cookie (ASF.Security.Filters.AID_COOKIE);
end Logout_User;
-- ------------------------------
-- Create an authenticate bean.
-- ------------------------------
function Create_Authenticate_Bean (Module : in AWA.Users.Modules.User_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Authenticate_Bean_Access := new Authenticate_Bean;
begin
Object.Module := Module;
Object.Manager := AWA.Users.Modules.Get_User_Manager;
return Object.all'Access;
end Create_Authenticate_Bean;
-- The code below this line could be generated automatically by an Asis tool.
package Authenticate_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Authenticate_User,
Name => "authenticate");
package Register_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Register_User,
Name => "register");
package Verify_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Verify_User,
Name => "verify");
package Lost_Password_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Lost_Password,
Name => "lostPassword");
package Reset_Password_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Reset_Password,
Name => "resetPassword");
package Logout_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Logout_User,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Authenticate_Binding.Proxy'Access,
Register_Binding.Proxy'Access,
Verify_Binding.Proxy'Access,
Lost_Password_Binding.Proxy'Access,
Reset_Password_Binding.Proxy'Access,
Logout_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Authenticate_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = EMAIL_ATTR then
return Util.Beans.Objects.To_Object (From.Email);
elsif Name = PASSWORD_ATTR then
return Util.Beans.Objects.To_Object (From.Password);
elsif Name = FIRST_NAME_ATTR then
return Util.Beans.Objects.To_Object (From.First_Name);
elsif Name = LAST_NAME_ATTR then
return Util.Beans.Objects.To_Object (From.Last_Name);
elsif Name = KEY_ATTR then
return Util.Beans.Objects.To_Object (From.Access_Key);
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 Authenticate_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = EMAIL_ATTR then
From.Email := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = PASSWORD_ATTR then
From.Password := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = FIRST_NAME_ATTR then
From.First_Name := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = LAST_NAME_ATTR then
From.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = KEY_ATTR then
From.Access_Key := 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 Authenticate_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
-- ------------------------------
-- 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 is
pragma Unreferenced (From);
use type AWA.Services.Contexts.Service_Context_Access;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
begin
if Ctx = null then
if Name = IS_LOGGED_ATTR then
return Util.Beans.Objects.To_Object (False);
else
return Util.Beans.Objects.Null_Object;
end if;
else
declare
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
begin
if User.Is_Null then
if Name = IS_LOGGED_ATTR then
return Util.Beans.Objects.To_Object (False);
else
return Util.Beans.Objects.Null_Object;
end if;
else
if Name = USER_NAME_ATTR then
return Util.Beans.Objects.To_Object (String '(User.Get_Name));
elsif Name = USER_EMAIL_ATTR then
return Util.Beans.Objects.To_Object (String '(User.Get_Email.Get_Email));
elsif Name = USER_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (User.Get_Id));
elsif Name = IS_LOGGED_ATTR then
return Util.Beans.Objects.To_Object (True);
else
return Util.Beans.Objects.Null_Object;
end if;
end if;
end;
end if;
end Get_Value;
-- ------------------------------
-- 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 is
Object : constant Current_User_Bean_Access := new Current_User_Bean;
begin
return Object.all'Access;
end Create_Current_User_Bean;
end AWA.Users.Beans;
|
-----------------------------------------------------------------------
-- awa-users-beans -- ASF Beans for user module
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Principals;
with ASF.Sessions;
with ASF.Events.Faces.Actions;
with ASF.Contexts.Faces;
with ASF.Contexts.Flash;
with ASF.Cookies;
with ASF.Applications.Messages.Factory;
with ASF.Security.Filters;
with ADO.Sessions;
with AWA.Services.Contexts;
package body AWA.Users.Beans is
use Util.Log;
use AWA.Users.Models;
use ASF.Applications;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Users.Beans");
-- Helper to send a remove cookie in the current response
procedure Remove_Cookie (Name : in String);
-- ------------------------------
-- Action to register a user
-- ------------------------------
procedure Register_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
User : User_Ref;
Email : Email_Ref;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Email.Set_Email (Data.Email);
User.Set_First_Name (Data.First_Name);
User.Set_Last_Name (Data.Last_Name);
User.Set_Password (Data.Password);
Data.Manager.Create_User (User => User,
Email => Email);
Outcome := To_Unbounded_String ("success");
-- Add a message to the flash context so that it will be displayed on the next page.
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "users.message_signup_sent", Messages.INFO);
exception
when Services.User_Exist =>
Outcome := To_Unbounded_String ("failure");
Messages.Factory.Add_Message (Ctx.all, "users.signup_error_message");
end Register_User;
-- ------------------------------
-- Action to verify the user after the registration
-- ------------------------------
procedure Verify_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
Principal : AWA.Users.Principals.Principal_Access;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Data.Manager.Verify_User (Key => To_String (Data.Access_Key),
IpAddr => "",
Principal => Principal);
Data.Set_Session_Principal (Principal);
Outcome := To_Unbounded_String ("success");
-- Add a message to the flash context so that it will be displayed on the next page.
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "users.message_registration_done", Messages.INFO);
exception
when Services.Not_Found =>
Outcome := To_Unbounded_String ("failure");
Messages.Factory.Add_Message (Ctx.all, "users.error_verify_register_key");
end Verify_User;
-- ------------------------------
-- Action to trigger the lost password email process.
-- ------------------------------
procedure Lost_Password (Data : in out Authenticate_Bean;
Outcome : in out 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
Data.Manager.Lost_Password (Email => To_String (Data.Email));
Outcome := To_Unbounded_String ("success");
-- Add a message to the flash context so that it will be displayed on the next page.
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "users.message_lost_password_sent", Messages.INFO);
exception
when Services.Not_Found =>
Messages.Factory.Add_Message (Ctx.all, "users.error_email_not_found");
end Lost_Password;
-- ------------------------------
-- 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) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
Principal : AWA.Users.Principals.Principal_Access;
begin
Data.Manager.Reset_Password (Key => To_String (Data.Access_Key),
Password => To_String (Data.Password),
IpAddr => "",
Principal => Principal);
Data.Set_Session_Principal (Principal);
Outcome := To_Unbounded_String ("success");
-- Add a message to the flash context so that it will be displayed on the next page.
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "users.message_reset_password_done", Messages.INFO);
exception
when Services.Not_Found =>
Messages.Factory.Add_Message (Ctx.all, "users.error_reset_password");
end Reset_Password;
procedure Set_Session_Principal (Data : in Authenticate_Bean;
Principal : in AWA.Users.Principals.Principal_Access) is
pragma Unreferenced (Data);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True);
begin
Session.Set_Principal (Principal.all'Access);
end Set_Session_Principal;
procedure Set_Authenticate_Cookie (Data : in out Authenticate_Bean;
Principal : in AWA.Users.Principals.Principal_Access) is
Cookie : constant String := Data.Manager.Get_Authenticate_Cookie (Principal.Get_Session_Identifier);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (ASF.Security.Filters.AID_COOKIE, Cookie);
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 15 * 86400);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Set_Authenticate_Cookie;
-- ------------------------------
-- Action to authenticate a user (password authentication).
-- ------------------------------
procedure Authenticate_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
Principal : AWA.Users.Principals.Principal_Access;
begin
Data.Manager.Authenticate (Email => To_String (Data.Email),
Password => To_String (Data.Password),
IpAddr => "",
Principal => Principal);
Outcome := To_Unbounded_String ("success");
Data.Set_Session_Principal (Principal);
Data.Set_Authenticate_Cookie (Principal);
exception
when Services.Not_Found =>
Outcome := To_Unbounded_String ("failure");
ASF.Applications.Messages.Factory.Add_Message ("users.login_signup_fail_message");
end Authenticate_User;
-- ------------------------------
-- Helper to send a remove cookie in the current response
-- ------------------------------
procedure Remove_Cookie (Name : in String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Remove_Cookie;
-- ------------------------------
-- Logout the user and closes the session.
-- ------------------------------
procedure Logout_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
use type ASF.Principals.Principal_Access;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := Ctx.Get_Session (Create => False);
begin
Outcome := To_Unbounded_String ("success");
-- If there is no session, we are done.
if not Session.Is_Valid then
return;
end if;
declare
Principal : constant ASF.Principals.Principal_Access := Session.Get_Principal;
begin
if Principal /= null and then Principal.all in AWA.Users.Principals.Principal'Class then
declare
P : constant AWA.Users.Principals.Principal_Access :=
AWA.Users.Principals.Principal'Class (Principal.all)'Access;
begin
Data.Manager.Close_Session (Id => P.Get_Session_Identifier,
Logout => True);
exception
when others =>
Log.Error ("Exception when closing user session...");
end;
end if;
Session.Invalidate;
end;
-- Remove the session cookie.
Remove_Cookie (ASF.Security.Filters.SID_COOKIE);
Remove_Cookie (ASF.Security.Filters.AID_COOKIE);
end Logout_User;
-- ------------------------------
-- Create an authenticate bean.
-- ------------------------------
function Create_Authenticate_Bean (Module : in AWA.Users.Modules.User_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Authenticate_Bean_Access := new Authenticate_Bean;
begin
Object.Module := Module;
Object.Manager := AWA.Users.Modules.Get_User_Manager;
return Object.all'Access;
end Create_Authenticate_Bean;
-- The code below this line could be generated automatically by an Asis tool.
package Authenticate_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Authenticate_User,
Name => "authenticate");
package Register_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Register_User,
Name => "register");
package Verify_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Verify_User,
Name => "verify");
package Lost_Password_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Lost_Password,
Name => "lostPassword");
package Reset_Password_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Reset_Password,
Name => "resetPassword");
package Logout_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Logout_User,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Authenticate_Binding.Proxy'Access,
Register_Binding.Proxy'Access,
Verify_Binding.Proxy'Access,
Lost_Password_Binding.Proxy'Access,
Reset_Password_Binding.Proxy'Access,
Logout_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Authenticate_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = EMAIL_ATTR then
return Util.Beans.Objects.To_Object (From.Email);
elsif Name = PASSWORD_ATTR then
return Util.Beans.Objects.To_Object (From.Password);
elsif Name = FIRST_NAME_ATTR then
return Util.Beans.Objects.To_Object (From.First_Name);
elsif Name = LAST_NAME_ATTR then
return Util.Beans.Objects.To_Object (From.Last_Name);
elsif Name = KEY_ATTR then
return Util.Beans.Objects.To_Object (From.Access_Key);
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 Authenticate_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = EMAIL_ATTR then
From.Email := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = PASSWORD_ATTR then
From.Password := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = FIRST_NAME_ATTR then
From.First_Name := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = LAST_NAME_ATTR then
From.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = KEY_ATTR then
From.Access_Key := 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 Authenticate_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
-- ------------------------------
-- 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 is
package ASC renames AWA.Services.Contexts;
pragma Unreferenced (From);
use type ASC.Service_Context_Access;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
if Ctx = null then
if Name = IS_LOGGED_ATTR then
return Util.Beans.Objects.To_Object (False);
else
return Util.Beans.Objects.Null_Object;
end if;
else
declare
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
begin
if User.Is_Null then
if Name = IS_LOGGED_ATTR then
return Util.Beans.Objects.To_Object (False);
else
return Util.Beans.Objects.Null_Object;
end if;
else
if Name = USER_NAME_ATTR then
return Util.Beans.Objects.To_Object (String '(User.Get_Name));
elsif Name = USER_EMAIL_ATTR then
declare
Email : AWA.Users.Models.Email_Ref'Class := User.Get_Email;
begin
if not Email.Is_Loaded then
-- The email object was not loaded. Load it using a new database session.
declare
Session : ADO.Sessions.Session := ASC.Get_Session (Ctx);
begin
Email.Load (Session, Email.Get_Id);
end;
end if;
return Util.Beans.Objects.To_Object (String '(Email.Get_Email));
end;
elsif Name = USER_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (User.Get_Id));
elsif Name = IS_LOGGED_ATTR then
return Util.Beans.Objects.To_Object (True);
else
return Util.Beans.Objects.Null_Object;
end if;
end if;
end;
end if;
end Get_Value;
-- ------------------------------
-- 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 is
Object : constant Current_User_Bean_Access := new Current_User_Bean;
begin
return Object.all'Access;
end Create_Current_User_Bean;
end AWA.Users.Beans;
|
Fix retrieval of user email address
|
Fix retrieval of user email address
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
cf80a4a640ee6828a008f4f40d2a97d623f4af27
|
awa/src/awa-users-beans.adb
|
awa/src/awa-users-beans.adb
|
-----------------------------------------------------------------------
-- awa-users-beans -- ASF Beans for user 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 ASF.Principals;
with ASF.Sessions;
with ASF.Events.Actions;
with ASF.Contexts.Faces;
with ASF.Cookies;
with AWA.Users.Principals;
package body AWA.Users.Beans is
use AWA.Users.Models;
-- ------------------------------
-- Action to register a user
-- ------------------------------
procedure Register_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
User : User_Ref;
Email : Email_Ref;
begin
Email.Set_Email (Data.Email);
User.Set_First_Name (Data.First_Name);
User.Set_Last_Name (Data.Last_Name);
User.Set_Password (Data.Password);
Data.Manager.Create_User (User => User,
Email => Email);
Outcome := To_Unbounded_String ("success");
end Register_User;
-- ------------------------------
-- Action to verify the user after the registration
-- ------------------------------
procedure Verify_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
User : User_Ref;
Session : Session_Ref;
begin
Data.Manager.Verify_User (Key => To_String (Data.Access_Key),
User => User,
IpAddr => "",
Session => Session);
Data.Set_Session_Principal (User, Session);
Outcome := To_Unbounded_String ("success");
end Verify_User;
-- ------------------------------
-- Action to trigger the lost password email process.
-- ------------------------------
procedure Lost_Password (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
begin
Data.Manager.Lost_Password (Email => To_String (Data.Email));
Outcome := To_Unbounded_String ("success");
end Lost_Password;
-- ------------------------------
-- 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) is
User : User_Ref;
Session : Session_Ref;
begin
Data.Manager.Reset_Password (Key => To_String (Data.Access_Key),
Password => To_String (Data.Password),
IpAddr => "",
User => User,
Session => Session);
Outcome := To_Unbounded_String ("success");
end Reset_Password;
procedure Set_Session_Principal (Data : in Authenticate_Bean;
User : in AWA.Users.Models.User_Ref;
Sess : in AWA.Users.Models.Session_Ref) is
pragma Unreferenced (Data);
Principal : constant Principals.Principal_Access := Principals.Create (User, Sess);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True);
begin
Session.Set_Principal (Principal.all'Access);
end Set_Session_Principal;
-- ------------------------------
-- Action to authenticate a user (password authentication).
-- ------------------------------
procedure Authenticate_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
User : User_Ref;
Session : Session_Ref;
begin
Data.Manager.Authenticate (Email => To_String (Data.Email),
Password => To_String (Data.Password),
IpAddr => "",
User => User,
Session => Session);
Outcome := To_Unbounded_String ("success");
Data.Set_Session_Principal (User, Session);
end Authenticate_User;
-- ------------------------------
-- Logout the user and closes the session.
-- ------------------------------
procedure Logout_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
use type ASF.Principals.Principal_Access;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := Ctx.Get_Session (Create => False);
begin
Outcome := To_Unbounded_String ("success");
-- If there is no session, we are done.
if not Session.Is_Valid then
return;
end if;
declare
Principal : constant ASF.Principals.Principal_Access := Session.Get_Principal;
begin
if Principal /= null and then Principal.all in AWA.Users.Principals.Principal'Class then
declare
P : constant AWA.Users.Principals.Principal_Access :=
AWA.Users.Principals.Principal'Class (Principal.all)'Access;
begin
Data.Manager.Close_Session (Id => P.Get_Session_Identifier);
end;
end if;
Session.Invalidate;
end;
-- Remove the session cookie.
declare
C : ASF.Cookies.Cookie := ASF.Cookies.Create ("SID", "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end;
end Logout_User;
-- ------------------------------
-- Create an authenticate bean.
-- ------------------------------
function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Authenticate_Bean_Access := new Authenticate_Bean;
begin
Object.Module := Module;
Object.Manager := AWA.Users.Module.Get_User_Manager;
return Object.all'Access;
end Create_Authenticate_Bean;
-- The code below this line could be generated automatically by an Asis tool.
package Authenticate_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Authenticate_User,
Name => "authenticate");
package Register_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Register_User,
Name => "register");
package Verify_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Verify_User,
Name => "verify");
package Lost_Password_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Lost_Password,
Name => "lostPassword");
package Reset_Password_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Reset_Password,
Name => "resetPassword");
package Logout_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Logout_User,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Authenticate_Binding.Proxy'Access,
Register_Binding.Proxy'Access,
Verify_Binding.Proxy'Access,
Lost_Password_Binding.Proxy'Access,
Reset_Password_Binding.Proxy'Access,
Logout_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Authenticate_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = EMAIL_ATTR then
return Util.Beans.Objects.To_Object (From.Email);
elsif Name = PASSWORD_ATTR then
return Util.Beans.Objects.To_Object (From.Password);
elsif Name = FIRST_NAME_ATTR then
return Util.Beans.Objects.To_Object (From.First_Name);
elsif Name = LAST_NAME_ATTR then
return Util.Beans.Objects.To_Object (From.Last_Name);
elsif Name = KEY_ATTR then
return Util.Beans.Objects.To_Object (From.Access_Key);
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 Authenticate_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = EMAIL_ATTR then
From.Email := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = PASSWORD_ATTR then
From.Password := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = FIRST_NAME_ATTR then
From.First_Name := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = LAST_NAME_ATTR then
From.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = KEY_ATTR then
From.Access_Key := 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 Authenticate_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
end AWA.Users.Beans;
|
-----------------------------------------------------------------------
-- awa-users-beans -- ASF Beans for user 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 Util.Log.Loggers;
with ASF.Principals;
with ASF.Sessions;
with ASF.Events.Actions;
with ASF.Contexts.Faces;
with ASF.Cookies;
with ASF.Applications.Messages.Factory;
with AWA.Users.Principals;
package body AWA.Users.Beans is
use Util.Log;
use AWA.Users.Models;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Users.Beans");
-- ------------------------------
-- Action to register a user
-- ------------------------------
procedure Register_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
User : User_Ref;
Email : Email_Ref;
begin
Email.Set_Email (Data.Email);
User.Set_First_Name (Data.First_Name);
User.Set_Last_Name (Data.Last_Name);
User.Set_Password (Data.Password);
Data.Manager.Create_User (User => User,
Email => Email);
Outcome := To_Unbounded_String ("success");
end Register_User;
-- ------------------------------
-- Action to verify the user after the registration
-- ------------------------------
procedure Verify_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
User : User_Ref;
Session : Session_Ref;
begin
Data.Manager.Verify_User (Key => To_String (Data.Access_Key),
User => User,
IpAddr => "",
Session => Session);
Data.Set_Session_Principal (User, Session);
Outcome := To_Unbounded_String ("success");
end Verify_User;
-- ------------------------------
-- Action to trigger the lost password email process.
-- ------------------------------
procedure Lost_Password (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
begin
Data.Manager.Lost_Password (Email => To_String (Data.Email));
Outcome := To_Unbounded_String ("success");
end Lost_Password;
-- ------------------------------
-- 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) is
User : User_Ref;
Session : Session_Ref;
begin
Data.Manager.Reset_Password (Key => To_String (Data.Access_Key),
Password => To_String (Data.Password),
IpAddr => "",
User => User,
Session => Session);
Outcome := To_Unbounded_String ("success");
end Reset_Password;
procedure Set_Session_Principal (Data : in Authenticate_Bean;
User : in AWA.Users.Models.User_Ref;
Sess : in AWA.Users.Models.Session_Ref) is
pragma Unreferenced (Data);
Principal : constant Principals.Principal_Access := Principals.Create (User, Sess);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True);
begin
Session.Set_Principal (Principal.all'Access);
end Set_Session_Principal;
-- ------------------------------
-- Action to authenticate a user (password authentication).
-- ------------------------------
procedure Authenticate_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
User : User_Ref;
Session : Session_Ref;
begin
Data.Manager.Authenticate (Email => To_String (Data.Email),
Password => To_String (Data.Password),
IpAddr => "",
User => User,
Session => Session);
Outcome := To_Unbounded_String ("success");
Data.Set_Session_Principal (User, Session);
exception
when Services.Not_Found =>
Outcome := To_Unbounded_String ("failure");
ASF.Applications.Messages.Factory.Add_Message ("users.login_signup_fail_message");
end Authenticate_User;
-- ------------------------------
-- Logout the user and closes the session.
-- ------------------------------
procedure Logout_User (Data : in out Authenticate_Bean;
Outcome : in out Unbounded_String) is
use type ASF.Principals.Principal_Access;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := Ctx.Get_Session (Create => False);
begin
Outcome := To_Unbounded_String ("success");
-- If there is no session, we are done.
if not Session.Is_Valid then
return;
end if;
declare
Principal : constant ASF.Principals.Principal_Access := Session.Get_Principal;
begin
if Principal /= null and then Principal.all in AWA.Users.Principals.Principal'Class then
declare
P : constant AWA.Users.Principals.Principal_Access :=
AWA.Users.Principals.Principal'Class (Principal.all)'Access;
begin
Data.Manager.Close_Session (Id => P.Get_Session_Identifier);
exception
when others =>
Log.Error ("Exception when closing user session...");
end;
end if;
Session.Invalidate;
end;
-- Remove the session cookie.
declare
C : ASF.Cookies.Cookie := ASF.Cookies.Create ("SID", "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end;
end Logout_User;
-- ------------------------------
-- Create an authenticate bean.
-- ------------------------------
function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Authenticate_Bean_Access := new Authenticate_Bean;
begin
Object.Module := Module;
Object.Manager := AWA.Users.Module.Get_User_Manager;
return Object.all'Access;
end Create_Authenticate_Bean;
-- The code below this line could be generated automatically by an Asis tool.
package Authenticate_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Authenticate_User,
Name => "authenticate");
package Register_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Register_User,
Name => "register");
package Verify_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Verify_User,
Name => "verify");
package Lost_Password_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Lost_Password,
Name => "lostPassword");
package Reset_Password_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Reset_Password,
Name => "resetPassword");
package Logout_Binding is
new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean,
Method => Logout_User,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Authenticate_Binding.Proxy'Access,
Register_Binding.Proxy'Access,
Verify_Binding.Proxy'Access,
Lost_Password_Binding.Proxy'Access,
Reset_Password_Binding.Proxy'Access,
Logout_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Authenticate_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = EMAIL_ATTR then
return Util.Beans.Objects.To_Object (From.Email);
elsif Name = PASSWORD_ATTR then
return Util.Beans.Objects.To_Object (From.Password);
elsif Name = FIRST_NAME_ATTR then
return Util.Beans.Objects.To_Object (From.First_Name);
elsif Name = LAST_NAME_ATTR then
return Util.Beans.Objects.To_Object (From.Last_Name);
elsif Name = KEY_ATTR then
return Util.Beans.Objects.To_Object (From.Access_Key);
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 Authenticate_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = EMAIL_ATTR then
From.Email := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = PASSWORD_ATTR then
From.Password := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = FIRST_NAME_ATTR then
From.First_Name := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = LAST_NAME_ATTR then
From.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = KEY_ATTR then
From.Access_Key := 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 Authenticate_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
end AWA.Users.Beans;
|
Add a global error message if the user authentication failed.
|
Add a global error message if the user authentication failed.
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
70e3cc89880bf567a42a212ffee7d7da132fa3de
|
arch/RISC-V/SiFive/devices/FE310/fe310-device.ads
|
arch/RISC-V/SiFive/devices/FE310/fe310-device.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017, 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 FE310.GPIO; use FE310.GPIO;
with FE310.UART; use FE310.UART;
with FE310.PWM; use FE310.PWM;
with FE310_SVD;
package FE310.Device is
P00 : aliased GPIO_Point (Pin => 00);
P01 : aliased GPIO_Point (Pin => 01);
P02 : aliased GPIO_Point (Pin => 02);
P03 : aliased GPIO_Point (Pin => 03);
P04 : aliased GPIO_Point (Pin => 04);
P05 : aliased GPIO_Point (Pin => 05);
P06 : aliased GPIO_Point (Pin => 06);
P07 : aliased GPIO_Point (Pin => 07);
P08 : aliased GPIO_Point (Pin => 08);
P09 : aliased GPIO_Point (Pin => 09);
P10 : aliased GPIO_Point (Pin => 10);
P11 : aliased GPIO_Point (Pin => 11);
P12 : aliased GPIO_Point (Pin => 12);
P13 : aliased GPIO_Point (Pin => 13);
P14 : aliased GPIO_Point (Pin => 14);
P15 : aliased GPIO_Point (Pin => 15);
P16 : aliased GPIO_Point (Pin => 16);
P17 : aliased GPIO_Point (Pin => 17);
P18 : aliased GPIO_Point (Pin => 18);
P19 : aliased GPIO_Point (Pin => 19);
P20 : aliased GPIO_Point (Pin => 20);
P21 : aliased GPIO_Point (Pin => 21);
P22 : aliased GPIO_Point (Pin => 22);
P23 : aliased GPIO_Point (Pin => 23);
P24 : aliased GPIO_Point (Pin => 24);
P25 : aliased GPIO_Point (Pin => 25);
P26 : aliased GPIO_Point (Pin => 26);
P27 : aliased GPIO_Point (Pin => 27);
P28 : aliased GPIO_Point (Pin => 28);
P29 : aliased GPIO_Point (Pin => 29);
P30 : aliased GPIO_Point (Pin => 30);
P31 : aliased GPIO_Point (Pin => 31);
Internal_UART0 : aliased Internal_UART with Import, Volatile, Address => FE310_SVD.UART0_Base;
Internal_UART1 : aliased Internal_UART with Import, Volatile, Address => FE310_SVD.UART1_Base;
UART0 : aliased UART_Port (Internal_UART0'Access);
UART1 : aliased UART_Port (Internal_UART1'Access);
Internal_PWM0 : aliased Internal_PWM with Import, Volatile, Address => FE310_SVD.PWM0_Base;
Internal_PWM1 : aliased Internal_PWM with Import, Volatile, Address => FE310_SVD.PWM1_Base;
Internal_PWM2 : aliased Internal_PWM with Import, Volatile, Address => FE310_SVD.PWM2_Base;
PWM0 : aliased PWM_Device (Internal_PWM0'Access);
PWM1 : aliased PWM_Device (Internal_PWM1'Access);
PWM2 : aliased PWM_Device (Internal_PWM2'Access);
end FE310.Device;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017, 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 FE310.GPIO; use FE310.GPIO;
with FE310.UART; use FE310.UART;
with FE310.PWM; use FE310.PWM;
with FE310_SVD;
package FE310.Device is
P00 : aliased GPIO_Point (Pin => 00);
P01 : aliased GPIO_Point (Pin => 01);
P02 : aliased GPIO_Point (Pin => 02);
P03 : aliased GPIO_Point (Pin => 03);
P04 : aliased GPIO_Point (Pin => 04);
P05 : aliased GPIO_Point (Pin => 05);
P06 : aliased GPIO_Point (Pin => 06);
P07 : aliased GPIO_Point (Pin => 07);
P08 : aliased GPIO_Point (Pin => 08);
P09 : aliased GPIO_Point (Pin => 09);
P10 : aliased GPIO_Point (Pin => 10);
P11 : aliased GPIO_Point (Pin => 11);
P12 : aliased GPIO_Point (Pin => 12);
P13 : aliased GPIO_Point (Pin => 13);
P14 : aliased GPIO_Point (Pin => 14);
P15 : aliased GPIO_Point (Pin => 15);
P16 : aliased GPIO_Point (Pin => 16);
P17 : aliased GPIO_Point (Pin => 17);
P18 : aliased GPIO_Point (Pin => 18);
P19 : aliased GPIO_Point (Pin => 19);
P20 : aliased GPIO_Point (Pin => 20);
P21 : aliased GPIO_Point (Pin => 21);
P22 : aliased GPIO_Point (Pin => 22);
P23 : aliased GPIO_Point (Pin => 23);
P24 : aliased GPIO_Point (Pin => 24);
P25 : aliased GPIO_Point (Pin => 25);
P26 : aliased GPIO_Point (Pin => 26);
P27 : aliased GPIO_Point (Pin => 27);
P28 : aliased GPIO_Point (Pin => 28);
P29 : aliased GPIO_Point (Pin => 29);
P30 : aliased GPIO_Point (Pin => 30);
P31 : aliased GPIO_Point (Pin => 31);
IOF_UART0 : constant IO_Function := IOF0;
IOF_UART1 : constant IO_Function := IOF0;
IOF_QSPI1 : constant IO_Function := IOF0;
IOF_QSPI2 : constant IO_Function := IOF0;
IOF_PWM0 : constant IO_Function := IOF1;
IOF_PWM1 : constant IO_Function := IOF1;
IOF_PWM2 : constant IO_Function := IOF1;
Internal_UART0 : aliased Internal_UART with Import, Volatile, Address => FE310_SVD.UART0_Base;
Internal_UART1 : aliased Internal_UART with Import, Volatile, Address => FE310_SVD.UART1_Base;
UART0 : aliased UART_Port (Internal_UART0'Access);
UART1 : aliased UART_Port (Internal_UART1'Access);
Internal_PWM0 : aliased Internal_PWM with Import, Volatile, Address => FE310_SVD.PWM0_Base;
Internal_PWM1 : aliased Internal_PWM with Import, Volatile, Address => FE310_SVD.PWM1_Base;
Internal_PWM2 : aliased Internal_PWM with Import, Volatile, Address => FE310_SVD.PWM2_Base;
PWM0 : aliased PWM_Device (Internal_PWM0'Access);
PWM1 : aliased PWM_Device (Internal_PWM1'Access);
PWM2 : aliased PWM_Device (Internal_PWM2'Access);
end FE310.Device;
|
Bring back the IO Functions definitions.
|
Bring back the IO Functions definitions.
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
7e7c1daf7e5d85a09f0238e28839b3b69f91e52f
|
src/wiki-writers-builders.adb
|
src/wiki-writers-builders.adb
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with GNAT.Encode_UTF8_String;
package body Wiki.Writers.Builders is
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, Content);
end Write;
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, To_Wide_Wide_String (Content));
end Write;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Writer_Builder_Type;
Process : not null access procedure (Chunk : in Wide_Wide_String)) is
begin
Wide_Wide_Builders.Iterate (Source.Content, Process);
end Iterate;
-- ------------------------------
-- Convert what was collected in the writer builder to a string and return it.
-- ------------------------------
function To_String (Source : in Writer_Builder_Type) return String is
Pos : Natural := 1;
Result : String (1 .. 5 * Wide_Wide_Builders.Length (Source.Content));
procedure Convert (Chunk : in Wide_Wide_String) is
begin
for I in Chunk'Range loop
GNAT.Encode_UTF8_String.Encode_Wide_Wide_Character (Char => Chunk (I),
Result => Result,
Ptr => Pos);
end loop;
end Convert;
begin
Wide_Wide_Builders.Iterate (Source.Content, Convert'Access);
return Result (1 .. Pos - 1);
end To_String;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write (Writer : in out Writer_Builder_Type;
Char : in Wide_Wide_Character) is
begin
Wide_Wide_Builders.Append (Writer.Content, Char);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write_Char (Writer : in out Writer_Builder_Type;
Char : in Character) is
begin
Wide_Wide_Builders.Append (Writer.Content,
Ada.Characters.Conversions.To_Wide_Wide_Character (Char));
end Write_Char;
-- ------------------------------
-- Write the string to the string builder.
-- ------------------------------
procedure Write_String (Writer : in out Writer_Builder_Type;
Content : in String) is
begin
for I in Content'Range loop
Writer.Write_Char (Content (I));
end loop;
end Write_String;
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Writer_Type'Class;
Char : in Wide_Wide_Character) is
Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_writer_Type'Class) is
begin
if Stream.Close_Start then
Stream.Write_Char ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Writer : in out Html_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Start_Element (Name);
Writer.Write_Wide_Text (Content);
Writer.End_Element (Name);
end Write_Wide_Element;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wide_Wide_String) is
begin
if Writer.Close_Start then
Writer.Write_Char (' ');
Writer.Write_String (Name);
Writer.Write_Char ('=');
Writer.Write_Char ('"');
for I in Content'Range loop
declare
C : constant Wide_Wide_Character := Content (I);
begin
if C = '"' then
Writer.Write_String (""");
else
Writer.Write_Escape (C);
end if;
end;
end loop;
Writer.Write_Char ('"');
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
if Writer.Close_Start then
Writer.Write_Char (' ');
Writer.Write_String (Name);
Writer.Write_Char ('=');
Writer.Write_Char ('"');
for I in 1 .. Count loop
declare
C : constant Wide_Wide_Character := Element (Content, I);
begin
if C = '"' then
Writer.Write_String (""");
else
Writer.Write_Escape (C);
end if;
end;
end loop;
Writer.Write_Char ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Close_Current (Writer);
Writer.Write_Char ('<');
Writer.Write_String (Name);
Writer.Close_Start := True;
end Start_Element;
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
if Writer.Close_Start then
Writer.Write_String (" />");
Writer.Close_Start := False;
else
Close_Current (Writer);
Writer.Write_String ("</");
Writer.Write_String (Name);
Writer.Write_Char ('>');
end if;
end End_Element;
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
Close_Current (Writer);
if Count > 0 then
for I in 1 .. Count loop
Html_Writer_Type'Class (Writer).Write_Escape (Element (Content, I));
end loop;
end if;
end Write_Wide_Text;
end Wiki.Writers.Builders;
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with GNAT.Encode_UTF8_String;
package body Wiki.Writers.Builders is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Writer_Type'Class);
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
procedure Write_Escape (Stream : in out Html_Writer_Type'Class;
Char : in Wide_Wide_Character);
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, Content);
end Write;
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, To_Wide_Wide_String (Content));
end Write;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Writer_Builder_Type;
Process : not null access procedure (Chunk : in Wide_Wide_String)) is
begin
Wide_Wide_Builders.Iterate (Source.Content, Process);
end Iterate;
-- ------------------------------
-- Convert what was collected in the writer builder to a string and return it.
-- ------------------------------
function To_String (Source : in Writer_Builder_Type) return String is
procedure Convert (Chunk : in Wide_Wide_String);
Pos : Natural := 1;
Result : String (1 .. 5 * Wide_Wide_Builders.Length (Source.Content));
procedure Convert (Chunk : in Wide_Wide_String) is
begin
for I in Chunk'Range loop
GNAT.Encode_UTF8_String.Encode_Wide_Wide_Character (Char => Chunk (I),
Result => Result,
Ptr => Pos);
end loop;
end Convert;
begin
Wide_Wide_Builders.Iterate (Source.Content, Convert'Access);
return Result (1 .. Pos - 1);
end To_String;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write (Writer : in out Writer_Builder_Type;
Char : in Wide_Wide_Character) is
begin
Wide_Wide_Builders.Append (Writer.Content, Char);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write_Char (Writer : in out Writer_Builder_Type;
Char : in Character) is
begin
Wide_Wide_Builders.Append (Writer.Content,
Ada.Characters.Conversions.To_Wide_Wide_Character (Char));
end Write_Char;
-- ------------------------------
-- Write the string to the string builder.
-- ------------------------------
procedure Write_String (Writer : in out Writer_Builder_Type;
Content : in String) is
begin
for I in Content'Range loop
Writer.Write_Char (Content (I));
end loop;
end Write_String;
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Writer_Type'Class;
Char : in Wide_Wide_Character) is
Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Writer_Type'Class) is
begin
if Stream.Close_Start then
Stream.Write_Char ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Start_Element (Name);
Writer.Write_Wide_Text (Content);
Writer.End_Element (Name);
end Write_Wide_Element;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wide_Wide_String) is
begin
if Writer.Close_Start then
Writer.Write_Char (' ');
Writer.Write_String (Name);
Writer.Write_Char ('=');
Writer.Write_Char ('"');
for I in Content'Range loop
declare
C : constant Wide_Wide_Character := Content (I);
begin
if C = '"' then
Writer.Write_String (""");
else
Writer.Write_Escape (C);
end if;
end;
end loop;
Writer.Write_Char ('"');
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
if Writer.Close_Start then
Writer.Write_Char (' ');
Writer.Write_String (Name);
Writer.Write_Char ('=');
Writer.Write_Char ('"');
for I in 1 .. Count loop
declare
C : constant Wide_Wide_Character := Element (Content, I);
begin
if C = '"' then
Writer.Write_String (""");
else
Writer.Write_Escape (C);
end if;
end;
end loop;
Writer.Write_Char ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Close_Current (Writer);
Writer.Write_Char ('<');
Writer.Write_String (Name);
Writer.Close_Start := True;
end Start_Element;
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
if Writer.Close_Start then
Writer.Write_String (" />");
Writer.Close_Start := False;
else
Close_Current (Writer);
Writer.Write_String ("</");
Writer.Write_String (Name);
Writer.Write_Char ('>');
end if;
end End_Element;
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
Close_Current (Writer);
if Count > 0 then
for I in 1 .. Count loop
Html_Writer_Type'Class (Writer).Write_Escape (Element (Content, I));
end loop;
end if;
end Write_Wide_Text;
end Wiki.Writers.Builders;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a7931421d1ed31a1a5d9161686c5dd77404ac8d9
|
awa/src/awa-commands.ads
|
awa/src/awa-commands.ads
|
-----------------------------------------------------------------------
-- awa-commands -- AWA commands for server or admin tool
-- Copyright (C) 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Commands;
with AWA.Applications;
private with Keystore.Passwords;
private with Keystore.Passwords.GPG;
private with Util.Commands.Consoles.Text;
private with ASF.Applications;
private with AWA.Applications.Factory;
private with Keystore.Properties;
private with Keystore.Files;
private with Keystore.Passwords.Keys;
private with GNAT.Command_Line;
private with GNAT.Strings;
package AWA.Commands is
Error : exception;
FILL_CONFIG : constant String := "fill-mode";
GPG_CRYPT_CONFIG : constant String := "gpg-encrypt";
GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt";
GPG_LIST_CONFIG : constant String := "gpg-list-keys";
subtype Argument_List is Util.Commands.Argument_List;
type Context_Type is limited new Ada.Finalization.Limited_Controlled with private;
overriding
procedure Initialize (Context : in out Context_Type);
overriding
procedure Finalize (Context : in out Context_Type);
-- Returns True if a keystore is used by the configuration and must be unlocked.
function Use_Keystore (Context : in Context_Type) return Boolean;
-- Open the keystore file using the password password.
procedure Open_Keystore (Context : in out Context_Type);
-- Get the keystore file path.
function Get_Keystore_Path (Context : in out Context_Type) return String;
-- Configure the application by loading its configuration file and merging it with
-- the keystore file if there is one.
procedure Configure (Application : in out AWA.Applications.Application'Class;
Name : in String;
Context : in out Context_Type);
private
function "-" (Message : in String) return String is (Message);
procedure Load_Configuration (Context : in out Context_Type);
package GC renames GNAT.Command_Line;
type Field_Number is range 1 .. 256;
type Notice_Type is (N_USAGE, N_INFO, N_ERROR);
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Number,
Notice_Type => Notice_Type);
package Text_Consoles is
new Consoles.Text;
subtype Justify_Type is Consoles.Justify_Type;
type Context_Type is limited new Ada.Finalization.Limited_Controlled with record
Console : Text_Consoles.Console_Type;
Wallet : aliased Keystore.Files.Wallet_File;
Info : Keystore.Wallet_Info;
Config : Keystore.Wallet_Config := Keystore.Secure_Config;
Secure_Config : Keystore.Properties.Manager;
App_Config : ASF.Applications.Config;
File_Config : ASF.Applications.Config;
Factory : AWA.Applications.Factory.Application_Factory;
Provider : Keystore.Passwords.Provider_Access;
Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access;
Slot : Keystore.Key_Slot;
Version : aliased Boolean := False;
Verbose : aliased Boolean := False;
Debug : aliased Boolean := False;
Dump : aliased Boolean := False;
Zero : aliased Boolean := False;
Config_File : aliased GNAT.Strings.String_Access;
Wallet_File : aliased GNAT.Strings.String_Access;
Data_Path : aliased GNAT.Strings.String_Access;
Wallet_Key_File : aliased GNAT.Strings.String_Access;
Password_File : aliased GNAT.Strings.String_Access;
Password_Env : aliased GNAT.Strings.String_Access;
Unsafe_Password : aliased GNAT.Strings.String_Access;
Password_Socket : aliased GNAT.Strings.String_Access;
Password_Command : aliased GNAT.Strings.String_Access;
Password_Askpass : aliased Boolean := False;
No_Password_Opt : Boolean := False;
Command_Config : GC.Command_Line_Configuration;
First_Arg : Positive := 1;
GPG : Keystore.Passwords.GPG.Context_Type;
end record;
procedure Setup_Password_Provider (Context : in out Context_Type);
procedure Setup_Key_Provider (Context : in out Context_Type);
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Config : in out GC.Command_Line_Configuration;
Context : in out Context_Type);
end AWA.Commands;
|
-----------------------------------------------------------------------
-- awa-commands -- AWA commands for server or admin tool
-- Copyright (C) 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Commands;
with AWA.Applications;
private with Keystore.Passwords;
private with Keystore.Passwords.GPG;
private with Util.Commands.Consoles.Text;
private with ASF.Applications;
private with AWA.Applications.Factory;
private with Keystore.Properties;
private with Keystore.Files;
private with Keystore.Passwords.Keys;
private with GNAT.Command_Line;
private with GNAT.Strings;
package AWA.Commands is
Error : exception;
FILL_CONFIG : constant String := "fill-mode";
GPG_CRYPT_CONFIG : constant String := "gpg-encrypt";
GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt";
GPG_LIST_CONFIG : constant String := "gpg-list-keys";
subtype Argument_List is Util.Commands.Argument_List;
type Context_Type is limited new Ada.Finalization.Limited_Controlled with private;
overriding
procedure Initialize (Context : in out Context_Type);
overriding
procedure Finalize (Context : in out Context_Type);
-- Returns True if a keystore is used by the configuration and must be unlocked.
function Use_Keystore (Context : in Context_Type) return Boolean;
-- Open the keystore file using the password password.
procedure Open_Keystore (Context : in out Context_Type);
-- Get the keystore file path.
function Get_Keystore_Path (Context : in out Context_Type) return String;
-- Configure the application by loading its configuration file and merging it with
-- the keystore file if there is one.
procedure Configure (Application : in out AWA.Applications.Application'Class;
Name : in String;
Context : in out Context_Type);
private
function "-" (Message : in String) return String is (Message);
procedure Load_Configuration (Context : in out Context_Type);
package GC renames GNAT.Command_Line;
type Field_Number is range 1 .. 256;
type Notice_Type is (N_USAGE, N_INFO, N_ERROR);
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Number,
Notice_Type => Notice_Type);
package Text_Consoles is
new Consoles.Text;
subtype Justify_Type is Consoles.Justify_Type;
type Context_Type is limited new Ada.Finalization.Limited_Controlled with record
Console : Text_Consoles.Console_Type;
Wallet : aliased Keystore.Files.Wallet_File;
Info : Keystore.Wallet_Info;
Config : Keystore.Wallet_Config := Keystore.Secure_Config;
Secure_Config : Keystore.Properties.Manager;
App_Config : ASF.Applications.Config;
File_Config : ASF.Applications.Config;
Factory : AWA.Applications.Factory.Application_Factory;
Provider : Keystore.Passwords.Provider_Access;
Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access;
Slot : Keystore.Key_Slot;
Version : aliased Boolean := False;
Verbose : aliased Boolean := False;
Debug : aliased Boolean := False;
Dump : aliased Boolean := False;
Zero : aliased Boolean := False;
Config_File : aliased GNAT.Strings.String_Access;
Wallet_File : aliased GNAT.Strings.String_Access;
Data_Path : aliased GNAT.Strings.String_Access;
Wallet_Key_File : aliased GNAT.Strings.String_Access;
Password_File : aliased GNAT.Strings.String_Access;
Password_Env : aliased GNAT.Strings.String_Access;
Unsafe_Password : aliased GNAT.Strings.String_Access;
Password_Socket : aliased GNAT.Strings.String_Access;
Password_Command : aliased GNAT.Strings.String_Access;
Password_Askpass : aliased Boolean := False;
No_Password_Opt : Boolean := False;
Command_Config : GC.Command_Line_Configuration;
First_Arg : Positive := 1;
GPG : Keystore.Passwords.GPG.Context_Type;
end record;
procedure Setup_Password_Provider (Context : in out Context_Type);
procedure Setup_Key_Provider (Context : in out Context_Type);
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Config : in out GC.Command_Line_Configuration;
Context : in out Context_Type);
function Sys_Daemon (No_Chdir : in Integer; No_Close : in Integer) return Integer
with Import => True, Convention => C, Link_Name => "daemon";
pragma Weak_External (Sys_Daemon);
end AWA.Commands;
|
Declare Sys_Daemon system call as weak symbol
|
Declare Sys_Daemon system call as weak symbol
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
9467a3c00dc44738d93780875d916a3f157b52d1
|
src/wiki-parsers-html.adb
|
src/wiki-parsers-html.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package body Wiki.Parsers.Html is
use Ada.Strings.Wide_Wide_Unbounded;
procedure Collect_Attributes (P : in out Parser);
function Is_Space (C : in Wide_Wide_Character) return Boolean;
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return C = ' ' or C = LF or C = CR;
end Is_Space;
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
procedure Skip_Spaces (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if not Is_Space (C) then
Put_Back (P, C);
return;
end if;
end loop;
end Skip_Spaces;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Quote : in Wide_Wide_Character;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = Quote;
Append (Value, C);
end loop;
end Collect_Attribute_Value;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
Token : Wide_Wide_Character;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
begin
Peek (P, C);
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Name);
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Name, P.Attributes);
End_Element (P, Name);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Name, P.Attributes);
end if;
end Parse_Element;
end Wiki.Parsers.Html;
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
package body Wiki.Parsers.Html is
use Ada.Strings.Wide_Wide_Unbounded;
procedure Collect_Attributes (P : in out Parser);
function Is_Space (C : in Wide_Wide_Character) return Boolean;
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return C = ' ' or C = LF or C = CR;
end Is_Space;
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
procedure Skip_Spaces (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
if not Is_Space (C) then
Put_Back (P, C);
return;
end if;
end loop;
end Skip_Spaces;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
Token : Wide_Wide_Character;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
begin
Peek (P, C);
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Name);
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Name, P.Attributes);
End_Element (P, Name);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Name, P.Attributes);
end if;
end Parse_Element;
end Wiki.Parsers.Html;
|
Remove unused procedure
|
Remove unused procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
99d2b6a8e2e7f67986de9ee8d5d20e270b9adfb7
|
awa/regtests/awa-users-tests.adb
|
awa/regtests/awa-users-tests.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Test_Caller;
with ASF.Tests;
with AWA.Tests;
with AWA.Users.Models;
with AWA.Users.Services.Tests.Helpers;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
package body AWA.Users.Tests is
use ASF.Tests;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of user by simulating web requests.
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "Joe-" & Util.Tests.Get_UUID & "@gmail.com";
Principal : Services.Tests.Helpers.Test_User;
begin
Services.Tests.Helpers.Initialize (Principal);
Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("password", "asdf");
Request.Set_Parameter ("password2", "asdf");
Request.Set_Parameter ("firstName", "joe");
Request.Set_Parameter ("lastName", "dalton");
Request.Set_Parameter ("register", "1");
Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
-- Now, get the access key and simulate a click on the validation link.
declare
Key : AWA.Users.Models.Access_Key_Ref;
begin
Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
Request.Set_Parameter ("key", Key.Get_Access_Key);
Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
end;
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Create_User;
procedure Test_Logout_User (T : in out Test) is
begin
null;
end Test_Logout_User;
-- ------------------------------
-- Test user authentication by simulating a web request.
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Principal :Services.Tests.Helpers.Test_User;
begin
AWA.Tests.Set_Application_Context;
Services.Tests.Helpers.Create_User (Principal, "[email protected]");
Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("login", "1");
Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Login_User;
-- ------------------------------
-- Test the reset password by simulating web requests.
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "[email protected]";
begin
Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("lost-password", "1");
Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Now, get the access key and simulate a click on the reset password link.
declare
Principal : Services.Tests.Helpers.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Set_Application_Context;
Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
-- Simulate user clicking on the reset password link.
-- This verifies the key, login the user and redirect him to the change-password page
Request.Set_Parameter ("key", Key.Get_Access_Key);
Do_Get (Request, Reply, "/auth/reset-password.html", "reset-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Post the reset password
Request.Set_Parameter ("password", "asd");
Request.Set_Parameter ("reset-password", "1");
Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is logged and we have a user principal now.
t.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end;
end Test_Reset_Password_User;
end AWA.Users.Tests;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Test_Caller;
with ASF.Tests;
with AWA.Tests;
with AWA.Users.Models;
with AWA.Users.Services.Tests.Helpers;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
package body AWA.Users.Tests is
use ASF.Tests;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of user by simulating web requests.
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "Joe-" & Util.Tests.Get_UUID & "@gmail.com";
Principal : Services.Tests.Helpers.Test_User;
begin
Services.Tests.Helpers.Initialize (Principal);
Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("password", "asdf");
Request.Set_Parameter ("password2", "asdf");
Request.Set_Parameter ("firstName", "joe");
Request.Set_Parameter ("lastName", "dalton");
Request.Set_Parameter ("register", "1");
Request.Set_Parameter ("register-button", "1");
Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
-- Now, get the access key and simulate a click on the validation link.
declare
Key : AWA.Users.Models.Access_Key_Ref;
begin
Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
Request.Set_Parameter ("key", Key.Get_Access_Key);
Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
end;
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Create_User;
procedure Test_Logout_User (T : in out Test) is
begin
null;
end Test_Logout_User;
-- ------------------------------
-- Test user authentication by simulating a web request.
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Principal :Services.Tests.Helpers.Test_User;
begin
AWA.Tests.Set_Application_Context;
Services.Tests.Helpers.Create_User (Principal, "[email protected]");
Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("login", "1");
Request.Set_Parameter ("login-button", "1");
Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Login_User;
-- ------------------------------
-- Test the reset password by simulating web requests.
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "[email protected]";
begin
Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("lost-password", "1");
Request.Set_Parameter ("lost-password-button", "1");
Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Now, get the access key and simulate a click on the reset password link.
declare
Principal : Services.Tests.Helpers.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Set_Application_Context;
Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
-- Simulate user clicking on the reset password link.
-- This verifies the key, login the user and redirect him to the change-password page
Request.Set_Parameter ("key", Key.Get_Access_Key);
Do_Get (Request, Reply, "/auth/reset-password.html", "reset-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Post the reset password
Request.Set_Parameter ("password", "asd");
Request.Set_Parameter ("reset-password", "1");
Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is logged and we have a user principal now.
t.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end;
end Test_Reset_Password_User;
end AWA.Users.Tests;
|
Fix unit test after changes in XHTML files
|
Fix unit test after changes in XHTML files
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
e10b7fee8cc224479d7d301223f7cf14956f463f
|
src/lzma/util-streams-buffered-lzma.adb
|
src/lzma/util-streams-buffered-lzma.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Lzma;
package body Util.Streams.Buffered.Lzma is
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
procedure Initialize (Stream : in out Compress_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String) is
begin
Stream.Initialize (Output, Size);
Stream.Transform := new Util.Encoders.Lzma.Compress;
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
First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First;
Last_Encoded : Ada.Streams.Stream_Element_Offset;
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
while First_Encoded <= Buffer'Last loop
Stream.Transform.Transform
(Data => Buffer (First_Encoded .. Buffer'Last),
Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last => Last_Pos,
Encoded => Last_Encoded);
if Last_Pos + 1 >= Stream.Buffer'Last then
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Write_Pos := Stream.Buffer'First;
else
Stream.Write_Pos := Last_Pos + 1;
end if;
First_Encoded := Last_Encoded + 1;
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Compress_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1;
begin
loop
Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last_Pos);
Stream.Write_Pos := Last_Pos + 1;
Output_Buffer_Stream (Stream).Flush;
exit when Stream.Write_Pos < Stream.Buffer'Last;
Stream.Write_Pos := 1;
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Lzma;
package body Util.Streams.Buffered.Lzma is
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
procedure Initialize (Stream : in out Compress_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String) is
pragma Unreferenced (Format);
begin
Stream.Initialize (Output, Size);
Stream.Transform := new Util.Encoders.Lzma.Compress;
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
First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First;
Last_Encoded : Ada.Streams.Stream_Element_Offset;
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
while First_Encoded <= Buffer'Last loop
Stream.Transform.Transform
(Data => Buffer (First_Encoded .. Buffer'Last),
Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last => Last_Pos,
Encoded => Last_Encoded);
if Last_Pos + 1 >= Stream.Buffer'Last then
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Write_Pos := Stream.Buffer'First;
else
Stream.Write_Pos := Last_Pos + 1;
end if;
First_Encoded := Last_Encoded + 1;
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Compress_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1;
begin
loop
Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last_Pos);
Stream.Write_Pos := Last_Pos + 1;
Output_Buffer_Stream (Stream).Flush;
exit when Stream.Write_Pos < Stream.Buffer'Last;
Stream.Write_Pos := 1;
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;
|
Fix compilation warning, unused Format parameter
|
Fix compilation warning, unused Format parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e0591b32b8ce3e48e93547ff7c526f160b544133
|
awa/awaunit/awa-tests.adb
|
awa/awaunit/awa-tests.adb
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
with AWA.Tests.Helpers.Users;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
-- ------------------------------
-- Cleanup after the test execution.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
begin
AWA.Tests.Helpers.Users.Tear_Down;
end Tear_Down;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
pragma Unreferenced (Add_Modules);
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
Application.Start;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access);
end Initialize_Filters;
end AWA.Tests;
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
with AWA.Tests.Helpers.Users;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
-- ------------------------------
-- Cleanup after the test execution.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
pragma Unreferenced (T);
begin
AWA.Tests.Helpers.Users.Tear_Down;
end Tear_Down;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
pragma Unreferenced (Add_Modules);
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
Application.Start;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access);
end Initialize_Filters;
end AWA.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f78a94ea0ea6fd415e0033b1066391fd0d49b192
|
tests/natools-smaz_tests.adb
|
tests/natools-smaz_tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2016, 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.Characters.Latin_1;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Natools.S_Expressions;
with Natools.Smaz_256;
with Natools.Smaz_64;
with Natools.Smaz_Generic;
with Natools.Smaz_Original;
with Natools.Smaz_Test_Base_64_Hash;
package body Natools.Smaz_Tests is
generic
with package Smaz is new Natools.Smaz_Generic (<>);
with function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Generic_Roundtrip_Test
(Test : in out NT.Test;
Dict : in Smaz.Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String;
function Direct_Image (S : Ada.Streams.Stream_Element_Array) return String
renames Natools.S_Expressions.To_String;
function To_SEA (S : String) return Ada.Streams.Stream_Element_Array
renames Natools.S_Expressions.To_Atom;
-----------------------
-- Test Dictionaries --
-----------------------
LF : constant Character := Ada.Characters.Latin_1.LF;
Dict_64 : constant Natools.Smaz_64.Dictionary
:= (Last_Code => 59,
Values_Last => 119,
Variable_Length_Verbatim => False,
Max_Word_Length => 6,
Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22,
24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53,
56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98,
101, 102, 103, 105, 111, 112, 114, 115, 118),
Values => " ee stainruos l dt enescm pépd de lere ld"
& "e" & LF & "on cqumede mentes aiquen teerou r sque , is m q"
& "ueà v'tiweblogfanj." & LF & LF & "ch",
Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String
is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Decimal_Image;
procedure Generic_Roundtrip_Test
(Test : in out NT.Test;
Dict : in Smaz.Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
begin
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant Ada.Streams.Stream_Element_Array
:= Smaz.Compress (Dict, Decompressed);
begin
First_OK := True;
if Buffer /= Compressed then
Test.Fail ("Bad compression of """ & Decompressed & '"');
Test.Info ("Found: " & Image (Buffer));
Test.Info ("Expected:" & Image (Compressed));
declare
Round : constant String
:= Smaz.Decompress (Dict, Buffer);
begin
if Round /= Decompressed then
Test.Info ("Roundtrip failed, got: """ & Round & '"');
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of """ & Decompressed & '"');
end if;
Test.Report_Exception (Error, NT.Fail);
end;
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant String
:= Smaz.Decompress (Dict, Compressed);
begin
First_OK := True;
if Buffer /= Decompressed then
Test.Fail ("Bad decompression of " & Image (Compressed));
Test.Info ("Found: """ & Buffer & '"');
Test.Info ("Expected:""" & Decompressed & '"');
declare
Round : constant Ada.Streams.Stream_Element_Array
:= Smaz.Compress (Dict, Buffer);
begin
if Round /= Compressed then
Test.Info ("Roundtrip failed, got: " & Image (Round));
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of " & Image (Compressed));
end if;
Test.Report_Exception (Error, NT.Fail);
end;
end Generic_Roundtrip_Test;
procedure Roundtrip_Test is new Generic_Roundtrip_Test
(Natools.Smaz_256, Decimal_Image);
procedure Roundtrip_Test is new Generic_Roundtrip_Test
(Natools.Smaz_64, Direct_Image);
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Report.Section ("Base 256");
All_Tests_256 (Report);
Report.End_Section;
Report.Section ("Base 64");
All_Tests_64 (Report);
Report.End_Section;
end All_Tests;
------------------------------
-- Test Suite for Each Base --
------------------------------
procedure All_Tests_256 (Report : in out NT.Reporter'Class) is
begin
Test_Validity_256 (Report);
Sample_Strings_256 (Report);
end All_Tests_256;
procedure All_Tests_64 (Report : in out NT.Reporter'Class) is
begin
Test_Validity_64 (Report);
Sample_Strings_64 (Report);
end All_Tests_64;
-------------------------------
-- Individual Base-256 Tests --
-------------------------------
procedure Sample_Strings_256 (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109,
112, 108, 51, 51, 51));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
": : : :",
(255, 6, 58, 32, 58, 32, 58, 32, 58));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings_256;
procedure Test_Validity_256 (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Test dictionary validity");
begin
if not Natools.Smaz_256.Is_Valid (Smaz_Original.Dictionary) then
Test.Fail;
end if;
exception
when Error : others => Test.Report_Exception (Error);
end Test_Validity_256;
------------------------------
-- Individual Base-64 Tests --
------------------------------
procedure Sample_Strings_64 (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Dict_64,
"Simple Test",
To_SEA ("+TBGSVYA+UBQE"));
-- <S>imp* <T>*t
Roundtrip_Test (Test, Dict_64,
"SiT",
To_SEA ("/ATlGV"));
-- <SiT> smaller than <S>i<T> ("+TBG+UB")
Roundtrip_Test (Test, Dict_64,
"sIMple TEST_WITH_14_B",
To_SEA ("D9J1EVYA8UVETR1XXlEVI9VM08lQ"));
-- s<IM>p* <TE ST_ WIT H_1 4_B>
-- TE 001010_10 1010_0010 00
-- ST_ 110010_10 0010_1010 11_111010
-- WIT 111010_10 1001_0010 00_101010
-- H_1 000100_10 1111_1010 10_001100
-- 4_B 001011_00 1111_1010 01_000010
Roundtrip_Test (Test, Dict_64,
"'7B_Verbatim'",
To_SEA ("0+3IC9lVlJnYF1S0"));
-- '<7B_Verb >a*m'
-- 7 111011_00 0100
-- B_V 010000_10 1111_1010 01_101010
-- erb 101001_10 0100_1110 01_000110
-- "erb" could have been encoded separately as "o+iB", which has
-- the same length, but the tie is broken in favor of the longer
-- verbatim fragment to help with corner cases.
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings_64;
procedure Test_Validity_64 (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Test dictionary validity");
begin
if not Natools.Smaz_64.Is_Valid (Dict_64) then
Test.Fail;
end if;
exception
when Error : others => Test.Report_Exception (Error);
end Test_Validity_64;
end Natools.Smaz_Tests;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2016, 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.Characters.Latin_1;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Natools.S_Expressions;
with Natools.Smaz_256;
with Natools.Smaz_64;
with Natools.Smaz_Generic;
with Natools.Smaz_Original;
with Natools.Smaz_Test_Base_64_Hash;
package body Natools.Smaz_Tests is
generic
with package Smaz is new Natools.Smaz_Generic (<>);
with function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Generic_Roundtrip_Test
(Test : in out NT.Test;
Dict : in Smaz.Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String;
function Direct_Image (S : Ada.Streams.Stream_Element_Array) return String
renames Natools.S_Expressions.To_String;
function To_SEA (S : String) return Ada.Streams.Stream_Element_Array
renames Natools.S_Expressions.To_Atom;
-----------------------
-- Test Dictionaries --
-----------------------
LF : constant Character := Ada.Characters.Latin_1.LF;
Dict_64 : constant Natools.Smaz_64.Dictionary
:= (Last_Code => 59,
Values_Last => 119,
Variable_Length_Verbatim => False,
Max_Word_Length => 6,
Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22,
24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53,
56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98,
101, 102, 103, 105, 111, 112, 114, 115, 118),
Values => " ee stainruos l dt enescm pépd de lere ld"
& "e" & LF & "on cqumede mentes aiquen teerou r sque , is m q"
& "ueà v'tiweblogfanj." & LF & LF & "ch",
Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String
is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Decimal_Image;
procedure Generic_Roundtrip_Test
(Test : in out NT.Test;
Dict : in Smaz.Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
begin
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant Ada.Streams.Stream_Element_Array
:= Smaz.Compress (Dict, Decompressed);
begin
First_OK := True;
if Buffer /= Compressed then
Test.Fail ("Bad compression of """ & Decompressed & '"');
Test.Info ("Found: " & Image (Buffer));
Test.Info ("Expected:" & Image (Compressed));
declare
Round : constant String
:= Smaz.Decompress (Dict, Buffer);
begin
if Round /= Decompressed then
Test.Info ("Roundtrip failed, got: """ & Round & '"');
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of """ & Decompressed & '"');
end if;
Test.Report_Exception (Error, NT.Fail);
end;
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant String
:= Smaz.Decompress (Dict, Compressed);
begin
First_OK := True;
if Buffer /= Decompressed then
Test.Fail ("Bad decompression of " & Image (Compressed));
Test.Info ("Found: """ & Buffer & '"');
Test.Info ("Expected:""" & Decompressed & '"');
declare
Round : constant Ada.Streams.Stream_Element_Array
:= Smaz.Compress (Dict, Buffer);
begin
if Round /= Compressed then
Test.Info ("Roundtrip failed, got: " & Image (Round));
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During decompression of " & Image (Compressed));
end if;
Test.Report_Exception (Error, NT.Fail);
end;
end Generic_Roundtrip_Test;
procedure Roundtrip_Test is new Generic_Roundtrip_Test
(Natools.Smaz_256, Decimal_Image);
procedure Roundtrip_Test is new Generic_Roundtrip_Test
(Natools.Smaz_64, Direct_Image);
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Report.Section ("Base 256");
All_Tests_256 (Report);
Report.End_Section;
Report.Section ("Base 64");
All_Tests_64 (Report);
Report.End_Section;
end All_Tests;
------------------------------
-- Test Suite for Each Base --
------------------------------
procedure All_Tests_256 (Report : in out NT.Reporter'Class) is
begin
Test_Validity_256 (Report);
Sample_Strings_256 (Report);
end All_Tests_256;
procedure All_Tests_64 (Report : in out NT.Reporter'Class) is
begin
Test_Validity_64 (Report);
Sample_Strings_64 (Report);
end All_Tests_64;
-------------------------------
-- Individual Base-256 Tests --
-------------------------------
procedure Sample_Strings_256 (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109,
112, 108, 51, 51, 51));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
Roundtrip_Test (Test, Smaz_Original.Dictionary,
": : : :",
(255, 6, 58, 32, 58, 32, 58, 32, 58));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings_256;
procedure Test_Validity_256 (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Test dictionary validity");
begin
if not Natools.Smaz_256.Is_Valid (Smaz_Original.Dictionary) then
Test.Fail;
end if;
exception
when Error : others => Test.Report_Exception (Error);
end Test_Validity_256;
------------------------------
-- Individual Base-64 Tests --
------------------------------
procedure Sample_Strings_64 (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Dict_64,
"Simple Test",
To_SEA ("+TBGSVYA+UBQE"));
-- <S>imp* <T>*t
Roundtrip_Test (Test, Dict_64,
"SiT",
To_SEA ("/ATlGV"));
-- <SiT> smaller than <S>i<T> ("+TBG+UB")
Roundtrip_Test (Test, Dict_64,
"sIMple TEST_WITH_14_B",
To_SEA ("D9J1EVYA8UVETR1XXlEVI9VM08lQ"));
-- s<IM>p* <TE ST_ WIT H_1 4_B>
-- TE 001010_10 1010_0010 00
-- ST_ 110010_10 0010_1010 11_111010
-- WIT 111010_10 1001_0010 00_101010
-- H_1 000100_10 1111_1010 10_001100
-- 4_B 001011_00 1111_1010 01_000010
Roundtrip_Test (Test, Dict_64,
"'7B_Verbatim'",
To_SEA ("0+3IC9lVlJnYF1S0"));
-- '<7B_Verb >a*m'
-- 7 111011_00 0100
-- B_V 010000_10 1111_1010 01_101010
-- erb 101001_10 0100_1110 01_000110
-- "erb" could have been encoded separately as "o+iB", which has
-- the same length, but the tie is broken in favor of the longer
-- verbatim fragment to help with corner cases.
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings_64;
procedure Test_Validity_64 (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Test dictionary validity");
begin
if not Natools.Smaz_64.Is_Valid (Dict_64) then
Test.Fail;
end if;
exception
when Error : others => Test.Report_Exception (Error);
end Test_Validity_64;
end Natools.Smaz_Tests;
|
fix message of exceptions during decompression roundtrip
|
smaz_tests: fix message of exceptions during decompression roundtrip
|
Ada
|
isc
|
faelys/natools
|
a255fa6d2ad172df9fdd2fc65c8c69a79daee178
|
examples/HiFive1/src/main.adb
|
examples/HiFive1/src/main.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017-2018, AdaCore and other contributors --
-- See https://github.com/AdaCore/Ada_Drivers_Library/graphs/contributors --
-- for more information --
-- --
-- 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 FE310;
with HiFive1.LEDs; use HiFive1.LEDs;
with FE310.Time; use FE310.Time;
procedure Main is
begin
FE310.Set_SPI_Flash_Clock_Divider (2);
FE310.Load_Internal_Oscilator_Calibration;
FE310.Use_Crystal_Oscillator;
HiFive1.LEDs.Initialize;
-- Blinky!
loop
Turn_On (Red_LED);
Delay_S (1);
Turn_Off (Red_LED);
Turn_On (Green_LED);
Delay_S (1);
Turn_Off (Green_LED);
Turn_On (Blue_LED);
Delay_S (1);
Turn_Off (Blue_LED);
end loop;
end Main;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017-2018, AdaCore and other contributors --
-- See https://github.com/AdaCore/Ada_Drivers_Library/graphs/contributors --
-- for more information --
-- --
-- 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 FE310;
with HiFive1.LEDs; use HiFive1.LEDs;
with FE310.Time; use FE310.Time;
procedure Main is
begin
-- The SPI flash clock divider should be as small as possible to increase
-- the execution speed of instructions that are not yet in the instruction
-- cache.
FE310.Set_SPI_Flash_Clock_Divider (2);
-- Load the internal oscillator factory calibration to be sure it
-- oscillates at a known frequency.
FE310.Load_Internal_Oscilator_Calibration;
-- Use the HiFive1 16 MHz crystal oscillator which is more acurate than the
-- internal oscollator.
FE310.Use_Crystal_Oscillator;
HiFive1.LEDs.Initialize;
-- Blinky!
loop
Turn_On (Red_LED);
Delay_S (1);
Turn_Off (Red_LED);
Turn_On (Green_LED);
Delay_S (1);
Turn_Off (Green_LED);
Turn_On (Blue_LED);
Delay_S (1);
Turn_Off (Blue_LED);
end loop;
end Main;
|
Add comments in the HiFive1 example.
|
Add comments in the HiFive1 example.
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
2e9fe38635ecd234b8040843cf0e4a32fd02374f
|
src/ado-drivers-dialects.adb
|
src/ado-drivers-dialects.adb
|
-----------------------------------------------------------------------
-- ADO Dialects -- Driver support for basic SQL Generation
-- Copyright (C) 2010, 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ADO.Drivers.Dialects is
-- --------------------
-- Get the quote character to escape an identifier.
-- --------------------
function Get_Identifier_Quote (D : in Dialect) return Character is
pragma Unreferenced (D);
begin
return '`';
end Get_Identifier_Quote;
-- ------------------------------
-- Append the item in the buffer escaping some characters if necessary.
-- The default implementation only escapes the single quote ' by doubling them.
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in String) is
pragma Unreferenced (D);
C : Character;
begin
Append (Buffer, ''');
for I in Item'Range loop
C := Item (I);
if C = ''' then
Append (Buffer, ''');
end if;
Append (Buffer, C);
end loop;
Append (Buffer, ''');
end Escape_Sql;
-- ------------------------------
-- Append the item in the buffer escaping some characters if necessary
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in ADO.Blob_Ref) is
pragma Unreferenced (D);
C : Ada.Streams.Stream_Element;
Blob : constant ADO.Blob_Access := Item.Value;
begin
Append (Buffer, ''');
for I in Blob.Data'Range loop
C := Blob.Data (I);
case C is
when Character'Pos (ASCII.NUL) =>
Append (Buffer, '\');
Append (Buffer, '0');
when Character'Pos (ASCII.CR) =>
Append (Buffer, '\');
Append (Buffer, 'r');
when Character'Pos (ASCII.LF) =>
Append (Buffer, '\');
Append (Buffer, 'n');
when Character'Pos ('\') | Character'Pos (''') | Character'Pos ('"') =>
Append (Buffer, '\');
Append (Buffer, Character'Val (C));
when others =>
Append (Buffer, Character'Val (C));
end case;
end loop;
Append (Buffer, ''');
end Escape_Sql;
-- ------------------------------
-- Append the boolean item in the buffer.
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in Boolean) is
pragma Unreferenced (D);
begin
Append (Buffer, (if Item then '1' else '0'));
end Escape_Sql;
end ADO.Drivers.Dialects;
|
-----------------------------------------------------------------------
-- ADO Dialects -- Driver support for basic SQL Generation
-- Copyright (C) 2010, 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ADO.Drivers.Dialects is
-- ------------------------------
-- Append the item in the buffer escaping some characters if necessary.
-- The default implementation only escapes the single quote ' by doubling them.
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in String) is
pragma Unreferenced (D);
C : Character;
begin
Append (Buffer, ''');
for I in Item'Range loop
C := Item (I);
if C = ''' then
Append (Buffer, ''');
end if;
Append (Buffer, C);
end loop;
Append (Buffer, ''');
end Escape_Sql;
-- ------------------------------
-- Append the item in the buffer escaping some characters if necessary
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in ADO.Blob_Ref) is
pragma Unreferenced (D);
C : Ada.Streams.Stream_Element;
Blob : constant ADO.Blob_Access := Item.Value;
begin
Append (Buffer, ''');
for I in Blob.Data'Range loop
C := Blob.Data (I);
case C is
when Character'Pos (ASCII.NUL) =>
Append (Buffer, '\');
Append (Buffer, '0');
when Character'Pos (ASCII.CR) =>
Append (Buffer, '\');
Append (Buffer, 'r');
when Character'Pos (ASCII.LF) =>
Append (Buffer, '\');
Append (Buffer, 'n');
when Character'Pos ('\') | Character'Pos (''') | Character'Pos ('"') =>
Append (Buffer, '\');
Append (Buffer, Character'Val (C));
when others =>
Append (Buffer, Character'Val (C));
end case;
end loop;
Append (Buffer, ''');
end Escape_Sql;
-- ------------------------------
-- Append the boolean item in the buffer.
-- ------------------------------
procedure Escape_Sql (D : in Dialect;
Buffer : in out Unbounded_String;
Item : in Boolean) is
pragma Unreferenced (D);
begin
Append (Buffer, (if Item then '1' else '0'));
end Escape_Sql;
end ADO.Drivers.Dialects;
|
Remove Get_Identifier_Quote because it is now abstract
|
Remove Get_Identifier_Quote because it is now abstract
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
1d3f927fe7b493ec3f54c9f9d16b79ee771fe96c
|
mat/src/mat-formats.adb
|
mat/src/mat-formats.adb
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : Boolean := True;
Conversion : constant String (1 .. 10) := "0123456789";
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the time relative to the start time.
-- ------------------------------
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- Format a file, line, function information into a string.
-- ------------------------------
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is
begin
case Item.Index is
when MAT.Events.Targets.MSG_MALLOC =>
return Size (Item.Size) & " bytes allocated";
when MAT.Events.Targets.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.Targets.MSG_FREE =>
return Size (Item.Size) & " bytes freed";
when others =>
return "unknown";
end case;
end Event;
function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First;
Free_Event : MAT.Events.Targets.Probe_Event_Type;
begin
Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE);
return Size (Item.Size) & " bytes allocated, @" & Duration (Free_Event.Time - Start_Time)
& " freed " & Duration (Free_Event.Time - Item.Time) & " after"
;
exception
when MAT.Events.Targets.Not_Found =>
return Size (Item.Size) & " bytes allocated";
end Event_Malloc;
-- Format a short description of the event.
function Event (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
case Item.Index is
when MAT.Events.Targets.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.Targets.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.Targets.MSG_FREE =>
return Size (Item.Size) & " bytes freed";
when MAT.Events.Targets.MSG_BEGIN =>
return "Begin event";
when MAT.Events.Targets.MSG_END =>
return "End event";
when MAT.Events.Targets.MSG_LIBRARY =>
return "Library information event";
when others =>
return "unknown";
end case;
end Event;
end MAT.Formats;
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : Boolean := True;
Conversion : constant String (1 .. 10) := "0123456789";
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the time relative to the start time.
-- ------------------------------
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- Format a file, line, function information into a string.
-- ------------------------------
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is
begin
case Item.Index is
when MAT.Events.Targets.MSG_MALLOC =>
return Size (Item.Size) & " bytes allocated";
when MAT.Events.Targets.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.Targets.MSG_FREE =>
return Size (Item.Size) & " bytes freed";
when others =>
return "unknown";
end case;
end Event;
function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First;
Free_Event : MAT.Events.Targets.Probe_Event_Type;
begin
Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE);
return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time)
& ", freed by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id)
& " after " & Duration (Free_Event.Time - Item.Time)
;
exception
when MAT.Events.Targets.Not_Found =>
return Size (Item.Size) & " bytes allocated";
end Event_Malloc;
function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First;
Alloc_Event : MAT.Events.Targets.Probe_Event_Type;
begin
Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC);
return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time)
& ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time)
& " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id)
;
exception
when MAT.Events.Targets.Not_Found =>
return Size (Item.Size) & " bytes freed";
end Event_Free;
-- Format a short description of the event.
function Event (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
case Item.Index is
when MAT.Events.Targets.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.Targets.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.Targets.MSG_FREE =>
return Event_Free (Item, Related, Start_Time);
when MAT.Events.Targets.MSG_BEGIN =>
return "Begin event";
when MAT.Events.Targets.MSG_END =>
return "End event";
when MAT.Events.Targets.MSG_LIBRARY =>
return "Library information event";
when others =>
return "unknown";
end case;
end Event;
end MAT.Formats;
|
Print information about the alloc/free events related to some allocation
|
Print information about the alloc/free events related to some allocation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
c0922e215172a19b6291540916346ff28865de54
|
mat/src/mat-readers.ads
|
mat/src/mat-readers.ads
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with System;
with Util.Properties;
with MAT.Types;
with MAT.Events;
package MAT.Readers is
type Buffer_Type is private;
type Buffer_Ptr is access all Buffer_Type;
type Message is record
Kind : MAT.Events.Event_Type;
Size : Natural;
Buffer : Buffer_Ptr;
end record;
-----------------
-- Abstract servant definition
-----------------
-- The Servant is a small proxy that binds the specific message
-- handlers to the client specific dispatcher.
type Reader_Base is abstract tagged limited private;
type Reader_Access is access all Reader_Base'Class;
procedure Dispatch (For_Servant : in out Reader_Base;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out Message) is abstract;
-- Dispatch the message
-- procedure Bind (For_Servant : in out Reader_Base) is abstract;
-- Bind the servant with the object adapter to register the
-- events it recognizes. This is called once we have all the
-- information about the structures of events that we can
-- receive.
-----------------
-- Ipc Client Manager
-----------------
-- The Manager is a kind of object adapter. It registers a collection
-- of servants and dispatches incomming messages to those servants.
type Manager_Base is tagged limited private;
type Manager is access all Manager_Base'Class;
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message);
private
type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN);
type Buffer_Type is record
Current : System.Address;
Start : System.Address;
Last : System.Address;
Size : Natural;
Total : Natural;
Endian : Endian_Type := LITTLE_ENDIAN;
end record;
type Reader_Base is abstract tagged limited record
Owner : Manager := null;
end record;
-- Record a servant
type Message_Handler is record
For_Servant : Reader_Access;
Id : MAT.Events.Internal_Reference;
Attributes : MAT.Events.Const_Attribute_Table_Access;
Mapping : MAT.Events.Attribute_Table_Ptr;
end record;
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type;
use type MAT.Types.Uint16;
package Reader_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Message_Handler,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Runtime handlers associated with the events.
package Handler_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16,
Element_Type => Message_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Manager_Base is tagged limited record
Readers : Reader_Maps.Map;
Handlers : Handler_Maps.Map;
Version : MAT.Types.Uint16;
Flags : MAT.Types.Uint16;
Probe : MAT.Events.Attribute_Table_Ptr;
Frame : access MAT.Events.Frame_Info;
end record;
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message);
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message);
end MAT.Readers;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with System;
with Util.Properties;
with MAT.Types;
with MAT.Events;
package MAT.Readers is
type Buffer_Type is private;
type Buffer_Ptr is access all Buffer_Type;
type Message is record
Kind : MAT.Events.Event_Type;
Size : Natural;
Buffer : Buffer_Ptr;
end record;
-----------------
-- Abstract servant definition
-----------------
-- The Servant is a small proxy that binds the specific message
-- handlers to the client specific dispatcher.
type Reader_Base is abstract tagged limited private;
type Reader_Access is access all Reader_Base'Class;
procedure Dispatch (For_Servant : in out Reader_Base;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out Message) is abstract;
-- Dispatch the message
-- procedure Bind (For_Servant : in out Reader_Base) is abstract;
-- Bind the servant with the object adapter to register the
-- events it recognizes. This is called once we have all the
-- information about the structures of events that we can
-- receive.
-----------------
-- Ipc Client Manager
-----------------
-- The Manager is a kind of object adapter. It registers a collection
-- of servants and dispatches incomming messages to those servants.
type Manager_Base is tagged limited private;
type Manager is access all Manager_Base'Class;
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message);
private
type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN);
type Buffer_Type is record
Current : System.Address;
Start : System.Address;
Last : System.Address;
Size : Natural;
Total : Natural;
Endian : Endian_Type := LITTLE_ENDIAN;
end record;
type Reader_Base is abstract tagged limited record
Owner : Manager := null;
end record;
-- Record a servant
type Message_Handler is record
For_Servant : Reader_Access;
Id : MAT.Events.Internal_Reference;
Attributes : MAT.Events.Const_Attribute_Table_Access;
Mapping : MAT.Events.Attribute_Table_Ptr;
end record;
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type;
use type MAT.Types.Uint16;
package Reader_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Message_Handler,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Runtime handlers associated with the events.
package Handler_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16,
Element_Type => Message_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Manager_Base is tagged limited record
Readers : Reader_Maps.Map;
Handlers : Handler_Maps.Map;
Version : MAT.Types.Uint16;
Flags : MAT.Types.Uint16;
Probe : MAT.Events.Attribute_Table_Ptr;
Frame : access MAT.Events.Frame_Info;
end record;
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message);
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message);
-- Read a list of event definitions from the stream and configure the reader.
procedure Read_Event_Definitions (Client : in out Manager_Base;
Msg : in out Message);
end MAT.Readers;
|
Declare the Read_Event_Definitions procedure
|
Declare the Read_Event_Definitions procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
3115645a89e966ae14249bcda3961c0f0e4a2f18
|
src/gen.ads
|
src/gen.ads
|
-----------------------------------------------------------------------
-- Gen -- Code Generator
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen is
-- Library SVN identification
SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk";
-- Revision used (must run 'make version' to update)
SVN_REV : constant Positive := 339;
end Gen;
|
-----------------------------------------------------------------------
-- Gen -- Code Generator
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen is
-- Library SVN identification
SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk";
-- Revision used (must run 'make version' to update)
SVN_REV : constant Positive := 395;
end Gen;
|
Update the version
|
Update the version
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
4f40226f34d7b6900d5f6fbb6a8daefcc12eadec
|
src/asf-components-core.adb
|
src/asf-components-core.adb
|
-----------------------------------------------------------------------
-- components-core -- ASF Core Components
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Ada.Unchecked_Deallocation;
package body ASF.Components.Core is
use ASF;
use EL.Objects;
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class,
Name => Faces_Event_Access);
-- ------------------------------
-- Return a client-side identifier for this component, generating
-- one if necessary.
-- ------------------------------
function Get_Client_Id (UI : UIComponentBase) return Unbounded_String is
Id : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("id");
begin
if Id /= null then
return To_Unbounded_String (Views.Nodes.Get_Value (Id.all, UI.Get_Context.all));
end if;
-- return UI.Id;
return Base.UIComponent (UI).Get_Client_Id;
end Get_Client_Id;
-- ------------------------------
-- Renders the UIText evaluating the EL expressions it may contain.
-- ------------------------------
procedure Encode_Begin (UI : in UIText;
Context : in out Faces_Context'Class) is
begin
UI.Text.Encode_All (UI.Expr_Table, Context);
end Encode_Begin;
-- ------------------------------
-- Set the expression array that contains reduced expressions.
-- ------------------------------
procedure Set_Expression_Table (UI : in out UIText;
Expr_Table : in Views.Nodes.Expression_Access_Array_Access) is
use type ASF.Views.Nodes.Expression_Access_Array_Access;
begin
if UI.Expr_Table /= null then
raise Program_Error with "Expression table already initialized";
end if;
UI.Expr_Table := Expr_Table;
end Set_Expression_Table;
-- ------------------------------
-- Finalize the object.
-- ------------------------------
overriding
procedure Finalize (UI : in out UIText) is
use type ASF.Views.Nodes.Expression_Access_Array_Access;
procedure Free is
new Ada.Unchecked_Deallocation (EL.Expressions.Expression'Class,
EL.Expressions.Expression_Access);
procedure Free is
new Ada.Unchecked_Deallocation (ASF.Views.Nodes.Expression_Access_Array,
ASF.Views.Nodes.Expression_Access_Array_Access);
begin
if UI.Expr_Table /= null then
for I in UI.Expr_Table'Range loop
Free (UI.Expr_Table (I));
end loop;
Free (UI.Expr_Table);
end if;
end Finalize;
function Create_UIText (Tag : ASF.Views.Nodes.Text_Tag_Node_Access)
return UIText_Access is
Result : constant UIText_Access := new UIText;
begin
Result.Text := Tag;
return Result;
end Create_UIText;
-- ------------------------------
-- Get the content type returned by the view.
-- ------------------------------
function Get_Content_Type (UI : in UIView;
Context : in Faces_Context'Class) return String is
begin
if Util.Beans.Objects.Is_Null (UI.Content_Type) then
return UI.Get_Attribute (Name => "contentType", Context => Context);
else
return Util.Beans.Objects.To_String (UI.Content_Type);
end if;
end Get_Content_Type;
-- ------------------------------
-- Set the content type returned by the view.
-- ------------------------------
procedure Set_Content_Type (UI : in out UIView;
Value : in String) is
begin
UI.Content_Type := Util.Beans.Objects.To_Object (Value);
end Set_Content_Type;
-- ------------------------------
-- Encode the begining of the view. Set the response content type.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIView;
Context : in out Faces_Context'Class) is
Content_Type : constant String := UI.Get_Content_Type (Context => Context);
begin
Context.Get_Response.Set_Content_Type (Content_Type);
end Encode_Begin;
-- ------------------------------
-- Decode any new state of the specified component from the request contained
-- in the specified context and store that state on the component.
--
-- During decoding, events may be enqueued for later processing
-- (by event listeners that have registered an interest), by calling
-- the <b>Queue_Event</b> on the associated component.
-- ------------------------------
overriding
procedure Process_Decodes (UI : in out UIView;
Context : in out Faces_Context'Class) is
begin
Base.UIComponent (UI).Process_Decodes (Context);
-- Dispatch events queued for this phase.
UI.Broadcast (ASF.Lifecycles.APPLY_REQUEST_VALUES, Context);
-- Drop other events if the response is to be returned.
if Context.Get_Render_Response or Context.Get_Response_Completed then
UI.Clear_Events;
end if;
end Process_Decodes;
-- ------------------------------
-- Perform the component tree processing required by the <b>Process Validations</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows:
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Validators</b> of all facets and children.
-- <ul>
-- ------------------------------
overriding
procedure Process_Validators (UI : in out UIView;
Context : in out Faces_Context'Class) is
begin
Base.UIComponent (UI).Process_Validators (Context);
-- Dispatch events queued for this phase.
UI.Broadcast (ASF.Lifecycles.PROCESS_VALIDATION, Context);
-- Drop other events if the response is to be returned.
if Context.Get_Render_Response or Context.Get_Response_Completed then
UI.Clear_Events;
end if;
end Process_Validators;
-- ------------------------------
-- Perform the component tree processing required by the <b>Update Model Values</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows.
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Updates/b> of all facets and children.
-- <ul>
-- ------------------------------
overriding
procedure Process_Updates (UI : in out UIView;
Context : in out Faces_Context'Class) is
begin
Base.UIComponent (UI).Process_Updates (Context);
-- Dispatch events queued for this phase.
UI.Broadcast (ASF.Lifecycles.UPDATE_MODEL_VALUES, Context);
-- Drop other events if the response is to be returned.
if Context.Get_Render_Response or Context.Get_Response_Completed then
UI.Clear_Events;
end if;
end Process_Updates;
-- ------------------------------
-- Broadcast any events that have been queued for the <b>Invoke Application</b>
-- phase of the request processing lifecycle and to clear out any events
-- for later phases if the event processing for this phase caused
-- <b>renderResponse</b> or <b>responseComplete</b> to be called.
-- ------------------------------
procedure Process_Application (UI : in out UIView;
Context : in out Faces_Context'Class) is
begin
-- Dispatch events queued for this phase.
UI.Broadcast (ASF.Lifecycles.INVOKE_APPLICATION, Context);
end Process_Application;
-- ------------------------------
-- Queue an event for broadcast at the end of the current request
-- processing lifecycle phase. The event object
-- will be freed after being dispatched.
-- ------------------------------
procedure Queue_Event (UI : in out UIView;
Event : not null access ASF.Events.Faces.Faces_Event'Class) is
begin
UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access);
end Queue_Event;
-- ------------------------------
-- Broadcast the events after the specified lifecycle phase.
-- Events that were queued will be freed.
-- ------------------------------
procedure Broadcast (UI : in out UIView;
Phase : in ASF.Lifecycles.Phase_Type;
Context : in out Faces_Context'Class) is
Pos : Natural := 0;
-- Broadcast the event to the component's listeners
-- and free that event.
procedure Broadcast (Ev : in out Faces_Event_Access);
procedure Broadcast (Ev : in out Faces_Event_Access) is
begin
if Ev /= null then
declare
C : constant Base.UIComponent_Access := Ev.Get_Component;
begin
C.Broadcast (Ev, Context);
end;
Free (Ev);
end if;
end Broadcast;
begin
-- Dispatch events in the order in which they were queued.
-- More events could be queued as a result of the dispatch.
-- After dispatching an event, it is freed but not removed
-- from the event queue (the access will be cleared).
loop
exit when Pos > UI.Phase_Events (Phase).Last_Index;
UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access);
Pos := Pos + 1;
end loop;
-- Now, clear the queue.
UI.Phase_Events (Phase).Clear;
end Broadcast;
-- ------------------------------
-- Clear the events that were queued.
-- ------------------------------
procedure Clear_Events (UI : in out UIView) is
begin
for Phase in UI.Phase_Events'Range loop
for I in 0 .. UI.Phase_Events (Phase).Last_Index loop
declare
Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I);
begin
Free (Ev);
end;
end loop;
UI.Phase_Events (Phase).Clear;
end loop;
end Clear_Events;
-- ------------------------------
-- Abstract Leaf component
-- ------------------------------
overriding
procedure Encode_Children (UI : in UILeaf;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_Children;
overriding
procedure Encode_Begin (UI : in UILeaf;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_Begin;
overriding
procedure Encode_End (UI : in UILeaf;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_End;
-- ------------------------------
-- Component Parameter
-- ------------------------------
-- ------------------------------
-- Get the parameter name
-- ------------------------------
function Get_Name (UI : UIParameter;
Context : Faces_Context'Class) return String is
Name : constant EL.Objects.Object := UI.Get_Attribute (Name => "name",
Context => Context);
begin
return EL.Objects.To_String (Name);
end Get_Name;
-- ------------------------------
-- Get the parameter value
-- ------------------------------
function Get_Value (UI : UIParameter;
Context : Faces_Context'Class) return EL.Objects.Object is
begin
return UI.Get_Attribute (Name => "value", Context => Context);
end Get_Value;
-- ------------------------------
-- Get the list of parameters associated with a component.
-- ------------------------------
function Get_Parameters (UI : Base.UIComponent'Class) return UIParameter_Access_Array is
Result : UIParameter_Access_Array (1 .. UI.Get_Children_Count);
Last : Natural := 0;
procedure Collect (Child : in Base.UIComponent_Access);
pragma Inline (Collect);
procedure Collect (Child : in Base.UIComponent_Access) is
begin
if Child.all in UIParameter'Class then
Last := Last + 1;
Result (Last) := UIParameter (Child.all)'Access;
end if;
end Collect;
procedure Iter is new ASF.Components.Base.Iterate (Process => Collect);
pragma Inline (Iter);
begin
Iter (UI);
return Result (1 .. Last);
end Get_Parameters;
end ASF.Components.Core;
|
-----------------------------------------------------------------------
-- components-core -- ASF Core Components
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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 Ada.Unchecked_Deallocation;
package body ASF.Components.Core is
use ASF;
use EL.Objects;
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class,
Name => Faces_Event_Access);
-- ------------------------------
-- Return a client-side identifier for this component, generating
-- one if necessary.
-- ------------------------------
function Get_Client_Id (UI : UIComponentBase) return Unbounded_String is
Id : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("id");
begin
if Id /= null then
return To_Unbounded_String (Views.Nodes.Get_Value (Id.all, UI.Get_Context.all));
end if;
-- return UI.Id;
return Base.UIComponent (UI).Get_Client_Id;
end Get_Client_Id;
-- ------------------------------
-- Renders the UIText evaluating the EL expressions it may contain.
-- ------------------------------
procedure Encode_Begin (UI : in UIText;
Context : in out Faces_Context'Class) is
begin
UI.Text.Encode_All (UI.Expr_Table, Context);
end Encode_Begin;
-- ------------------------------
-- Set the expression array that contains reduced expressions.
-- ------------------------------
procedure Set_Expression_Table (UI : in out UIText;
Expr_Table : in Views.Nodes.Expression_Access_Array_Access) is
use type ASF.Views.Nodes.Expression_Access_Array_Access;
begin
if UI.Expr_Table /= null then
raise Program_Error with "Expression table already initialized";
end if;
UI.Expr_Table := Expr_Table;
end Set_Expression_Table;
-- ------------------------------
-- Finalize the object.
-- ------------------------------
overriding
procedure Finalize (UI : in out UIText) is
use type ASF.Views.Nodes.Expression_Access_Array_Access;
procedure Free is
new Ada.Unchecked_Deallocation (EL.Expressions.Expression'Class,
EL.Expressions.Expression_Access);
procedure Free is
new Ada.Unchecked_Deallocation (ASF.Views.Nodes.Expression_Access_Array,
ASF.Views.Nodes.Expression_Access_Array_Access);
begin
if UI.Expr_Table /= null then
for I in UI.Expr_Table'Range loop
Free (UI.Expr_Table (I));
end loop;
Free (UI.Expr_Table);
end if;
end Finalize;
function Create_UIText (Tag : ASF.Views.Nodes.Text_Tag_Node_Access)
return UIText_Access is
Result : constant UIText_Access := new UIText;
begin
Result.Text := Tag;
return Result;
end Create_UIText;
-- ------------------------------
-- Get the content type returned by the view.
-- ------------------------------
function Get_Content_Type (UI : in UIView;
Context : in Faces_Context'Class) return String is
begin
if Util.Beans.Objects.Is_Null (UI.Content_Type) then
return UI.Get_Attribute (Name => "contentType", Context => Context);
else
return Util.Beans.Objects.To_String (UI.Content_Type);
end if;
end Get_Content_Type;
-- ------------------------------
-- Set the content type returned by the view.
-- ------------------------------
procedure Set_Content_Type (UI : in out UIView;
Value : in String) is
begin
UI.Content_Type := Util.Beans.Objects.To_Object (Value);
end Set_Content_Type;
-- ------------------------------
-- Encode the begining of the view. Set the response content type.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIView;
Context : in out Faces_Context'Class) is
Content_Type : constant String := UI.Get_Content_Type (Context => Context);
begin
Context.Get_Response.Set_Content_Type (Content_Type);
end Encode_Begin;
-- ------------------------------
-- Decode any new state of the specified component from the request contained
-- in the specified context and store that state on the component.
--
-- During decoding, events may be enqueued for later processing
-- (by event listeners that have registered an interest), by calling
-- the <b>Queue_Event</b> on the associated component.
-- ------------------------------
overriding
procedure Process_Decodes (UI : in out UIView;
Context : in out Faces_Context'Class) is
begin
Base.UIComponent (UI).Process_Decodes (Context);
-- Dispatch events queued for this phase.
UI.Broadcast (ASF.Lifecycles.APPLY_REQUEST_VALUES, Context);
-- Drop other events if the response is to be returned.
if Context.Get_Render_Response or Context.Get_Response_Completed then
UI.Clear_Events;
end if;
end Process_Decodes;
-- ------------------------------
-- Perform the component tree processing required by the <b>Process Validations</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows:
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Validators</b> of all facets and children.
-- <ul>
-- ------------------------------
overriding
procedure Process_Validators (UI : in out UIView;
Context : in out Faces_Context'Class) is
begin
Base.UIComponent (UI).Process_Validators (Context);
-- Dispatch events queued for this phase.
UI.Broadcast (ASF.Lifecycles.PROCESS_VALIDATION, Context);
-- Drop other events if the response is to be returned.
if Context.Get_Render_Response or Context.Get_Response_Completed then
UI.Clear_Events;
end if;
end Process_Validators;
-- ------------------------------
-- Perform the component tree processing required by the <b>Update Model Values</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows.
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Updates/b> of all facets and children.
-- <ul>
-- ------------------------------
overriding
procedure Process_Updates (UI : in out UIView;
Context : in out Faces_Context'Class) is
begin
Base.UIComponent (UI).Process_Updates (Context);
-- Dispatch events queued for this phase.
UI.Broadcast (ASF.Lifecycles.UPDATE_MODEL_VALUES, Context);
-- Drop other events if the response is to be returned.
if Context.Get_Render_Response or Context.Get_Response_Completed then
UI.Clear_Events;
end if;
end Process_Updates;
-- ------------------------------
-- Broadcast any events that have been queued for the <b>Invoke Application</b>
-- phase of the request processing lifecycle and to clear out any events
-- for later phases if the event processing for this phase caused
-- <b>renderResponse</b> or <b>responseComplete</b> to be called.
-- ------------------------------
procedure Process_Application (UI : in out UIView;
Context : in out Faces_Context'Class) is
begin
-- Dispatch events queued for this phase.
UI.Broadcast (ASF.Lifecycles.INVOKE_APPLICATION, Context);
end Process_Application;
-- ------------------------------
-- Queue an event for broadcast at the end of the current request
-- processing lifecycle phase. The event object
-- will be freed after being dispatched.
-- ------------------------------
procedure Queue_Event (UI : in out UIView;
Event : not null access ASF.Events.Faces.Faces_Event'Class) is
use type Base.UIComponent_Access;
Parent : constant Base.UIComponent_Access := UI.Get_Parent;
begin
if Parent /= null then
Parent.Queue_Event (Event);
else
UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access);
end if;
end Queue_Event;
-- ------------------------------
-- Broadcast the events after the specified lifecycle phase.
-- Events that were queued will be freed.
-- ------------------------------
procedure Broadcast (UI : in out UIView;
Phase : in ASF.Lifecycles.Phase_Type;
Context : in out Faces_Context'Class) is
Pos : Natural := 0;
-- Broadcast the event to the component's listeners
-- and free that event.
procedure Broadcast (Ev : in out Faces_Event_Access);
procedure Broadcast (Ev : in out Faces_Event_Access) is
begin
if Ev /= null then
declare
C : constant Base.UIComponent_Access := Ev.Get_Component;
begin
C.Broadcast (Ev, Context);
end;
Free (Ev);
end if;
end Broadcast;
begin
-- Dispatch events in the order in which they were queued.
-- More events could be queued as a result of the dispatch.
-- After dispatching an event, it is freed but not removed
-- from the event queue (the access will be cleared).
loop
exit when Pos > UI.Phase_Events (Phase).Last_Index;
UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access);
Pos := Pos + 1;
end loop;
-- Now, clear the queue.
UI.Phase_Events (Phase).Clear;
end Broadcast;
-- ------------------------------
-- Clear the events that were queued.
-- ------------------------------
procedure Clear_Events (UI : in out UIView) is
begin
for Phase in UI.Phase_Events'Range loop
for I in 0 .. UI.Phase_Events (Phase).Last_Index loop
declare
Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I);
begin
Free (Ev);
end;
end loop;
UI.Phase_Events (Phase).Clear;
end loop;
end Clear_Events;
-- ------------------------------
-- Abstract Leaf component
-- ------------------------------
overriding
procedure Encode_Children (UI : in UILeaf;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_Children;
overriding
procedure Encode_Begin (UI : in UILeaf;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_Begin;
overriding
procedure Encode_End (UI : in UILeaf;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_End;
-- ------------------------------
-- Component Parameter
-- ------------------------------
-- ------------------------------
-- Get the parameter name
-- ------------------------------
function Get_Name (UI : UIParameter;
Context : Faces_Context'Class) return String is
Name : constant EL.Objects.Object := UI.Get_Attribute (Name => "name",
Context => Context);
begin
return EL.Objects.To_String (Name);
end Get_Name;
-- ------------------------------
-- Get the parameter value
-- ------------------------------
function Get_Value (UI : UIParameter;
Context : Faces_Context'Class) return EL.Objects.Object is
begin
return UI.Get_Attribute (Name => "value", Context => Context);
end Get_Value;
-- ------------------------------
-- Get the list of parameters associated with a component.
-- ------------------------------
function Get_Parameters (UI : Base.UIComponent'Class) return UIParameter_Access_Array is
Result : UIParameter_Access_Array (1 .. UI.Get_Children_Count);
Last : Natural := 0;
procedure Collect (Child : in Base.UIComponent_Access);
pragma Inline (Collect);
procedure Collect (Child : in Base.UIComponent_Access) is
begin
if Child.all in UIParameter'Class then
Last := Last + 1;
Result (Last) := UIParameter (Child.all)'Access;
end if;
end Collect;
procedure Iter is new ASF.Components.Base.Iterate (Process => Collect);
pragma Inline (Iter);
begin
Iter (UI);
return Result (1 .. Last);
end Get_Parameters;
end ASF.Components.Core;
|
Fix nesting UIView components - If the UIView is not the root component, propagate the event to the parent
|
Fix nesting UIView components
- If the UIView is not the root component, propagate the event to the parent
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
6b7567d5f19e5659ec532318c4f7805e006ad60d
|
src/ado-drivers-connections.adb
|
src/ado-drivers-connections.adb
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Systems.DLLs;
with System;
with Ada.Strings.Fixed;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Exceptions;
package body ADO.Drivers.Connections is
use Ada.Strings.Fixed;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections");
-- Load the database driver.
procedure Load_Driver (Name : in String);
-- ------------------------------
-- Set the connection URL to connect to the database.
-- The driver connection is a string of the form:
--
-- driver://[host][:port]/[database][?property1][=value1]...
--
-- If the string is invalid or if the driver cannot be found,
-- the Connection_Error exception is raised.
-- ------------------------------
procedure Set_Connection (Controller : in out Configuration;
URI : in String) is
Pos, Pos2, Slash_Pos, Next : Natural;
Is_Hidden : Boolean;
begin
Controller.URI := To_Unbounded_String (URI);
Pos := Index (URI, "://");
if Pos <= 1 then
Log.Error ("Invalid connection URI: {0}", URI);
raise Connection_Error
with "Invalid URI: '" & URI & "'";
end if;
Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1));
if Controller.Driver = null then
Log.Error ("No driver found for connection URI: {0}", URI);
raise Connection_Error
with "Driver '" & URI (URI'First .. Pos - 1) & "' not found";
end if;
Pos := Pos + 3;
Slash_Pos := Index (URI, "/", Pos);
if Slash_Pos < Pos then
Log.Error ("Invalid connection URI: {0}", URI);
raise Connection_Error
with "Invalid connection URI: '" & URI & "'";
end if;
-- Extract the server and port.
Pos2 := Index (URI, ":", Pos);
if Pos2 >= Pos then
Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1));
begin
Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1));
exception
when Constraint_Error =>
Log.Error ("Invalid port in connection URI: {0}", URI);
raise Connection_Error
with "Invalid port in connection URI: '" & URI & "'";
end;
else
Controller.Port := 0;
Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1));
end if;
-- Extract the database name.
Pos := Index (URI, "?", Slash_Pos);
if Pos - 1 > Slash_Pos + 1 then
Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1));
elsif Pos = 0 and Slash_Pos + 1 < URI'Last then
Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last));
else
Controller.Database := Null_Unbounded_String;
end if;
-- Parse the optional properties
if Pos > Slash_Pos then
Controller.Log_URI := To_Unbounded_String (URI (URI'First .. Pos));
while Pos < URI'Last loop
Pos2 := Index (URI, "=", Pos + 1);
if Pos2 > Pos then
Next := Index (URI, "&", Pos2 + 1);
Append (Controller.Log_URI, URI (Pos + 1 .. Pos2));
Is_Hidden := URI (Pos + 1 .. Pos2 - 1) = "password";
if Is_Hidden then
Append (Controller.Log_URI, "XXXXXXX");
end if;
if Next > 0 then
Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1),
URI (Pos2 + 1 .. Next - 1));
if not Is_Hidden then
Append (Controller.Log_URI, URI (Pos2 + 1 .. Next - 1));
end if;
Append (Controller.Log_URI, "&");
Pos := Next;
else
Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1),
URI (Pos2 + 1 .. URI'Last));
if not Is_Hidden then
Append (Controller.Log_URI, URI (Pos2 + 1 .. URI'Last));
end if;
Pos := URI'Last;
end if;
else
Controller.Properties.Set (URI (Pos + 1 .. URI'Last), "");
Append (Controller.Log_URI, URI (Pos + 1 .. URI'Last));
Pos := URI'Last;
end if;
end loop;
else
Controller.Log_URI := Controller.URI;
end if;
Log.Info ("Set connection URI: {0}", Controller.Log_URI);
end Set_Connection;
-- ------------------------------
-- Set a property on the datasource for the driver.
-- The driver can retrieve the property to configure and open
-- the database connection.
-- ------------------------------
procedure Set_Property (Controller : in out Configuration;
Name : in String;
Value : in String) is
begin
Controller.Properties.Set (Name, Value);
end Set_Property;
-- ------------------------------
-- Get a property from the datasource configuration.
-- If the property does not exist, an empty string is returned.
-- ------------------------------
function Get_Property (Controller : in Configuration;
Name : in String) return String is
begin
return Controller.Properties.Get (Name, "");
end Get_Property;
-- ------------------------------
-- Get the server hostname.
-- ------------------------------
function Get_Server (Controller : in Configuration) return String is
begin
return To_String (Controller.Server);
end Get_Server;
-- ------------------------------
-- Set the server hostname.
-- ------------------------------
procedure Set_Server (Controller : in out Configuration;
Server : in String) is
begin
Controller.Server := To_Unbounded_String (Server);
end Set_Server;
-- ------------------------------
-- Set the server port.
-- ------------------------------
procedure Set_Port (Controller : in out Configuration;
Port : in Natural) is
begin
Controller.Port := Port;
end Set_Port;
-- ------------------------------
-- Get the server port.
-- ------------------------------
function Get_Port (Controller : in Configuration) return Natural is
begin
return Controller.Port;
end Get_Port;
-- ------------------------------
-- Set the database name.
-- ------------------------------
procedure Set_Database (Controller : in out Configuration;
Database : in String) is
begin
Controller.Database := To_Unbounded_String (Database);
end Set_Database;
-- ------------------------------
-- Get the database name.
-- ------------------------------
function Get_Database (Controller : in Configuration) return String is
begin
return To_String (Controller.Database);
end Get_Database;
-- ------------------------------
-- Get the database driver name.
-- ------------------------------
function Get_Driver (Controller : in Configuration) return String is
begin
if Controller.Driver /= null then
return Get_Driver_Name (Controller.Driver.all);
else
return "";
end if;
end Get_Driver;
-- ------------------------------
-- Create a new connection using the configuration parameters.
-- ------------------------------
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
begin
if Config.Driver = null then
Log.Error ("No driver found for connection {0}", To_String (Config.Log_URI));
raise Connection_Error with "Data source is not initialized: driver not found";
end if;
Config.Driver.Create_Connection (Config, Result);
if Result.Is_Null then
Log.Error ("Driver {0} failed to create connection {0}",
Config.Driver.Name.all, To_String (Config.Log_URI));
raise Connection_Error with "Data source is not initialized: driver error";
end if;
Log.Info ("Created connection to '{0}' -> {1}", Config.Log_URI, Result.Value.Ident);
exception
when others =>
Log.Info ("Failed to create connection to '{0}'", Config.Log_URI);
raise;
end Create_Connection;
-- Get the database driver index.
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is
Driver : constant ADO.Drivers.Connections.Driver_Access
:= Database_Connection'Class (Database).Get_Driver;
begin
return Driver.Get_Driver_Index;
end Get_Driver_Index;
package Driver_List is
new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access);
Next_Index : Driver_Index := 1;
Drivers : Driver_List.List;
-- ------------------------------
-- Get the driver unique index.
-- ------------------------------
function Get_Driver_Index (D : in Driver) return Driver_Index is
begin
return D.Index;
end Get_Driver_Index;
-- ------------------------------
-- Get the driver name.
-- ------------------------------
function Get_Driver_Name (D : in Driver) return String is
begin
return D.Name.all;
end Get_Driver_Name;
-- ------------------------------
-- Register a database driver.
-- ------------------------------
procedure Register (Driver : in Driver_Access) is
begin
Log.Info ("Register driver {0}", Driver.Name.all);
Driver_List.Prepend (Container => Drivers, New_Item => Driver);
Driver.Index := Next_Index;
Next_Index := Next_Index + 1;
end Register;
-- ------------------------------
-- Load the database driver.
-- ------------------------------
procedure Load_Driver (Name : in String) is
Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension;
Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize";
Handle : Util.Systems.DLLs.Handle;
Addr : System.Address;
begin
Log.Info ("Loading driver {0}", Lib);
Handle := Util.Systems.DLLs.Load (Lib);
Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol);
declare
procedure Init;
pragma Import (C, Init);
for Init'Address use Addr;
begin
Init;
end;
exception
when Util.Systems.DLLs.Not_Found =>
Log.Error ("Driver for {0} was loaded but does not define the initialization symbol",
Name);
when E : Util.Systems.DLLs.Load_Error =>
Log.Error ("Driver for {0} was not found: {1}",
Name, Ada.Exceptions.Exception_Message (E));
end Load_Driver;
-- ------------------------------
-- Get a database driver given its name.
-- ------------------------------
function Get_Driver (Name : in String) return Driver_Access is
begin
Log.Info ("Get driver {0}", Name);
for Retry in 0 .. 2 loop
if Retry = 1 then
ADO.Drivers.Initialize;
elsif Retry = 2 then
Load_Driver (Name);
end if;
declare
Iter : Driver_List.Cursor := Driver_List.First (Drivers);
begin
while Driver_List.Has_Element (Iter) loop
declare
D : constant Driver_Access := Driver_List.Element (Iter);
begin
if Name = D.Name.all then
return D;
end if;
end;
Driver_List.Next (Iter);
end loop;
end;
end loop;
return null;
end Get_Driver;
end ADO.Drivers.Connections;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Systems.DLLs;
with System;
with Ada.Strings.Fixed;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Exceptions;
package body ADO.Drivers.Connections is
use Ada.Strings.Fixed;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections");
-- Load the database driver.
procedure Load_Driver (Name : in String);
-- ------------------------------
-- Set the connection URL to connect to the database.
-- The driver connection is a string of the form:
--
-- driver://[host][:port]/[database][?property1][=value1]...
--
-- If the string is invalid or if the driver cannot be found,
-- the Connection_Error exception is raised.
-- ------------------------------
procedure Set_Connection (Controller : in out Configuration;
URI : in String) is
Pos, Pos2, Slash_Pos, Next : Natural;
Is_Hidden : Boolean;
begin
Controller.URI := To_Unbounded_String (URI);
Pos := Index (URI, "://");
if Pos <= 1 then
Log.Error ("Invalid connection URI: {0}", URI);
raise Connection_Error
with "Invalid URI: '" & URI & "'";
end if;
Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1));
if Controller.Driver = null then
Log.Error ("No driver found for connection URI: {0}", URI);
raise Connection_Error
with "Driver '" & URI (URI'First .. Pos - 1) & "' not found";
end if;
Pos := Pos + 3;
Slash_Pos := Index (URI, "/", Pos);
if Slash_Pos < Pos then
Log.Error ("Invalid connection URI: {0}", URI);
raise Connection_Error
with "Invalid connection URI: '" & URI & "'";
end if;
-- Extract the server and port.
Pos2 := Index (URI, ":", Pos);
if Pos2 >= Pos then
Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1));
begin
Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1));
exception
when Constraint_Error =>
Log.Error ("Invalid port in connection URI: {0}", URI);
raise Connection_Error
with "Invalid port in connection URI: '" & URI & "'";
end;
else
Controller.Port := 0;
Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1));
end if;
-- Extract the database name.
Pos := Index (URI, "?", Slash_Pos);
if Pos - 1 > Slash_Pos + 1 then
Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1));
elsif Pos = 0 and Slash_Pos + 1 < URI'Last then
Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last));
else
Controller.Database := Null_Unbounded_String;
end if;
-- Parse the optional properties
if Pos > Slash_Pos then
Controller.Log_URI := To_Unbounded_String (URI (URI'First .. Pos));
while Pos < URI'Last loop
Pos2 := Index (URI, "=", Pos + 1);
if Pos2 > Pos then
Next := Index (URI, "&", Pos2 + 1);
Append (Controller.Log_URI, URI (Pos + 1 .. Pos2));
Is_Hidden := URI (Pos + 1 .. Pos2 - 1) = "password";
if Is_Hidden then
Append (Controller.Log_URI, "XXXXXXX");
end if;
if Next > 0 then
Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1),
URI (Pos2 + 1 .. Next - 1));
if not Is_Hidden then
Append (Controller.Log_URI, URI (Pos2 + 1 .. Next - 1));
end if;
Append (Controller.Log_URI, "&");
Pos := Next;
else
Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1),
URI (Pos2 + 1 .. URI'Last));
if not Is_Hidden then
Append (Controller.Log_URI, URI (Pos2 + 1 .. URI'Last));
end if;
Pos := URI'Last;
end if;
else
Controller.Properties.Set (URI (Pos + 1 .. URI'Last), "");
Append (Controller.Log_URI, URI (Pos + 1 .. URI'Last));
Pos := URI'Last;
end if;
end loop;
else
Controller.Log_URI := Controller.URI;
end if;
Log.Info ("Set connection URI: {0}", Controller.Log_URI);
end Set_Connection;
-- ------------------------------
-- Set a property on the datasource for the driver.
-- The driver can retrieve the property to configure and open
-- the database connection.
-- ------------------------------
procedure Set_Property (Controller : in out Configuration;
Name : in String;
Value : in String) is
begin
Controller.Properties.Set (Name, Value);
end Set_Property;
-- ------------------------------
-- Get a property from the datasource configuration.
-- If the property does not exist, an empty string is returned.
-- ------------------------------
function Get_Property (Controller : in Configuration;
Name : in String) return String is
begin
return Controller.Properties.Get (Name, "");
end Get_Property;
-- ------------------------------
-- Get the server hostname.
-- ------------------------------
function Get_Server (Controller : in Configuration) return String is
begin
return To_String (Controller.Server);
end Get_Server;
-- ------------------------------
-- Set the server hostname.
-- ------------------------------
procedure Set_Server (Controller : in out Configuration;
Server : in String) is
begin
Controller.Server := To_Unbounded_String (Server);
end Set_Server;
-- ------------------------------
-- Set the server port.
-- ------------------------------
procedure Set_Port (Controller : in out Configuration;
Port : in Natural) is
begin
Controller.Port := Port;
end Set_Port;
-- ------------------------------
-- Get the server port.
-- ------------------------------
function Get_Port (Controller : in Configuration) return Natural is
begin
return Controller.Port;
end Get_Port;
-- ------------------------------
-- Set the database name.
-- ------------------------------
procedure Set_Database (Controller : in out Configuration;
Database : in String) is
begin
Controller.Database := To_Unbounded_String (Database);
end Set_Database;
-- ------------------------------
-- Get the database name.
-- ------------------------------
function Get_Database (Controller : in Configuration) return String is
begin
return To_String (Controller.Database);
end Get_Database;
-- ------------------------------
-- Get the database driver name.
-- ------------------------------
function Get_Driver (Controller : in Configuration) return String is
begin
if Controller.Driver /= null then
return Get_Driver_Name (Controller.Driver.all);
else
return "";
end if;
end Get_Driver;
-- ------------------------------
-- Get the database driver index.
-- ------------------------------
function Get_Driver (Controller : in Configuration) return Driver_Index is
begin
if Controller.Driver /= null then
return Controller.Driver.Index;
else
return Driver_Index'First;
end if;
end Get_Driver;
-- ------------------------------
-- Create a new connection using the configuration parameters.
-- ------------------------------
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
begin
if Config.Driver = null then
Log.Error ("No driver found for connection {0}", To_String (Config.Log_URI));
raise Connection_Error with "Data source is not initialized: driver not found";
end if;
Config.Driver.Create_Connection (Config, Result);
if Result.Is_Null then
Log.Error ("Driver {0} failed to create connection {0}",
Config.Driver.Name.all, To_String (Config.Log_URI));
raise Connection_Error with "Data source is not initialized: driver error";
end if;
Log.Info ("Created connection to '{0}' -> {1}", Config.Log_URI, Result.Value.Ident);
exception
when others =>
Log.Info ("Failed to create connection to '{0}'", Config.Log_URI);
raise;
end Create_Connection;
-- Get the database driver index.
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is
Driver : constant ADO.Drivers.Connections.Driver_Access
:= Database_Connection'Class (Database).Get_Driver;
begin
return Driver.Get_Driver_Index;
end Get_Driver_Index;
package Driver_List is
new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access);
Next_Index : Driver_Index := 1;
Drivers : Driver_List.List;
-- ------------------------------
-- Get the driver unique index.
-- ------------------------------
function Get_Driver_Index (D : in Driver) return Driver_Index is
begin
return D.Index;
end Get_Driver_Index;
-- ------------------------------
-- Get the driver name.
-- ------------------------------
function Get_Driver_Name (D : in Driver) return String is
begin
return D.Name.all;
end Get_Driver_Name;
-- ------------------------------
-- Register a database driver.
-- ------------------------------
procedure Register (Driver : in Driver_Access) is
begin
Log.Info ("Register driver {0}", Driver.Name.all);
Driver_List.Prepend (Container => Drivers, New_Item => Driver);
Driver.Index := Next_Index;
Next_Index := Next_Index + 1;
end Register;
-- ------------------------------
-- Load the database driver.
-- ------------------------------
procedure Load_Driver (Name : in String) is
Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension;
Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize";
Handle : Util.Systems.DLLs.Handle;
Addr : System.Address;
begin
Log.Info ("Loading driver {0}", Lib);
Handle := Util.Systems.DLLs.Load (Lib);
Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol);
declare
procedure Init;
pragma Import (C, Init);
for Init'Address use Addr;
begin
Init;
end;
exception
when Util.Systems.DLLs.Not_Found =>
Log.Error ("Driver for {0} was loaded but does not define the initialization symbol",
Name);
when E : Util.Systems.DLLs.Load_Error =>
Log.Error ("Driver for {0} was not found: {1}",
Name, Ada.Exceptions.Exception_Message (E));
end Load_Driver;
-- ------------------------------
-- Get a database driver given its name.
-- ------------------------------
function Get_Driver (Name : in String) return Driver_Access is
begin
Log.Info ("Get driver {0}", Name);
for Retry in 0 .. 2 loop
if Retry = 1 then
ADO.Drivers.Initialize;
elsif Retry = 2 then
Load_Driver (Name);
end if;
declare
Iter : Driver_List.Cursor := Driver_List.First (Drivers);
begin
while Driver_List.Has_Element (Iter) loop
declare
D : constant Driver_Access := Driver_List.Element (Iter);
begin
if Name = D.Name.all then
return D;
end if;
end;
Driver_List.Next (Iter);
end loop;
end;
end loop;
return null;
end Get_Driver;
end ADO.Drivers.Connections;
|
Implement the Get_Driver function
|
Implement the Get_Driver function
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
7704791aae56465fe161eb075b9293f9be1435b4
|
samples/facebook.adb
|
samples/facebook.adb
|
-----------------------------------------------------------------------
-- facebook -- Get information about a Facebook user using the Facebook API
-- 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.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Util.Strings;
with Util.Beans.Objects;
with Util.Http.Clients;
with Util.Http.Clients.Web;
with Util.Http.Rest;
with Util.Serialize.IO.JSON;
with Mapping;
-- This example shows how to invoke a REST service, retrieve and extract a JSON content
-- into some Ada record. It uses the Facebook Graph API which does not need any
-- authentication (ie, the public Facebook API).
procedure Facebook is
procedure Print (P : in Mapping.Person) is
use Ada.Strings.Unbounded;
begin
Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id));
Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name));
Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name));
Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name));
Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username));
Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender));
Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link));
end Print;
procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper);
Count : constant Natural := Ada.Command_Line.Argument_Count;
-- Mapping for the Person record.
Person_Mapping : aliased Mapping.Person_Mapper.Mapper;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: facebook username ...");
Ada.Text_IO.Put_Line ("Example: facebook btaylor");
return;
end if;
Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID);
Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME);
Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME);
Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME);
Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK);
Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME);
Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER);
Util.Http.Clients.Web.Register;
for I in 1 .. Count loop
declare
URI : constant String := Ada.Command_Line.Argument (I);
P : aliased Mapping.Person;
begin
Get_User ("https://graph.facebook.com/" & URI,
Person_Mapping'Unchecked_Access,
P'Unchecked_Access);
Print (P);
end;
end loop;
end Facebook;
|
-----------------------------------------------------------------------
-- facebook -- Get information about a Facebook user using the Facebook API
-- 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.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
with Util.Http.Clients.Web;
with Util.Http.Rest;
with Mapping;
-- This example shows how to invoke a REST service, retrieve and extract a JSON content
-- into some Ada record. It uses the Facebook Graph API which does not need any
-- authentication (ie, the public Facebook API).
procedure Facebook is
procedure Print (P : in Mapping.Person);
procedure Print (P : in Mapping.Person) is
use Ada.Strings.Unbounded;
begin
Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id));
Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name));
Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name));
Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name));
Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username));
Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender));
Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link));
end Print;
procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper);
Count : constant Natural := Ada.Command_Line.Argument_Count;
-- Mapping for the Person record.
Person_Mapping : aliased Mapping.Person_Mapper.Mapper;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: facebook username ...");
Ada.Text_IO.Put_Line ("Example: facebook btaylor");
return;
end if;
Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID);
Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME);
Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME);
Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME);
Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK);
Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME);
Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER);
Util.Http.Clients.Web.Register;
for I in 1 .. Count loop
declare
URI : constant String := Ada.Command_Line.Argument (I);
P : aliased Mapping.Person;
begin
Get_User ("https://graph.facebook.com/" & URI,
Person_Mapping'Unchecked_Access,
P'Unchecked_Access);
Print (P);
end;
end loop;
end Facebook;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f8d080a850a1afa007f498d52b7031d286c99c87
|
tools/druss-tools.adb
|
tools/druss-tools.adb
|
-----------------------------------------------------------------------
-- druss-tools -- Druss main tool
-- 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 GNAT.Command_Line; use GNAT.Command_Line;
with Ada.Command_Line;
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.Strings.Unbounded;
with Util.Commands;
with Util.Http.Clients.Curl;
with Druss.Config;
with Druss.Commands;
procedure Druss.Tools is
use Ada.Text_IO;
use Ada.Strings.Unbounded;
Config : Ada.Strings.Unbounded.Unbounded_String;
Output : Ada.Strings.Unbounded.Unbounded_String;
Debug : Boolean := False;
Verbose : Boolean := False;
First : Natural := 0;
All_Args : Util.Commands.Default_Argument_List (0);
begin
Druss.Commands.Initialize;
Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs");
-- Parse the command line
loop
case Getopt ("* v d o: c:") is
when ASCII.NUL => exit;
when 'c' =>
Config := Ada.Strings.Unbounded.To_Unbounded_String (Parameter);
when 'o' =>
Output := Ada.Strings.Unbounded.To_Unbounded_String (Parameter);
when 'd' =>
Debug := True;
when 'v' =>
Verbose := True;
when '*' =>
exit;
when others =>
null;
end case;
First := First + 1;
end loop;
Druss.Config.Initialize (To_String (Config));
Util.Http.Clients.Curl.Register;
if First >= Ada.Command_Line.Argument_Count then
Ada.Text_IO.Put_Line ("Missing command name to execute.");
Druss.Commands.Driver.Usage (All_Args);
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
declare
Cmd_Name : constant String := Full_Switch;
Args : Util.Commands.Default_Argument_List (First + 1);
Ctx : Druss.Commands.Context_Type;
begin
Druss.Config.Get_Gateways (Ctx.Gateways);
Druss.Commands.Driver.Execute (Cmd_Name, Args, Ctx);
end;
exception
when E : Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E));
Ada.Command_Line.Set_Exit_Status (2);
end Druss.Tools;
|
-----------------------------------------------------------------------
-- druss-tools -- Druss main tool
-- 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 GNAT.Command_Line; use GNAT.Command_Line;
with Ada.Command_Line;
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.Strings.Unbounded;
with Util.Commands;
with Util.Http.Clients.Curl;
with Util.Log.Loggers;
with Util.Properties;
with Druss.Config;
with Druss.Commands;
procedure Druss.Tools is
use Ada.Text_IO;
use Ada.Strings.Unbounded;
Log_Config : Util.Properties.Manager;
Config : Ada.Strings.Unbounded.Unbounded_String;
Output : Ada.Strings.Unbounded.Unbounded_String;
Debug : Boolean := False;
Verbose : Boolean := False;
First : Natural := 0;
All_Args : Util.Commands.Default_Argument_List (0);
begin
Log_Config.Set ("log4j.rootCategory", "DEBUG,console");
Log_Config.Set ("log4j.appender.console", "Console");
Log_Config.Set ("log4j.appender.console.level", "ERROR");
Log_Config.Set ("log4j.appender.console.layout", "level-message");
Log_Config.Set ("log4j.appender.stdout", "Console");
Log_Config.Set ("log4j.appender.stdout.level", "INFO");
Log_Config.Set ("log4j.appender.stdout.layout", "message");
Log_Config.Set ("log4j.logger.Util", "WARN");
Util.Log.Loggers.Initialize (Log_Config);
Druss.Commands.Initialize;
Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs");
-- Parse the command line
loop
case Getopt ("* v d o: c:") is
when ASCII.NUL => exit;
when 'c' =>
Config := Ada.Strings.Unbounded.To_Unbounded_String (Parameter);
when 'o' =>
Output := Ada.Strings.Unbounded.To_Unbounded_String (Parameter);
when 'd' =>
Debug := True;
when 'v' =>
Verbose := True;
when '*' =>
exit;
when others =>
null;
end case;
First := First + 1;
end loop;
if Verbose then
Log_Config.Set ("log4j.appender.console.level", "INFO");
end if;
if Debug then
Log_Config.Set ("log4j.appender.console.level", "DEBUG");
end if;
Util.Log.Loggers.Initialize (Log_Config);
Druss.Config.Initialize (To_String (Config));
Util.Http.Clients.Curl.Register;
if First >= Ada.Command_Line.Argument_Count then
Ada.Text_IO.Put_Line ("Missing command name to execute.");
Druss.Commands.Driver.Usage (All_Args);
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
declare
Cmd_Name : constant String := Full_Switch;
Args : Util.Commands.Default_Argument_List (First + 1);
Ctx : Druss.Commands.Context_Type;
begin
Druss.Config.Get_Gateways (Ctx.Gateways);
Druss.Commands.Driver.Execute (Cmd_Name, Args, Ctx);
end;
exception
when E : Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E));
Ada.Command_Line.Set_Exit_Status (2);
end Druss.Tools;
|
Use -v and -d options to enable and trigger several log levels
|
Use -v and -d options to enable and trigger several log levels
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
509c47d08fd6adc1c32916c2f423bfb6acb0b9ec
|
regtests/babel-base-users-tests.ads
|
regtests/babel-base-users-tests.ads
|
-----------------------------------------------------------------------
-- babel-base-users-tests - Unit tests for babel users
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Babel.Base.Users.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Find function resolving some existing user.
procedure Test_Find (T : in out Test);
end Babel.Base.Users.Tests;
|
-----------------------------------------------------------------------
-- babel-base-users-tests - Unit tests for babel users
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Babel.Base.Users.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Find function resolving some existing user.
procedure Test_Find (T : in out Test);
-- Test the Get_Name operation.
procedure Test_Get_Name (T : in out Test);
end Babel.Base.Users.Tests;
|
Declare the Test_Get_Name procedure
|
Declare the Test_Get_Name procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
15b320881e7eee6f6c767be174f7165a03f2955b
|
awa/src/awa-users-modules.adb
|
awa/src/awa-users-modules.adb
|
-----------------------------------------------------------------------
-- awa-users-model -- User management module
-- Copyright (C) 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 AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Applications;
with AWA.Users.Beans;
with Util.Log.Loggers;
package body AWA.Users.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Module");
package Register is new AWA.Modules.Beans (Module => User_Module,
Module_Access => User_Module_Access);
-- ------------------------------
-- Initialize the user module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the users module");
-- Setup the resource bundles.
App.Register ("userMsg", "users");
-- Register the OpenID servlets.
App.Add_Servlet (Name => "openid-auth",
Server => Plugin.Auth'Unchecked_Access);
App.Add_Servlet (Name => "openid-verify",
Server => Plugin.Verify_Auth'Unchecked_Access);
-- Setup the verify access key filter.
App.Add_Filter ("verify-access-key", Plugin.Key_Filter'Unchecked_Access);
App.Add_Filter ("auth-filter", Plugin.Auth_Filter'Unchecked_Access);
Plugin.Key_Filter.Initialize (App.all);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Authenticate_Bean",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Current_User_Bean",
Handler => AWA.Users.Beans.Create_Current_User_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Create the user manager when everything is initialized.
Plugin.Manager := Plugin.Create_User_Manager;
end Initialize;
-- ------------------------------
-- Get the user manager.
-- ------------------------------
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
begin
return Plugin.Manager;
end Get_User_Manager;
-- ------------------------------
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
-- ------------------------------
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
Result : constant Services.User_Service_Access := new Services.User_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_User_Manager;
-- ------------------------------
-- Get the user module instance associated with the current application.
-- ------------------------------
function Get_User_Module return User_Module_Access is
function Get is new AWA.Modules.Get (User_Module, User_Module_Access, NAME);
begin
return Get;
end Get_User_Module;
-- ------------------------------
-- Get the user manager instance associated with the current application.
-- ------------------------------
function Get_User_Manager return Services.User_Service_Access is
Module : constant User_Module_Access := Get_User_Module;
begin
if Module = null then
Log.Error ("There is no active User_Module");
return null;
else
return Module.Get_User_Manager;
end if;
end Get_User_Manager;
end AWA.Users.Modules;
|
-----------------------------------------------------------------------
-- awa-users-model -- User management module
-- Copyright (C) 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 AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Applications;
with AWA.Users.Beans;
with Util.Log.Loggers;
package body AWA.Users.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Module");
package Register is new AWA.Modules.Beans (Module => User_Module,
Module_Access => User_Module_Access);
-- ------------------------------
-- Initialize the user module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the users module");
-- Setup the resource bundles.
App.Register ("userMsg", "users");
-- Register the OpenID servlets.
App.Add_Servlet (Name => "openid-auth",
Server => Plugin.Auth'Unchecked_Access);
App.Add_Servlet (Name => "openid-verify",
Server => Plugin.Verify_Auth'Unchecked_Access);
-- Setup the verify access key filter.
App.Add_Filter ("verify-access-key", Plugin.Key_Filter'Unchecked_Access);
App.Add_Filter ("auth-filter", Plugin.Auth_Filter'Unchecked_Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Authenticate_Bean",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Current_User_Bean",
Handler => AWA.Users.Beans.Create_Current_User_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Create the user manager when everything is initialized.
Plugin.Manager := Plugin.Create_User_Manager;
end Initialize;
-- ------------------------------
-- Get the user manager.
-- ------------------------------
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
begin
return Plugin.Manager;
end Get_User_Manager;
-- ------------------------------
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
-- ------------------------------
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
Result : constant Services.User_Service_Access := new Services.User_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_User_Manager;
-- ------------------------------
-- Get the user module instance associated with the current application.
-- ------------------------------
function Get_User_Module return User_Module_Access is
function Get is new AWA.Modules.Get (User_Module, User_Module_Access, NAME);
begin
return Get;
end Get_User_Module;
-- ------------------------------
-- Get the user manager instance associated with the current application.
-- ------------------------------
function Get_User_Manager return Services.User_Service_Access is
Module : constant User_Module_Access := Get_User_Module;
begin
if Module = null then
Log.Error ("There is no active User_Module");
return null;
else
return Module.Get_User_Manager;
end if;
end Get_User_Manager;
end AWA.Users.Modules;
|
Remove the Key_Filter initialization because this is now correctly done by ASF
|
Remove the Key_Filter initialization because this is now correctly done by ASF
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a826725b8689998f87955cda0557f08b57b4f1eb
|
src/aws/asf-responses-web.adb
|
src/aws/asf-responses-web.adb
|
-----------------------------------------------------------------------
-- asf.responses.web -- ASF Responses with AWS server
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWS.Headers;
with AWS.Messages;
with AWS.Response.Set;
with AWS.Containers.Tables;
package body ASF.Responses.Web is
procedure Initialize (Resp : in out Response) is
begin
Resp.Content.Initialize (Size => 256 * 1024,
Output => Resp'Unchecked_Access,
Input => null);
Resp.Stream := Resp.Content'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
procedure Write (Stream : in out Response;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
AWS.Response.Set.Append_Body (D => Stream.Data,
Item => Buffer);
end Write;
-- ------------------------------
-- Flush the buffer (if any) to the sink.
-- ------------------------------
procedure Flush (Stream : in out Response) is
begin
null;
end Flush;
function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code;
function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code is
use AWS.Messages;
begin
case Status is
when 100 =>
return S100;
when 101 =>
return S101;
when 200 =>
return S200;
when 201 =>
return S201;
when 202 =>
return S202;
when 301 =>
return S301;
when 302 =>
return S302;
when 400 =>
return S400;
when 401 =>
return S401;
when 402 =>
return S402;
when 403 =>
return S403;
when 404 =>
return S404;
when others =>
return S500;
end case;
end To_Status_Code;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Resp : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
Headers : constant AWS.Headers.List := AWS.Response.Header (Resp.Data);
begin
AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (Headers),
";", Process);
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Resp : in Response;
Name : in String) return Boolean is
begin
raise Program_Error with "Contains_Header is not implemented";
return False;
end Contains_Header;
-- ------------------------------
-- Sets a response header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
procedure Set_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
if AWS.Response.Header (Resp.Data, Name)'Length = 0 then
AWS.Response.Set.Add_Header (D => Resp.Data,
Name => Name,
Value => Value);
end if;
end Set_Header;
-- ------------------------------
-- Adds a response header with the given name and value.
-- This method allows response headers to have multiple values.
-- ------------------------------
procedure Add_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
AWS.Response.Set.Add_Header (D => Resp.Data,
Name => Name,
Value => Value);
end Add_Header;
-- ------------------------------
-- Sends a temporary redirect response to the client using the specified redirect
-- location URL. This method can accept relative URLs; the servlet container must
-- convert the relative URL to an absolute URL before sending the response to the
-- client. If the location is relative without a leading '/' the container
-- interprets it as relative to the current request URI. If the location is relative
-- with a leading '/' the container interprets it as relative to the servlet
-- container root.
--
-- If the response has already been committed, this method throws an
-- IllegalStateException. After using this method, the response should be
-- considered to be committed and should not be written to.
-- ------------------------------
procedure Send_Redirect (Resp : in out Response;
Location : in String) is
begin
Response'Class (Resp).Set_Status (SC_FOUND);
Response'Class (Resp).Set_Header (Name => "Location",
Value => Location);
Resp.Redirect := True;
end Send_Redirect;
-- ------------------------------
-- Prepare the response data by collecting the status, content type and message body.
-- ------------------------------
procedure Build (Resp : in out Response) is
begin
if not Resp.Redirect then
AWS.Response.Set.Content_Type (D => Resp.Data,
Value => Resp.Get_Content_Type);
Resp.Content.Flush;
else
AWS.Response.Set.Mode (D => Resp.Data,
Value => AWS.Response.Header);
end if;
AWS.Response.Set.Status_Code (D => Resp.Data,
Value => To_Status_Code (Resp.Get_Status));
end Build;
-- ------------------------------
-- Get the response data
-- ------------------------------
function Get_Data (Resp : in Response) return AWS.Response.Data is
begin
return Resp.Data;
end Get_Data;
end ASF.Responses.Web;
|
-----------------------------------------------------------------------
-- asf.responses.web -- ASF Responses with AWS server
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWS.Headers;
with AWS.Messages;
with AWS.Response.Set;
with AWS.Containers.Tables;
package body ASF.Responses.Web is
procedure Initialize (Resp : in out Response) is
begin
Resp.Content.Initialize (Size => 256 * 1024,
Output => Resp'Unchecked_Access,
Input => null);
Resp.Stream := Resp.Content'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
procedure Write (Stream : in out Response;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
AWS.Response.Set.Append_Body (D => Stream.Data,
Item => Buffer);
end Write;
-- ------------------------------
-- Flush the buffer (if any) to the sink.
-- ------------------------------
procedure Flush (Stream : in out Response) is
begin
null;
end Flush;
function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code;
function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code is
use AWS.Messages;
begin
case Status is
when 100 =>
return S100;
when 101 =>
return S101;
when 200 =>
return S200;
when 201 =>
return S201;
when 202 =>
return S202;
when 301 =>
return S301;
when 302 =>
return S302;
when 400 =>
return S400;
when 401 =>
return S401;
when 402 =>
return S402;
when 403 =>
return S403;
when 404 =>
return S404;
when others =>
return S500;
end case;
end To_Status_Code;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Resp : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
Headers : constant AWS.Headers.List := AWS.Response.Header (Resp.Data);
begin
AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (Headers),
";", Process);
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Resp : in Response;
Name : in String) return Boolean is
begin
raise Program_Error with "Contains_Header is not implemented";
return False;
end Contains_Header;
-- ------------------------------
-- Sets a response header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
procedure Set_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
if AWS.Response.Header (Resp.Data, Name)'Length = 0 then
AWS.Response.Set.Add_Header (D => Resp.Data,
Name => Name,
Value => Value);
end if;
end Set_Header;
-- ------------------------------
-- Adds a response header with the given name and value.
-- This method allows response headers to have multiple values.
-- ------------------------------
procedure Add_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
AWS.Response.Set.Add_Header (D => Resp.Data,
Name => Name,
Value => Value);
end Add_Header;
-- ------------------------------
-- Sends a temporary redirect response to the client using the specified redirect
-- location URL. This method can accept relative URLs; the servlet container must
-- convert the relative URL to an absolute URL before sending the response to the
-- client. If the location is relative without a leading '/' the container
-- interprets it as relative to the current request URI. If the location is relative
-- with a leading '/' the container interprets it as relative to the servlet
-- container root.
--
-- If the response has already been committed, this method throws an
-- IllegalStateException. After using this method, the response should be
-- considered to be committed and should not be written to.
-- ------------------------------
procedure Send_Redirect (Resp : in out Response;
Location : in String) is
begin
Response'Class (Resp).Set_Status (SC_FOUND);
Response'Class (Resp).Set_Header (Name => "Location",
Value => Location);
Resp.Redirect := True;
end Send_Redirect;
-- ------------------------------
-- Prepare the response data by collecting the status, content type and message body.
-- ------------------------------
procedure Build (Resp : in out Response) is
begin
if not Resp.Redirect then
AWS.Response.Set.Content_Type (D => Resp.Data,
Value => Resp.Get_Content_Type);
Resp.Content.Flush;
if AWS.Response.Is_Empty (Resp.Data) then
AWS.Response.Set.Message_Body (Resp.Data, "");
end if;
else
AWS.Response.Set.Mode (D => Resp.Data,
Value => AWS.Response.Header);
end if;
AWS.Response.Set.Status_Code (D => Resp.Data,
Value => To_Status_Code (Resp.Get_Status));
end Build;
-- ------------------------------
-- Get the response data
-- ------------------------------
function Get_Data (Resp : in Response) return AWS.Response.Data is
begin
return Resp.Data;
end Get_Data;
end ASF.Responses.Web;
|
Fix AWS support - if the response is empty and this is not a redirect, return an empty body.
|
Fix AWS support
- if the response is empty and this is not a redirect, return an empty body.
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
38a655baa342acd48718e83ae22ea80ece825f8c
|
awa/src/awa-events.ads
|
awa/src/awa-events.ads
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- 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.Strings;
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with ASF.Applications;
-- == Introduction ==
-- The <b>AWA.Events</b> package defines an event framework for modules to post events
-- and have Ada bean methods be invoked when these events are dispatched. Subscription to
-- events is done through configuration files. This allows to configure the modules and
-- integrate them together easily at configuration time.
--
-- 1/ Modules define the events that they can generate by instantiating the <b>Definition</b>
-- package. This is a static definition of the event. Each event is given a unique name.
--
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- 2/ The module can post an event to inform other modules or the system that a particular
-- action occurred. The module creates the event instance of type <b>Module_Event</b> and
-- populates that event with useful properties for event receivers.
--
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- 3/ The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- 4/ Modules or applications interested by a particular event will configure the event manager
-- to dispatch the event to an Ada bean event action. The Ada bean is an object that must
-- implement a procedure that matches the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- 5/ The configuration file indicates how to bind the Ada bean action and the event together.
-- The action is specified using an EL Method Expression (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
-- ------------------------------
-- Event kind definition
-- ------------------------------
-- This package must be instantiated for each event that a module can post.
generic
Name : String;
package Definition is
function Kind return Event_Index;
pragma Inline_Always (Kind);
end Definition;
-- Exception raised if an event name is not found.
Not_Found : exception;
-- Identifies an invalid event.
Invalid_Event : constant Event_Index := 0;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String) return Event_Index;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
private
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Invalid_Event;
Props : ASF.Applications.Config;
end record;
-- The index of the last event definition.
Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with ASF.Applications;
-- == Introduction ==
-- The <b>AWA.Events</b> package defines an event framework for modules to post events
-- and have Ada bean methods be invoked when these events are dispatched. Subscription to
-- events is done through configuration files. This allows to configure the modules and
-- integrate them together easily at configuration time.
--
-- 1/ Modules define the events that they can generate by instantiating the <b>Definition</b>
-- package. This is a static definition of the event. Each event is given a unique name.
--
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- 2/ The module can post an event to inform other modules or the system that a particular
-- action occurred. The module creates the event instance of type <b>Module_Event</b> and
-- populates that event with useful properties for event receivers.
--
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- 3/ The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- 4/ Modules or applications interested by a particular event will configure the event manager
-- to dispatch the event to an Ada bean event action. The Ada bean is an object that must
-- implement a procedure that matches the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- 5/ The configuration file indicates how to bind the Ada bean action and the event together.
-- The action is specified using an EL Method Expression (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
-- == Data Model ==
-- @include Queues.hbm.xml
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
-- ------------------------------
-- Event kind definition
-- ------------------------------
-- This package must be instantiated for each event that a module can post.
generic
Name : String;
package Definition is
function Kind return Event_Index;
pragma Inline_Always (Kind);
end Definition;
-- Exception raised if an event name is not found.
Not_Found : exception;
-- Identifies an invalid event.
Invalid_Event : constant Event_Index := 0;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String) return Event_Index;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
private
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Invalid_Event;
Props : ASF.Applications.Config;
end record;
-- The index of the last event definition.
Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
Add the event data model
|
Add the event data model
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
75157ea033090c47d6d89c54f13f71ba05651f6e
|
samples/json.adb
|
samples/json.adb
|
-----------------------------------------------------------------------
-- json -- JSON Reader
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
with Util.Serialize.IO.JSON;
with Ada.Containers;
with Mapping;
with Util.Streams.Texts;
with Util.Streams.Buffered;
procedure Json is
use Util.Streams.Buffered;
use Ada.Strings.Unbounded;
use type Mapping.Person_Access;
use type Ada.Containers.Count_Type;
Reader : Util.Serialize.IO.JSON.Parser;
Count : constant Natural := Ada.Command_Line.Argument_Count;
procedure Print (P : in Mapping.Person_Vector.Cursor);
procedure Print (P : in Mapping.Person);
procedure Print (P : in Mapping.Person) is
begin
Ada.Text_IO.Put_Line ("first_name : " & To_String (P.First_Name));
Ada.Text_IO.Put_Line ("last_name : " & To_String (P.Last_Name));
Ada.Text_IO.Put_Line ("Age : " & Natural'Image (P.Age));
Ada.Text_IO.Put_Line ("Street : " & To_String (P.Addr.Street));
Ada.Text_IO.Put_Line ("City : " & To_String (P.Addr.City));
Ada.Text_IO.Put_Line ("Zip : " & Natural'Image (P.Addr.Zip));
Ada.Text_IO.Put_Line ("Country : " & To_String (P.Addr.Country));
Ada.Text_IO.Put_Line ("Info : " & To_String (P.Addr.Info.Name)
& "=" & To_String (P.Addr.Info.Value));
end Print;
procedure Print (P : in Mapping.Person_Vector.Cursor) is
begin
Print (Mapping.Person_Vector.Element (P));
end Print;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: json file...");
return;
end if;
Reader.Add_Mapping ("list", Mapping.Get_Person_Vector_Mapper.all'Access);
Reader.Add_Mapping ("person", Mapping.Get_Person_Mapper.all'Access);
for I in 1 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
List : aliased Mapping.Person_Vector.Vector;
P : aliased Mapping.Person;
begin
Mapping.Person_Vector_Mapper.Set_Context (Reader, List'Unchecked_Access);
Mapping.Person_Mapper.Set_Context (Reader, P'Unchecked_Access);
Reader.Parse (S);
-- The list now contains our elements.
List.Iterate (Process => Print'Access);
if List.Length = 0 then
Print (P);
end if;
declare
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Output.Initialize (Size => 10000);
Mapping.Get_Person_Mapper.Write (Output, P);
Ada.Text_IO.Put_Line ("Person: "
& Util.Streams.Texts.To_String (Buffered_Stream (Output)));
end;
declare
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Output.Initialize (Size => 10000);
Output.Write ("{""list"":");
Mapping.Get_Person_Vector_Mapper.Write (Output, List);
Output.Write ("}");
Ada.Text_IO.Put_Line ("IO:");
Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Buffered_Stream (Output)));
end;
end;
end loop;
end Json;
|
-----------------------------------------------------------------------
-- json -- JSON Reader
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
with Util.Serialize.IO.JSON;
with Ada.Containers;
with Mapping;
with Util.Streams.Texts;
with Util.Streams.Buffered;
procedure Json is
use Util.Streams.Buffered;
use Ada.Strings.Unbounded;
use type Mapping.Person_Access;
use type Ada.Containers.Count_Type;
Reader : Util.Serialize.IO.JSON.Parser;
Count : constant Natural := Ada.Command_Line.Argument_Count;
procedure Print (P : in Mapping.Person_Vector.Cursor);
procedure Print (P : in Mapping.Person);
procedure Print (P : in Mapping.Person) is
begin
Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name));
Ada.Text_IO.Put_Line ("first_name : " & To_String (P.First_Name));
Ada.Text_IO.Put_Line ("last_name : " & To_String (P.Last_Name));
Ada.Text_IO.Put_Line ("Age : " & Natural'Image (P.Age));
Ada.Text_IO.Put_Line ("Street : " & To_String (P.Addr.Street));
Ada.Text_IO.Put_Line ("City : " & To_String (P.Addr.City));
Ada.Text_IO.Put_Line ("Zip : " & Natural'Image (P.Addr.Zip));
Ada.Text_IO.Put_Line ("Country : " & To_String (P.Addr.Country));
Ada.Text_IO.Put_Line ("Info : " & To_String (P.Addr.Info.Name)
& "=" & To_String (P.Addr.Info.Value));
end Print;
procedure Print (P : in Mapping.Person_Vector.Cursor) is
begin
Print (Mapping.Person_Vector.Element (P));
end Print;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: json file...");
return;
end if;
Reader.Add_Mapping ("/list", Mapping.Get_Person_Vector_Mapper.all'Access);
Reader.Add_Mapping ("/person", Mapping.Get_Person_Mapper.all'Access);
for I in 1 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
List : aliased Mapping.Person_Vector.Vector;
P : aliased Mapping.Person;
begin
Mapping.Person_Vector_Mapper.Set_Context (Reader, List'Unchecked_Access);
Mapping.Person_Mapper.Set_Context (Reader, P'Unchecked_Access);
Reader.Parse (S);
-- The list now contains our elements.
List.Iterate (Process => Print'Access);
if List.Length = 0 then
Print (P);
end if;
declare
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Output.Initialize (Size => 10000);
Mapping.Get_Person_Mapper.Write (Output, P);
Ada.Text_IO.Put_Line ("Person: "
& Util.Streams.Texts.To_String (Buffered_Stream (Output)));
end;
declare
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Output.Initialize (Size => 10000);
Output.Write ("{""list"":");
Mapping.Get_Person_Vector_Mapper.Write (Output, List);
Output.Write ("}");
Ada.Text_IO.Put_Line ("IO:");
Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Buffered_Stream (Output)));
end;
end;
end loop;
end Json;
|
Update the json example
|
Update the json example
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
521ea20e0f7e992f1564f3e0e9a845a9c39e773b
|
awa/awaunit/awa-tests.adb
|
awa/awaunit/awa-tests.adb
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with ASF.Server.Web;
with ASF.Converters.Dates;
with ASF.Tests;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
-- with AWA.Applications;
with AWA.Applications.Factory;
with AWA.Services.Filters;
with AWA.Services.Contexts;
package body AWA.Tests is
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new AWA.Applications.Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
if Add_Modules then
declare
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Tests.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
end AWA.Tests;
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with ASF.Server.Web;
with ASF.Converters.Dates;
with ASF.Tests;
with AWA.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
-- with AWA.Applications;
with AWA.Applications.Factory;
with AWA.Services.Filters;
with AWA.Services.Contexts;
package body AWA.Tests is
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new AWA.Applications.Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
if Add_Modules then
declare
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Tests.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
end AWA.Tests;
|
Add a relative date converter
|
Add a relative date converter
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
68994b3e7309c99a4476fa064e3dd8ed1165d10c
|
src/wiki-filters.adb
|
src/wiki-filters.adb
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
begin
if Filter.Next /= null then
Filter.Add_Node (Document, Kind);
else
Wiki.Nodes.Append (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map) is
begin
if Filter.Next /= null then
Filter.Add_Text (Document, Text, Format);
else
Wiki.Nodes.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Filter.Next /= null then
Filter.Add_Header (Document, Header, Level);
else
Wiki.Nodes.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Filter_Type;
Level : in Natural) is
begin
Document.Document.Add_Blockquote (Level);
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Filter_Type;
Level : in Positive;
Ordered : in Boolean) is
begin
Document.Document.Add_List_Item (Level, Ordered);
end Add_List_Item;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Link (Name, Link, Language, Title);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Filter_Type;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Image (Link, Alt, Position, Description);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Filter_Type;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Quote (Quote, Link, Language);
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
Document.Document.Add_Text (Text, Format);
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Preformatted (Text, Format);
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
begin
Document.Document.Start_Element (Name, Attributes);
end Start_Element;
overriding
procedure End_Element (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Document.End_Element (Name);
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Filter_Type) is
begin
Document.Document.Finish;
end Finish;
end Wiki.Filters;
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
begin
if Filter.Next /= null then
Filter.Add_Node (Document, Kind);
else
Wiki.Nodes.Append (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Nodes.Format_Map) is
begin
if Filter.Next /= null then
Filter.Add_Text (Document, Text, Format);
else
Wiki.Nodes.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
if Filter.Next /= null then
Filter.Add_Header (Document, Header, Level);
else
Wiki.Nodes.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type) is
begin
if Filter.Next /= null then
Filter.Push_Node (Document, Tag, Attributes);
else
Wiki.Nodes.Append (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Nodes.Document;
Tag : in Wiki.Nodes.Html_Tag_Type) is
begin
if Filter.Next /= null then
Filter.Pop_Node (Document, Tag);
else
Wiki.Nodes.Append (Document, Tag);
end if;
end Pop_Node;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Filter_Type;
Level : in Natural) is
begin
Document.Document.Add_Blockquote (Level);
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Filter_Type;
Level : in Positive;
Ordered : in Boolean) is
begin
Document.Document.Add_List_Item (Level, Ordered);
end Add_List_Item;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Filter_Type;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Link (Name, Link, Language, Title);
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Filter_Type;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Image (Link, Alt, Position, Description);
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Filter_Type;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Quote (Quote, Link, Language);
end Add_Quote;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
overriding
procedure Add_Preformatted (Document : in out Filter_Type;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Document.Add_Preformatted (Text, Format);
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Filter_Type) is
begin
Document.Document.Finish;
end Finish;
end Wiki.Filters;
|
Implement the Push_Node and Pop_Node operations
|
Implement the Push_Node and Pop_Node operations
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
50c343752fc2a1f52f762c95e879daf821e2ca82
|
awa/plugins/awa-jobs/src/awa-jobs-services.adb
|
awa/plugins/awa-jobs/src/awa-jobs-services.adb
|
-----------------------------------------------------------------------
-- awa-jobs -- 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.Serialize.Tools;
with Util.Log.Loggers;
with Ada.Tags;
with Ada.Calendar;
with Ada.Unchecked_Deallocation;
with ADO.Sessions.Entities;
with AWA.Users.Models;
with AWA.Events.Models;
with AWA.Services.Contexts;
with AWA.Jobs.Modules;
with AWA.Applications;
with AWA.Events.Services;
with AWA.Modules;
package body AWA.Jobs.Services is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services");
-- ------------------------------
-- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>.
-- ------------------------------
procedure Set_Parameter (Job : in out Abstract_Job_Type;
Name : in String;
Value : in String) is
begin
Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value));
end Set_Parameter;
-- ------------------------------
-- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>.
-- ------------------------------
procedure Set_Parameter (Job : in out Abstract_Job_Type;
Name : in String;
Value : in Integer) is
begin
Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value));
end Set_Parameter;
-- ------------------------------
-- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>.
-- The value object can hold any kind of basic value type (integer, enum, date, strings).
-- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised.
-- ------------------------------
procedure Set_Parameter (Job : in out Abstract_Job_Type;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Job.Props.Include (Name, Value);
Job.Props_Modified := True;
end Set_Parameter;
-- ------------------------------
-- Get the job parameter identified by the <b>Name</b> and convert the value into a string.
-- ------------------------------
function Get_Parameter (Job : in Abstract_Job_Type;
Name : in String) return String is
Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name);
begin
return Util.Beans.Objects.To_String (Value);
end Get_Parameter;
-- ------------------------------
-- Get the job parameter identified by the <b>Name</b> and convert the value as an integer.
-- If the parameter is not defined, return the default value passed in <b>Default</b>.
-- ------------------------------
function Get_Parameter (Job : in Abstract_Job_Type;
Name : in String;
Default : in Integer) return Integer is
Pos : constant Util.Beans.Objects.Maps.Cursor := Job.Props.Find (Name);
begin
if Util.Beans.Objects.Maps.Has_Element (Pos) then
declare
Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Element (Pos);
begin
if Util.Beans.Objects.Is_Null (Value) then
return Default;
else
return Util.Beans.Objects.To_Integer (Value);
end if;
end;
else
return Default;
end if;
end Get_Parameter;
-- ------------------------------
-- Get the job parameter identified by the <b>Name</b> and return it as a typed object.
-- ------------------------------
function Get_Parameter (Job : in Abstract_Job_Type;
Name : in String) return Util.Beans.Objects.Object is
begin
return Job.Props.Element (Name);
end Get_Parameter;
-- ------------------------------
-- Get the job status.
-- ------------------------------
function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is
begin
return Job.Job.Get_Status;
end Get_Status;
-- ------------------------------
-- Set the job status.
-- When the job is terminated, it is closed and the job parameters or results cannot be
-- changed.
-- ------------------------------
procedure Set_Status (Job : in out Abstract_Job_Type;
Status : in AWA.Jobs.Models.Job_Status_Type) is
begin
case Job.Job.Get_Status is
when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED =>
raise Closed_Error;
when Models.SCHEDULED | Models.RUNNING =>
Job.Job.Set_Status (Status);
end case;
end Set_Status;
-- ------------------------------
-- Save the job information in the database. Use the database session defined by <b>DB</b>
-- to save the job.
-- ------------------------------
procedure Save (Job : in out Abstract_Job_Type;
DB : in out ADO.Sessions.Master_Session'Class) is
begin
if Job.Results_Modified then
Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results));
Job.Results_Modified := False;
end if;
Job.Job.Save (DB);
end Save;
-- Schedule the job.
procedure Schedule (Job : in out Abstract_Job_Type;
Definition : in Job_Factory'Class) is
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is
begin
Manager.Set_Message_Type (Msg, Job_Create_Event.Kind);
Manager.Set_Event_Queue (Msg, "job-queue");
end Set_Event;
begin
if Job.Job.Is_Inserted then
Log.Error ("Job is already scheduled");
raise Schedule_Error with "The job is already scheduled.";
end if;
AWA.Jobs.Modules.Create_Event (Msg);
Job.Job.Set_Create_Date (Msg.Get_Create_Date);
DB.Begin_Transaction;
Job.Job.Set_Name (Definition.Get_Name);
Job.Job.Set_User (User);
Job.Job.Set_Session (Sess);
Job.Save (DB);
-- Create the event
Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props));
App.Do_Event_Manager (Process => Set_Event'Access);
Msg.Set_User (User);
Msg.Set_Session (Sess);
Msg.Set_Entity_Id (Job.Job.Get_Id);
Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB,
Object => Job.Job.Get_Key));
Msg.Save (DB);
Job.Job.Set_Event (Msg);
Job.Job.Save (DB);
DB.Commit;
end Schedule;
-- ------------------------------
-- Execute the job and save the job information in the database.
-- ------------------------------
procedure Execute (Job : in out Abstract_Job_Type'Class;
DB : in out ADO.Sessions.Master_Session'Class) is
use type AWA.Jobs.Models.Job_Status_Type;
begin
-- Execute the job with an exception guard.
begin
Job.Execute;
exception
when E : others =>
Log.Error ("Exception when executing job {0}", Job.Job.Get_Name);
Log.Error ("Exception: {0}", E, True);
Job.Job.Set_Status (Models.FAILED);
end;
-- If the job did not set a completion status, mark it as terminated.
if Job.Job.Get_Status = Models.SCHEDULED or Job.Job.Get_Status = Models.RUNNING then
Job.Job.Set_Status (Models.TERMINATED);
end if;
-- And save the job.
DB.Begin_Transaction;
Job.Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => True, Value => Ada.Calendar.Clock));
Job.Save (DB);
DB.Commit;
end Execute;
-- ------------------------------
-- Execute the job associated with the given event.
-- ------------------------------
procedure Execute (Event : in AWA.Events.Module_Event'Class) is
use AWA.Jobs.Modules;
use type AWA.Modules.Module_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Abstract_Job_Type'Class,
Name => Abstract_Job_Access);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
Module : constant AWA.Modules.Module_Access := App.Find_Module (AWA.Jobs.Modules.NAME);
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Job : AWA.Jobs.Models.Job_Ref;
begin
if Module = null then
Log.Warn ("There is no Job module to execute a job");
raise Execute_Error;
end if;
if not (Module.all in AWA.Jobs.Modules.Job_Module'Class) then
Log.Warn ("The 'job' module is not a valid module for job execution");
raise Execute_Error;
end if;
DB.Begin_Transaction;
Job.Load (Session => DB,
Id => Event.Get_Entity_Identifier);
Job.Set_Start_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock));
Job.Set_Status (AWA.Jobs.Models.RUNNING);
Job.Save (Session => DB);
DB.Commit;
declare
Name : constant String := Job.Get_Name;
begin
Log.Info ("Restoring job '{0}'", Name);
declare
Plugin : constant Job_Module_Access := Job_Module'Class (Module.all)'Access;
Factory : constant Job_Factory_Access := Plugin.Find_Factory (Name);
Work : AWA.Jobs.Services.Abstract_Job_Access := null;
begin
if Factory /= null then
Work := Factory.Create;
Work.Job := Job;
Work.Execute (DB);
Free (Work);
else
Log.Error ("There is no factory to execute job '{0}'", Name);
Job.Set_Status (AWA.Jobs.Models.FAILED);
DB.Begin_Transaction;
Job.Save (Session => DB);
DB.Commit;
end if;
end;
end;
end Execute;
function Get_Name (Factory : in Job_Factory'Class) return String is
begin
return Ada.Tags.Expanded_Name (Factory'Tag);
end Get_Name;
procedure Set_Work (Job : in out Job_Type;
Work : in Work_Factory'Class) is
begin
Job.Work := Work.Work;
Job.Job.Set_Name (Work.Get_Name);
end Set_Work;
procedure Execute (Job : in out Job_Type) is
begin
Job.Work (Job);
end Execute;
overriding
function Create (Factory : in Work_Factory) return Abstract_Job_Access is
begin
return new Job_Type '(Ada.Finalization.Limited_Controlled with
Work => Factory.Work,
others => <>);
end Create;
-- ------------------------------
-- Job Declaration
-- ------------------------------
-- The <tt>Definition</tt> package must be instantiated with a given job type to
-- register the new job definition.
package body Definition is
function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is
pragma Unreferenced (Factory);
begin
return new T;
end Create;
end Definition;
end AWA.Jobs.Services;
|
-----------------------------------------------------------------------
-- awa-jobs -- 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.Serialize.Tools;
with Util.Log.Loggers;
with Ada.Tags;
with Ada.Calendar;
with Ada.Unchecked_Deallocation;
with ADO.Sessions.Entities;
with AWA.Users.Models;
with AWA.Events.Models;
with AWA.Services.Contexts;
with AWA.Jobs.Modules;
with AWA.Applications;
with AWA.Events.Services;
with AWA.Modules;
package body AWA.Jobs.Services is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services");
-- ------------------------------
-- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>.
-- ------------------------------
procedure Set_Parameter (Job : in out Abstract_Job_Type;
Name : in String;
Value : in String) is
begin
Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value));
end Set_Parameter;
-- ------------------------------
-- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>.
-- ------------------------------
procedure Set_Parameter (Job : in out Abstract_Job_Type;
Name : in String;
Value : in Integer) is
begin
Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value));
end Set_Parameter;
-- ------------------------------
-- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>.
-- The value object can hold any kind of basic value type (integer, enum, date, strings).
-- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised.
-- ------------------------------
procedure Set_Parameter (Job : in out Abstract_Job_Type;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Job.Props.Include (Name, Value);
Job.Props_Modified := True;
end Set_Parameter;
-- ------------------------------
-- Get the job parameter identified by the <b>Name</b> and convert the value into a string.
-- ------------------------------
function Get_Parameter (Job : in Abstract_Job_Type;
Name : in String) return String is
Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name);
begin
return Util.Beans.Objects.To_String (Value);
end Get_Parameter;
-- ------------------------------
-- Get the job parameter identified by the <b>Name</b> and convert the value as an integer.
-- If the parameter is not defined, return the default value passed in <b>Default</b>.
-- ------------------------------
function Get_Parameter (Job : in Abstract_Job_Type;
Name : in String;
Default : in Integer) return Integer is
Pos : constant Util.Beans.Objects.Maps.Cursor := Job.Props.Find (Name);
begin
if Util.Beans.Objects.Maps.Has_Element (Pos) then
declare
Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Element (Pos);
begin
if Util.Beans.Objects.Is_Null (Value) then
return Default;
else
return Util.Beans.Objects.To_Integer (Value);
end if;
end;
else
return Default;
end if;
end Get_Parameter;
-- ------------------------------
-- Get the job parameter identified by the <b>Name</b> and return it as a typed object.
-- ------------------------------
function Get_Parameter (Job : in Abstract_Job_Type;
Name : in String) return Util.Beans.Objects.Object is
begin
return Job.Props.Element (Name);
end Get_Parameter;
-- ------------------------------
-- Get the job status.
-- ------------------------------
function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is
begin
return Job.Job.Get_Status;
end Get_Status;
-- ------------------------------
-- Set the job status.
-- When the job is terminated, it is closed and the job parameters or results cannot be
-- changed.
-- ------------------------------
procedure Set_Status (Job : in out Abstract_Job_Type;
Status : in AWA.Jobs.Models.Job_Status_Type) is
begin
case Job.Job.Get_Status is
when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED =>
raise Closed_Error;
when Models.SCHEDULED | Models.RUNNING =>
Job.Job.Set_Status (Status);
end case;
end Set_Status;
-- ------------------------------
-- Save the job information in the database. Use the database session defined by <b>DB</b>
-- to save the job.
-- ------------------------------
procedure Save (Job : in out Abstract_Job_Type;
DB : in out ADO.Sessions.Master_Session'Class) is
begin
if Job.Results_Modified then
Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results));
Job.Results_Modified := False;
end if;
Job.Job.Save (DB);
end Save;
-- Schedule the job.
procedure Schedule (Job : in out Abstract_Job_Type;
Definition : in Job_Factory'Class) is
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is
begin
Manager.Set_Message_Type (Msg, Job_Create_Event.Kind);
Manager.Set_Event_Queue (Msg, "job-queue");
end Set_Event;
begin
if Job.Job.Is_Inserted then
Log.Error ("Job is already scheduled");
raise Schedule_Error with "The job is already scheduled.";
end if;
AWA.Jobs.Modules.Create_Event (Msg);
Job.Job.Set_Create_Date (Msg.Get_Create_Date);
DB.Begin_Transaction;
Job.Job.Set_Name (Definition.Get_Name);
Job.Job.Set_User (User);
Job.Job.Set_Session (Sess);
Job.Save (DB);
-- Create the event
Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props));
App.Do_Event_Manager (Process => Set_Event'Access);
Msg.Set_User (User);
Msg.Set_Session (Sess);
Msg.Set_Entity_Id (Job.Job.Get_Id);
Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB,
Object => Job.Job.Get_Key));
Msg.Save (DB);
Job.Job.Set_Event (Msg);
Job.Job.Save (DB);
DB.Commit;
end Schedule;
-- ------------------------------
-- Execute the job and save the job information in the database.
-- ------------------------------
procedure Execute (Job : in out Abstract_Job_Type'Class;
DB : in out ADO.Sessions.Master_Session'Class) is
use type AWA.Jobs.Models.Job_Status_Type;
begin
-- Execute the job with an exception guard.
begin
Job.Execute;
exception
when E : others =>
Log.Error ("Exception when executing job {0}", Job.Job.Get_Name);
Log.Error ("Exception:", E, True);
Job.Job.Set_Status (Models.FAILED);
end;
-- If the job did not set a completion status, mark it as terminated.
if Job.Job.Get_Status = Models.SCHEDULED or Job.Job.Get_Status = Models.RUNNING then
Job.Job.Set_Status (Models.TERMINATED);
end if;
-- And save the job.
DB.Begin_Transaction;
Job.Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Job.Save (DB);
DB.Commit;
end Execute;
-- ------------------------------
-- Execute the job associated with the given event.
-- ------------------------------
procedure Execute (Event : in AWA.Events.Module_Event'Class) is
use AWA.Jobs.Modules;
use type AWA.Modules.Module_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Abstract_Job_Type'Class,
Name => Abstract_Job_Access);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
Module : constant AWA.Modules.Module_Access := App.Find_Module (AWA.Jobs.Modules.NAME);
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Job : AWA.Jobs.Models.Job_Ref;
begin
if Module = null then
Log.Warn ("There is no Job module to execute a job");
raise Execute_Error;
end if;
if not (Module.all in AWA.Jobs.Modules.Job_Module'Class) then
Log.Warn ("The 'job' module is not a valid module for job execution");
raise Execute_Error;
end if;
DB.Begin_Transaction;
Job.Load (Session => DB,
Id => Event.Get_Entity_Identifier);
Job.Set_Start_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock));
Job.Set_Status (AWA.Jobs.Models.RUNNING);
Job.Save (Session => DB);
DB.Commit;
declare
Name : constant String := Job.Get_Name;
begin
Log.Info ("Restoring job '{0}'", Name);
declare
Plugin : constant Job_Module_Access := Job_Module'Class (Module.all)'Access;
Factory : constant Job_Factory_Access := Plugin.Find_Factory (Name);
Work : AWA.Jobs.Services.Abstract_Job_Access := null;
begin
if Factory /= null then
Work := Factory.Create;
Work.Job := Job;
Work.Execute (DB);
Free (Work);
else
Log.Error ("There is no factory to execute job '{0}'", Name);
Job.Set_Status (AWA.Jobs.Models.FAILED);
Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
DB.Begin_Transaction;
Job.Save (Session => DB);
DB.Commit;
end if;
end;
end;
end Execute;
function Get_Name (Factory : in Job_Factory'Class) return String is
begin
return Ada.Tags.Expanded_Name (Factory'Tag);
end Get_Name;
procedure Set_Work (Job : in out Job_Type;
Work : in Work_Factory'Class) is
begin
Job.Work := Work.Work;
Job.Job.Set_Name (Work.Get_Name);
end Set_Work;
procedure Execute (Job : in out Job_Type) is
begin
Job.Work (Job);
end Execute;
overriding
function Create (Factory : in Work_Factory) return Abstract_Job_Access is
begin
return new Job_Type '(Ada.Finalization.Limited_Controlled with
Work => Factory.Work,
others => <>);
end Create;
-- ------------------------------
-- Job Declaration
-- ------------------------------
-- The <tt>Definition</tt> package must be instantiated with a given job type to
-- register the new job definition.
package body Definition is
function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is
pragma Unreferenced (Factory);
begin
return new T;
end Create;
end Definition;
end AWA.Jobs.Services;
|
Fix setting the finish date after job execution
|
Fix setting the finish date after job execution
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
4b174bc915390aea8b2eb1837296bb9fbcb5219a
|
src/asf-security-filters.ads
|
src/asf-security-filters.ads
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Sessions;
with ASF.Principals;
with Security.Permissions; use Security;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package ASF.Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
type Auth_Filter is new ASF.Filters.Filter with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class);
-- Set the permission manager that must be used to verify the permission.
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Permissions.Permission_Manager_Access);
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access);
private
type Auth_Filter is new ASF.Filters.Filter with record
Manager : Permissions.Permission_Manager_Access := null;
end record;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Sessions;
with ASF.Principals;
with Security.Policies; use Security;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package ASF.Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
type Auth_Filter is new ASF.Filters.Filter with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class);
-- Set the permission manager that must be used to verify the permission.
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access);
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain);
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access);
private
type Auth_Filter is new ASF.Filters.Filter with record
Manager : Policies.Policy_Manager_Access := null;
end record;
end ASF.Security.Filters;
|
Update after Security package refactorisation
|
Update after Security package refactorisation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
184aa5ceebc31f9a80fdffca2dd4188617a6b067
|
regtests/ado-testsuite.adb
|
regtests/ado-testsuite.adb
|
-----------------------------------------------------------------------
-- ado-testsuite -- Testsuite for ADO
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Tests;
with ADO.Schemas.Tests;
with ADO.Objects.Tests;
with ADO.Queries.Tests;
with ADO.Parameters.Tests;
package body ADO.Testsuite is
use ADO.Tests;
procedure Drivers (Suite : in Util.Tests.Access_Test_Suite);
procedure Drivers (Suite : in Util.Tests.Access_Test_Suite) is separate;
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
ADO.Parameters.Tests.Add_Tests (Ret);
ADO.Objects.Tests.Add_Tests (Ret);
ADO.Tests.Add_Tests (Ret);
ADO.Schemas.Tests.Add_Tests (Ret);
Drivers (Ret);
ADO.Queries.Tests.Add_Tests (Ret);
return Ret;
end Suite;
end ADO.Testsuite;
|
-----------------------------------------------------------------------
-- ado-testsuite -- Testsuite for ADO
-- 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 ADO.Tests;
with ADO.Sequences.Tests;
with ADO.Schemas.Tests;
with ADO.Objects.Tests;
with ADO.Queries.Tests;
with ADO.Parameters.Tests;
package body ADO.Testsuite is
use ADO.Tests;
procedure Drivers (Suite : in Util.Tests.Access_Test_Suite);
procedure Drivers (Suite : in Util.Tests.Access_Test_Suite) is separate;
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
ADO.Parameters.Tests.Add_Tests (Ret);
ADO.Sequences.Tests.Add_Tests (Ret);
ADO.Objects.Tests.Add_Tests (Ret);
ADO.Tests.Add_Tests (Ret);
ADO.Schemas.Tests.Add_Tests (Ret);
Drivers (Ret);
ADO.Queries.Tests.Add_Tests (Ret);
return Ret;
end Suite;
end ADO.Testsuite;
|
Add the sequence factory test
|
Add the sequence factory test
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
f4e1e82bbafdce2123abc039d39115b29473a036
|
awa/samples/src/atlas-server.adb
|
awa/samples/src/atlas-server.adb
|
-----------------------------------------------------------------------
-- Atlas-server -- Application server
-- Copyright (C) 2011 unknown
-- Written by unknown ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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 ASF.Server.Web;
with Atlas.Applications;
procedure Atlas.Server is
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;
begin
Atlas.Applications.Initialize (App);
WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access);
Log.Info ("Connect you browser to: http://localhost:8080/atlas/index.html");
WS.Start;
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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 ASF.Server.Web;
with Atlas.Applications;
procedure Atlas.Server is
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;
begin
Atlas.Applications.Initialize (App);
WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access);
Log.Info ("Connect you browser to: http://localhost:8080/atlas/index.html");
WS.Start;
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;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
49f8fd4029bb595a0cb44a372a7b08620dd6d1e4
|
posix-symlink.adb
|
posix-symlink.adb
|
with C_String;
with Interfaces.C;
with POSIX.Path;
package body POSIX.Symlink is
procedure C_Readlink_Boundary
(File_Name : in String;
Modified_Buffer : out File.File_Name_t;
Modified_Size : out C_Types.Signed_Size_t)
--# derives Modified_Buffer, Modified_Size from File_Name;
is
--# hide C_Readlink_Boundary
function C_Readlink
(Path : in C_String.String_Not_Null_Ptr_t;
Buffer : in C_String.Char_Array_Not_Null_Ptr_t;
Buffer_Size : in C_Types.Size_t) return C_Types.Signed_Size_t;
pragma Import (C, C_Readlink, "readlink");
begin
declare
C_Buffer : aliased Interfaces.C.char_array :=
(Interfaces.C.size_t (File.File_Name_Index_t'First) ..
Interfaces.C.size_t (File.File_Name_Index_t'Last) => Interfaces.C.nul);
C_File_Name_Buffer : aliased Interfaces.C.char_array :=
Interfaces.C.To_C (File_Name, Append_Nul => True);
C_Size : C_Types.Signed_Size_t;
begin
C_Size := C_Readlink
(Path => C_String.To_C_String (C_File_Name_Buffer'Unchecked_Access),
Buffer => C_String.To_C_Char_Array (C_Buffer'Unchecked_Access),
Buffer_Size => C_Buffer'Length);
if C_Size > 0 then
Modified_Buffer (File.File_Name_Index_t'First .. Positive (C_Size)) := C_String.To_String
(Item => C_String.To_C_Char_Array (C_Buffer'Unchecked_Access),
Size => Interfaces.C.size_t (C_Size));
Modified_Size := C_Size;
else
Modified_Size := -1;
end if;
end;
exception
-- Do not propagate exceptions.
when Storage_Error =>
Error.Set_Error (Error.Error_Out_Of_Memory);
Modified_Size := -1;
when others =>
Error.Set_Error (Error.Error_Unknown);
Modified_Size := -1;
end C_Readlink_Boundary;
procedure Read_Link
(File_Name : in String;
Buffer : out File.File_Name_t;
Buffer_Size : out File.File_Name_Size_t;
Error_Value : out Error.Error_t)
is
Returned_Buffer : File.File_Name_t;
Returned_Size : C_Types.Signed_Size_t;
begin
if File_Name'Last > Path.Max_Length then
Error_Value := Error.Error_Name_Too_Long;
Buffer := File.File_Name_t'(File.File_Name_Index_t => Character'Val (0));
Buffer_Size := 0;
else
-- Call system readlink().
C_Readlink_Boundary
(File_Name => File_Name,
Modified_Buffer => Returned_Buffer,
Modified_Size => Returned_Size);
if Returned_Size = -1 then
Error_Value := Error.Get_Error;
Buffer := File.File_Name_t'(File.File_Name_Index_t => Character'Val (0));
Buffer_Size := 0;
else
Error_Value := Error.Error_None;
Buffer := Returned_Buffer;
Buffer_Size := File.File_Name_Size_t (Returned_Size);
end if;
end if;
end Read_Link;
function C_Create_Boundary
(File_Name : in String;
Target : in String) return Error.Return_Value_t is
--# hide C_Create_Boundary
function C_Symlink
(File_Name : in C_String.String_Not_Null_Ptr_t;
Target : in C_String.String_Not_Null_Ptr_t) return Error.Return_Value_t;
pragma Import (C, C_Symlink, "symlink");
begin
declare
C_File_Name_Buffer : aliased Interfaces.C.char_array :=
Interfaces.C.To_C (File_Name, Append_Nul => True);
C_Target_Buffer : aliased Interfaces.C.char_array :=
Interfaces.C.To_C (Target, Append_Nul => True);
begin
return C_Symlink
(Target => C_String.To_C_String (C_File_Name_Buffer'Unchecked_Access),
File_Name => C_String.To_C_String (C_Target_Buffer'Unchecked_Access));
end;
exception
-- Do not propagate exceptions.
when Storage_Error =>
Error.Set_Error (Error.Error_Out_Of_Memory);
return -1;
when others =>
Error.Set_Error (Error.Error_Unknown);
return -1;
end C_Create_Boundary;
procedure Create
(File_Name : in String;
Target : in String;
Error_Value : out Error.Error_t)
is
Names_OK : Boolean;
Return_Value : Error.Return_Value_t;
begin
Error_Value := Error.Error_None;
Names_OK := True;
if File_Name'Last > Path.Max_Length then
Error_Value := Error.Error_Name_Too_Long;
Names_OK := False;
end if;
if Target'Last > Path.Max_Length then
Error_Value := Error.Error_Name_Too_Long;
Names_OK := False;
end if;
if Names_OK then
Return_Value := C_Create_Boundary
(File_Name => File_Name,
Target => Target);
case Return_Value is
when 0 => Error_Value := Error.Error_None;
when -1 => Error_Value := Error.Get_Error;
end case;
end if;
end Create;
end POSIX.Symlink;
|
with C_String;
with Interfaces.C;
with POSIX.Path;
package body POSIX.Symlink is
procedure C_Readlink_Boundary
(File_Name : in String;
Modified_Buffer : out File.File_Name_t;
Modified_Size : out File.File_Name_Size_t;
Read_Error : out Boolean)
--# derives Modified_Buffer, Modified_Size, Read_Error from File_Name;
is
--# hide C_Readlink_Boundary
function C_Readlink
(Path : in C_String.String_Not_Null_Ptr_t;
Buffer : in C_String.Char_Array_Not_Null_Ptr_t;
Buffer_Size : in C_Types.Size_t) return C_Types.Signed_Size_t;
pragma Import (C, C_Readlink, "readlink");
begin
declare
C_Buffer : aliased Interfaces.C.char_array :=
(Interfaces.C.size_t (File.File_Name_Index_t'First) ..
Interfaces.C.size_t (File.File_Name_Index_t'Last) => Interfaces.C.nul);
C_File_Name_Buffer : aliased Interfaces.C.char_array :=
Interfaces.C.To_C (File_Name, Append_Nul => True);
C_Size : C_Types.Signed_Size_t;
begin
C_Size := C_Readlink
(Path => C_String.To_C_String (C_File_Name_Buffer'Unchecked_Access),
Buffer => C_String.To_C_Char_Array (C_Buffer'Unchecked_Access),
Buffer_Size => C_Buffer'Length);
case C_Size is
when -1 =>
Modified_Size := 0;
Read_Error := True;
when C_Types.Signed_Size_t (File.File_Name_Index_t'First) ..
C_Types.Signed_Size_t (File.File_Name_Index_t'Last) =>
Modified_Buffer (File.File_Name_Index_t'First .. Positive (C_Size)) :=
C_String.To_String
(Item => C_String.To_C_Char_Array (C_Buffer'Unchecked_Access),
Size => Interfaces.C.size_t (C_Size));
Modified_Size := File.File_Name_Size_t (C_Size);
Read_Error := False;
when others =>
Error.Set_Error (Error.Error_Out_Of_Range);
Modified_Size := 0;
Read_Error := False;
end case;
end;
exception
-- Do not propagate exceptions.
when Storage_Error =>
Error.Set_Error (Error.Error_Out_Of_Memory);
Modified_Size := 0;
Read_Error := True;
when others =>
Error.Set_Error (Error.Error_Unknown);
Modified_Size := 0;
Read_Error := True;
end C_Readlink_Boundary;
procedure Read_Link
(File_Name : in String;
Buffer : out File.File_Name_t;
Buffer_Size : out File.File_Name_Size_t;
Error_Value : out Error.Error_t)
is
Returned_Buffer : File.File_Name_t;
Returned_Size : File.File_Name_Size_t;
Read_Error : Boolean;
begin
if File_Name'Last > Path.Max_Length then
Error_Value := Error.Error_Name_Too_Long;
Buffer := File.File_Name_t'(File.File_Name_Index_t => Character'Val (0));
Buffer_Size := 0;
else
-- Call system readlink().
C_Readlink_Boundary
(File_Name => File_Name,
Modified_Buffer => Returned_Buffer,
Modified_Size => Returned_Size,
Read_Error => Read_Error);
if Read_Error then
Error_Value := Error.Get_Error;
Buffer := File.File_Name_t'(File.File_Name_Index_t => Character'Val (0));
Buffer_Size := 0;
else
Error_Value := Error.Error_None;
Buffer := Returned_Buffer;
Buffer_Size := Returned_Size;
end if;
end if;
end Read_Link;
function C_Create_Boundary
(File_Name : in String;
Target : in String) return Error.Return_Value_t is
--# hide C_Create_Boundary
function C_Symlink
(File_Name : in C_String.String_Not_Null_Ptr_t;
Target : in C_String.String_Not_Null_Ptr_t) return Error.Return_Value_t;
pragma Import (C, C_Symlink, "symlink");
begin
declare
C_File_Name_Buffer : aliased Interfaces.C.char_array :=
Interfaces.C.To_C (File_Name, Append_Nul => True);
C_Target_Buffer : aliased Interfaces.C.char_array :=
Interfaces.C.To_C (Target, Append_Nul => True);
begin
return C_Symlink
(Target => C_String.To_C_String (C_File_Name_Buffer'Unchecked_Access),
File_Name => C_String.To_C_String (C_Target_Buffer'Unchecked_Access));
end;
exception
-- Do not propagate exceptions.
when Storage_Error =>
Error.Set_Error (Error.Error_Out_Of_Memory);
return -1;
when others =>
Error.Set_Error (Error.Error_Unknown);
return -1;
end C_Create_Boundary;
procedure Create
(File_Name : in String;
Target : in String;
Error_Value : out Error.Error_t)
is
Names_OK : Boolean;
Return_Value : Error.Return_Value_t;
begin
Error_Value := Error.Error_None;
Names_OK := True;
if File_Name'Last > Path.Max_Length then
Error_Value := Error.Error_Name_Too_Long;
Names_OK := False;
end if;
if Target'Last > Path.Max_Length then
Error_Value := Error.Error_Name_Too_Long;
Names_OK := False;
end if;
if Names_OK then
Return_Value := C_Create_Boundary
(File_Name => File_Name,
Target => Target);
case Return_Value is
when 0 => Error_Value := Error.Error_None;
when -1 => Error_Value := Error.Get_Error;
end case;
end if;
end Create;
end POSIX.Symlink;
|
Improve interface for SPARK checking.
|
Improve interface for SPARK checking.
|
Ada
|
isc
|
io7m/coreland-posix-ada,io7m/coreland-posix-ada,io7m/coreland-posix-ada
|
f0e8ad19ac586c4c6509b4517bc4f3d9765fb7ec
|
awa/src/awa-users.ads
|
awa/src/awa-users.ads
|
-----------------------------------------------------------------------
-- awa-users -- Users module
-- Copyright (C) 2009, 2010, 2011, 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.
-----------------------------------------------------------------------
-- = Users Module =
-- The <b>Users.Module</b> manages the creation, update, removal and authentication of users
-- in an application. The module provides the foundations for user management in
-- a web application.
--
-- A user can register himself by using a subscription form. In that case, a verification mail
-- is sent and the user has to follow the verification link defined in the mail to finish
-- the registration process. The user will authenticate using a password.
--
-- A user can also use an OpenID account and be automatically registered.
--
-- A user can have one or several permissions that allow to protect the application data.
-- User permissions are managed by the <b>Permissions.Module</b>.
--
-- @include awa-users-modules.ads
package AWA.Users is
pragma Preelaborate;
end AWA.Users;
|
-----------------------------------------------------------------------
-- awa-users -- Users module
-- Copyright (C) 2009, 2010, 2011, 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.
-----------------------------------------------------------------------
-- = Users Module =
-- The `Users.Module` manages the creation, update, removal and authentication of users
-- in an application. The module provides the foundations for user management in
-- a web application.
--
-- A user can register himself by using a subscription form. In that case, a verification mail
-- is sent and the user has to follow the verification link defined in the mail to finish
-- the registration process. The user will authenticate using a password.
--
-- A user can also use an OpenID account and be automatically registered.
--
-- A user can have one or several permissions that allow to protect the application data.
-- User permissions are managed by the `Permissions.Module`.
--
-- @include awa-users-modules.ads
package AWA.Users is
pragma Preelaborate;
end AWA.Users;
|
Fix user guide presentation
|
Fix user guide presentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1270b66f550dd83bf6b7d6c768131ea98e968d1e
|
awa/src/awa.ads
|
awa/src/awa.ads
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- 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.
-----------------------------------------------------------------------
-- = AWA Core ==
--
-- @include awa-applications.ads
-- @include awa-modules.ads
-- @include awa-permissions.ads
-- @include awa-events.ads
-- @include awa-commands.ads
-- @include awa.xml
package AWA is
pragma Pure;
end AWA;
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- 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.
-----------------------------------------------------------------------
-- = AWA Core ==
--
-- @include awa-applications.ads
-- @include awa-modules.ads
-- @include awa-permissions.ads
-- @include awa-events.ads
-- @include awa-commands.ads
package AWA is
pragma Pure;
end AWA;
|
Fix documentation
|
Fix documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
484cd65e2e79a0c10bf86fa50b33cfb949764895
|
src/wiki-documents.adb
|
src/wiki-documents.adb
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0));
Into.Using_TOC := True;
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST, Len => 0,
Level => Level, others => <>));
end if;
end Add_List_Item;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Level => Level, others => <>));
end Add_Blockquote;
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Preformatted => Text, others => <>));
end Add_Preformatted;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref) is
begin
if Wiki.Nodes.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
-- ------------------------------
-- Append a HTML tag start node to the document.
-- ------------------------------
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
pragma Unreferenced (Tag);
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0));
Into.Using_TOC := True;
end case;
end Append;
-- ------------------------------
-- Append the text with the given format at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST, Len => 0,
Level => Level, others => <>));
end if;
end Add_List_Item;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Into : in out Document;
Level : in Natural) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Level => Level, others => <>));
end Add_Blockquote;
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Preformatted => Text, others => <>));
end Add_Preformatted;
-- ------------------------------
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
-- ------------------------------
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref) is
begin
if Wiki.Nodes.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
end Wiki.Documents;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
898621f491f13ef46cdecfd4de77ef69646e547d
|
src/imago-binary.ads
|
src/imago-binary.ads
|
pragma License (Modified_GPL);
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: Modified GNU GPLv3 or any later as published by Free Software --
-- Foundation (GMGPL). --
-- --
-- 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. --
------------------------------------------------------------------------------
--------------------------------------------------------------------------
-- This package is based on Lumen.Binary package from Lumen library. --
--------------------------------------------------------------------------
package Imago.Binary is
--------------------------------------------------------------------------
Pragma Pure;
--------------------------------------------------------------------------
-----------------------
-- C O N S T A N T S --
-----------------------
--------------------------------------------------------------------------
-- Basic sizes of fundamental binary data types.
Byte_Bits : constant := 8;
Short_Bits: constant := 16;
Word_Bits : constant := 32;
Long_Bits : constant := 64;
--------------------------------------------------------------------------
-- Derived sizes.
Short_Bytes: constant := Short_Bits / Byte_Bits;
Word_Bytes : constant := Word_Bits / Byte_Bits;
Long_Bytes : constant := Long_Bits / Byte_Bits;
--------------------------------------------------------------------------
-- "Last-bit" values for use in rep clauses.
Byte_LB : constant := Byte_Bits - 1;
Short_LB: constant := Short_Bits - 1;
Word_LB : constant := Word_Bits - 1;
Long_LB : constant := Long_Bits - 1;
--------------------------------------------------------------------------
---------------
-- T Y P E S --
---------------
--------------------------------------------------------------------------
-- Unsigned types.
type Byte is mod 2 ** Byte_Bits;
type Short is mod 2 ** Short_Bits;
type Word is mod 2 ** Word_Bits;
type Long is mod 2 ** Long_Bits;
for Byte'Size use Byte_Bits;
for Short'Size use Short_Bits;
for Word'Size use Word_Bits;
for Long'Size use Long_Bits;
--------------------------------------------------------------------------
-- Signed types.
type S_Byte is new Integer range -(2 ** Byte_LB) .. (2 ** Byte_LB) - 1;
type S_Short is new Integer range -(2 ** Short_LB) .. (2 ** Short_LB) - 1;
type S_Word is new Integer range -(2 ** Word_LB) .. (2 ** Word_LB) - 1;
type S_Long is new Long_Integer range -(2 ** Long_LB) .. (2 ** Long_LB) - 1;
for S_Byte'Size use Byte_Bits;
for S_Short'Size use Short_Bits;
for S_Word'Size use Word_Bits;
for S_Long'Size use Long_Bits;
--------------------------------------------------------------------------
-- Array types.
type Byte_Array is array (Natural range <>) of Byte;
type Short_Array is array (Natural range <>) of Byte;
type Word_Array is array (Natural range <>) of Word;
type Long_Array is array (Natural range <>) of Long;
type S_Byte_Array is array (Natural range <>) of S_Byte;
type S_Short_Array is array (Natural range <>) of S_Short;
type S_Word_Array is array (Natural range <>) of S_Word;
type S_Long_Array is array (Natural range <>) of S_Long;
---------------------------------------------------------------------------
end Imago.Binary;
|
pragma License (Modified_GPL);
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: Modified GNU GPLv3 or any later as published by Free Software --
-- Foundation (GMGPL). --
-- --
-- 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. --
------------------------------------------------------------------------------
--------------------------------------------------------------------------
-- This package is based on Lumen.Binary package from Lumen library. --
--------------------------------------------------------------------------
package Imago.Binary is
--------------------------------------------------------------------------
Pragma Pure;
--------------------------------------------------------------------------
-----------------------
-- C O N S T A N T S --
-----------------------
--------------------------------------------------------------------------
-- Basic sizes of fundamental binary data types.
Byte_Bits : constant := 8;
Short_Bits: constant := 16;
Word_Bits : constant := 32;
Long_Bits : constant := 64;
--------------------------------------------------------------------------
-- Derived sizes.
Short_Bytes: constant := Short_Bits / Byte_Bits;
Word_Bytes : constant := Word_Bits / Byte_Bits;
Long_Bytes : constant := Long_Bits / Byte_Bits;
--------------------------------------------------------------------------
-- "Last-bit" values for use in rep clauses.
Byte_LB : constant := Byte_Bits - 1;
Short_LB: constant := Short_Bits - 1;
Word_LB : constant := Word_Bits - 1;
Long_LB : constant := Long_Bits - 1;
--------------------------------------------------------------------------
---------------
-- T Y P E S --
---------------
--------------------------------------------------------------------------
-- Unsigned types.
type Byte is mod 2 ** Byte_Bits;
type Short is mod 2 ** Short_Bits;
type Word is mod 2 ** Word_Bits;
type Long is mod 2 ** Long_Bits;
for Byte'Size use Byte_Bits;
for Short'Size use Short_Bits;
for Word'Size use Word_Bits;
for Long'Size use Long_Bits;
--------------------------------------------------------------------------
-- Signed types.
type S_Byte is new Integer range -(2 ** Byte_LB) .. (2 ** Byte_LB) - 1;
type S_Short is new Integer range -(2 ** Short_LB) .. (2 ** Short_LB) - 1;
type S_Word is new Integer range -(2 ** Word_LB) .. (2 ** Word_LB) - 1;
type S_Long is new Long_Integer range -(2 ** Long_LB) .. (2 ** Long_LB) - 1;
for S_Byte'Size use Byte_Bits;
for S_Short'Size use Short_Bits;
for S_Word'Size use Word_Bits;
for S_Long'Size use Long_Bits;
--------------------------------------------------------------------------
-- Array types.
type Byte_Array is array (Natural range <>) of Byte;
type Short_Array is array (Natural range <>) of Short;
type Word_Array is array (Natural range <>) of Word;
type Long_Array is array (Natural range <>) of Long;
type S_Byte_Array is array (Natural range <>) of S_Byte;
type S_Short_Array is array (Natural range <>) of S_Short;
type S_Word_Array is array (Natural range <>) of S_Word;
type S_Long_Array is array (Natural range <>) of S_Long;
---------------------------------------------------------------------------
end Imago.Binary;
|
Fix typo in Imago.Binary.
|
Fix typo in Imago.Binary.
Special thx to ovenpasta for spotting this.
Signed-off-by: darkestkhan <[email protected]>
|
Ada
|
isc
|
darkestkhan/imago
|
7292a021be43b3f8574b659e491c640600c4f7b9
|
src/security-oauth-servers.ads
|
src/security-oauth-servers.ads
|
-----------------------------------------------------------------------
-- security-oauth-servers -- OAuth Server Authentication Support
-- Copyright (C) 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Strings;
with Security.Auth;
with Security.Permissions;
-- == OAuth Server ==
-- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package.
-- This package allows to implement the authorization framework described in RFC 6749
-- The OAuth 2.0 Authorization Framework.
--
-- The authorization method produce a <tt>Grant_Type</tt> object that contains the result
-- of the grant (successful or denied). It is the responsibility of the caller to format
-- the result in JSON/XML and return it to the client.
--
-- Three important operations are defined for the OAuth 2.0 framework.
--
-- <tt>Authorize</tt> is used to obtain an authorization request. This operation is
-- optional in the OAuth 2.0 framework since some authorization method directly return
-- the access token. This operation is used by the "Authorization Code Grant" and the
-- "Implicit Grant".
--
-- <tt>Token</tt> is used to get the access token and optional refresh token.
--
-- <tt>Authenticate</tt> is used for the API request to verify the access token
-- and authenticate the API call.
-- Several grant types are supported.
--
-- === Application Manager ===
-- The application manager maintains the repository of applications which are known by
-- the server and which can request authorization. Each application is identified by
-- a client identifier (represented by the <tt>client_id</tt> request parameter).
-- The application defines the authorization methods which are allowed as well as
-- the parameters to control and drive the authorization. This includes the redirection
-- URI, the application secret, the expiration delay for the access token.
--
-- The application manager is implemented by the application server and it must
-- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt>
-- method. The <tt>Find_Application</tt> is one of the first call made during the
-- authenticate and token generation phases.
--
-- === Resource Owner Password Credentials Grant ===
-- The password grant is one of the easiest grant method to understand but it is also one
-- of the less secure. In this grant method, the username and user password are passed in
-- the request parameter together with the application client identifier. The realm verifies
-- the username and password and when they are correct it generates the access token with
-- an optional refresh token.
--
-- Realm : Security.OAuth.Servers.Auth_Manager;
-- Grant : Security.OAuth.Servers.Grant_Type;
--
-- Realm.Authorize (Params, Grant);
--
-- === Accessing Protected Resources ===
-- When accessing a protected resource, the API implementation will use the
-- <tt>Authenticate</tt> operation to verify the access token and get a security principal.
-- The security principal will identifies the resource owner as well as the application
-- that is doing the call.
--
-- Realm : Security.OAuth.Servers.Auth_Manager;
-- Auth : Security.Principal_Access;
-- Token : String := ...;
--
-- Realm.Authenticate (Token, Auth);
--
-- When a security principal is returned, the access token was validated and the
-- request is granted for the application.
--
package Security.OAuth.Servers is
Invalid_Application : exception;
type Application is new Security.OAuth.Application with private;
-- Check if the application has the given permission.
function Has_Permission (App : in Application;
Permission : in Security.Permissions.Permission_Index) return Boolean;
-- Define the status of the grant.
type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant,
Stealed_Grant, Valid_Grant);
-- Define the grant type.
type Grant_Kind is (No_Grant, Access_Grant, Code_Grant,
Implicit_Grant, Password_Grant, Credential_Grant,
Extension_Grant);
-- The <tt>Grant_Type</tt> holds the results of the authorization.
-- When the grant is refused, the type holds information about the refusal.
type Grant_Type is record
-- The request grant type.
Request : Grant_Kind := No_Grant;
-- The response status.
Status : Grant_Status := Invalid_Grant;
-- When success, the token to return.
Token : Ada.Strings.Unbounded.Unbounded_String;
-- When success, the token expiration date.
Expires : Ada.Calendar.Time;
-- When success, the authentication principal.
Auth : Security.Principal_Access;
-- When error, the type of error to return.
Error : Util.Strings.Name_Access;
end record;
type Application_Manager is limited interface;
type Application_Manager_Access is access all Application_Manager'Class;
-- Find the application that correspond to the given client id.
-- The <tt>Invalid_Application</tt> exception should be raised if there is no such application.
function Find_Application (Realm : in Application_Manager;
Client_Id : in String) return Application'Class is abstract;
type Realm_Manager is limited interface;
type Realm_Manager_Access is access all Realm_Manager'Class;
-- Authenticate the token and find the associated authentication principal.
-- The access token has been verified and the token represents the identifier
-- of the Tuple (client_id, user, session) that describes the authentication.
-- The <tt>Authenticate</tt> procedure should look in its database (internal
-- or external) to find the authentication principal that was granted for
-- the token Tuple. When the token was not found (because it was revoked),
-- the procedure should return a null principal. If the authentication
-- principal can be cached, the <tt>Cacheable</tt> value should be set.
-- In that case, the access token and authentication principal are inserted
-- in a cache.
procedure Authenticate (Realm : in out Realm_Manager;
Token : in String;
Auth : out Principal_Access;
Cacheable : out Boolean) is abstract;
-- Create an auth token string that identifies the given principal. The returned
-- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The
-- returned token does not need to be signed. It will be inserted in the public part
-- of the returned access token.
function Authorize (Realm : in Realm_Manager;
App : in Application'Class;
Scope : in String;
Auth : in Principal_Access) return String is abstract;
procedure Verify (Realm : in out Realm_Manager;
Username : in String;
Password : in String;
Auth : out Principal_Access) is abstract;
procedure Verify (Realm : in out Realm_Manager;
Token : in String;
Auth : out Principal_Access) is abstract;
procedure Revoke (Realm : in out Realm_Manager;
Auth : in Principal_Access) is abstract;
type Auth_Manager is tagged limited private;
type Auth_Manager_Access is access all Auth_Manager'Class;
-- Set the auth private key.
procedure Set_Private_Key (Manager : in out Auth_Manager;
Key : in String);
-- Set the application manager to use and and applications.
procedure Set_Application_Manager (Manager : in out Auth_Manager;
Repository : in Application_Manager_Access);
-- Set the realm manager to authentify users.
procedure Set_Realm_Manager (Manager : in out Auth_Manager;
Realm : in Realm_Manager_Access);
-- Authorize the access to the protected resource by the application and for the
-- given principal. The resource owner has been verified and is represented by the
-- <tt>Auth</tt> principal. Extract from the request parameters represented by
-- <tt>Params</tt> the application client id, the scope and the expected response type.
-- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749.
procedure Authorize (Realm : in out Auth_Manager;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
procedure Token (Realm : in out Auth_Manager;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
-- Make the access token from the authorization code that was created by the
-- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the
-- client secret and the validity of the authorization code. Extract from the
-- authorization code the auth principal that was used for the grant and make the
-- access token.
procedure Token_From_Code (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
procedure Authorize_Code (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
procedure Authorize_Token (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
-- Make the access token from the resource owner password credentials. The username,
-- password and scope are extracted from the request and they are verified through the
-- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the
-- principal describes the authorization and it is used to forge the access token.
-- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant.
procedure Token_From_Password (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
-- RFC 6749: 5. Issuing an Access Token
procedure Create_Token (Realm : in Auth_Manager;
Ident : in String;
Grant : in out Grant_Type);
-- Authenticate the access token and get a security principal that identifies the app/user.
-- See RFC 6749, 7. Accessing Protected Resources.
-- The access token is first searched in the cache. If it was found, it means the access
-- token was already verified in the past, it is granted and associated with a principal.
-- Otherwise, we have to verify the token signature first, then the expiration date and
-- we extract from the token public part the auth identification. The <tt>Authenticate</tt>
-- operation is then called to obtain the principal from the auth identification.
-- When access token is invalid or authentification cannot be verified, a null principal
-- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason
-- of failures (if any).
procedure Authenticate (Realm : in out Auth_Manager;
Token : in String;
Grant : out Grant_Type);
procedure Revoke (Realm : in out Auth_Manager;
Token : in String);
private
use Ada.Strings.Unbounded;
function Format_Expire (Expire : in Ada.Calendar.Time) return String;
type Application is new Security.OAuth.Application with record
Expire_Timeout : Duration := 3600.0;
Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET;
end record;
type Cache_Entry is record
Expire : Ada.Calendar.Time;
Auth : Principal_Access;
end record;
package Cache_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Cache_Entry,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
-- The access token cache is used to speed up the access token verification
-- when a request to a protected resource is made.
protected type Token_Cache is
procedure Authenticate (Token : in String;
Grant : in out Grant_Type);
procedure Insert (Token : in String;
Expire : in Ada.Calendar.Time;
Principal : in Principal_Access);
procedure Remove (Token : in String);
procedure Timeout;
private
Entries : Cache_Map.Map;
end Token_Cache;
type Auth_Manager is new Ada.Finalization.Limited_Controlled with record
-- The repository of applications.
Repository : Application_Manager_Access;
-- The realm for user authentication.
Realm : Realm_Manager_Access;
-- The server private key used by the HMAC signature.
Private_Key : Ada.Strings.Unbounded.Unbounded_String;
-- The access token cache.
Cache : Token_Cache;
-- The expiration time for the generated authorization code.
Expire_Code : Duration := 300.0;
end record;
-- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>)
type Token_Validity is record
Status : Grant_Status := Invalid_Grant;
Ident_Start : Natural := 0;
Ident_End : Natural := 0;
Expire : Ada.Calendar.Time;
end record;
function Validate (Realm : in Auth_Manager;
Client_Id : in String;
Token : in String) return Token_Validity;
end Security.OAuth.Servers;
|
-----------------------------------------------------------------------
-- security-oauth-servers -- OAuth Server Authentication Support
-- Copyright (C) 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Strings;
with Security.Auth;
with Security.Permissions;
-- == OAuth Server ==
-- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package.
-- This package allows to implement the authorization framework described in RFC 6749
-- The OAuth 2.0 Authorization Framework.
--
-- The authorization method produce a <tt>Grant_Type</tt> object that contains the result
-- of the grant (successful or denied). It is the responsibility of the caller to format
-- the result in JSON/XML and return it to the client.
--
-- Three important operations are defined for the OAuth 2.0 framework.
--
-- <tt>Authorize</tt> is used to obtain an authorization request. This operation is
-- optional in the OAuth 2.0 framework since some authorization method directly return
-- the access token. This operation is used by the "Authorization Code Grant" and the
-- "Implicit Grant".
--
-- <tt>Token</tt> is used to get the access token and optional refresh token.
--
-- <tt>Authenticate</tt> is used for the API request to verify the access token
-- and authenticate the API call.
-- Several grant types are supported.
--
-- === Application Manager ===
-- The application manager maintains the repository of applications which are known by
-- the server and which can request authorization. Each application is identified by
-- a client identifier (represented by the <tt>client_id</tt> request parameter).
-- The application defines the authorization methods which are allowed as well as
-- the parameters to control and drive the authorization. This includes the redirection
-- URI, the application secret, the expiration delay for the access token.
--
-- The application manager is implemented by the application server and it must
-- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt>
-- method. The <tt>Find_Application</tt> is one of the first call made during the
-- authenticate and token generation phases.
--
-- === Resource Owner Password Credentials Grant ===
-- The password grant is one of the easiest grant method to understand but it is also one
-- of the less secure. In this grant method, the username and user password are passed in
-- the request parameter together with the application client identifier. The realm verifies
-- the username and password and when they are correct it generates the access token with
-- an optional refresh token.
--
-- Realm : Security.OAuth.Servers.Auth_Manager;
-- Grant : Security.OAuth.Servers.Grant_Type;
--
-- Realm.Authorize (Params, Grant);
--
-- === Accessing Protected Resources ===
-- When accessing a protected resource, the API implementation will use the
-- <tt>Authenticate</tt> operation to verify the access token and get a security principal.
-- The security principal will identifies the resource owner as well as the application
-- that is doing the call.
--
-- Realm : Security.OAuth.Servers.Auth_Manager;
-- Auth : Security.Principal_Access;
-- Token : String := ...;
--
-- Realm.Authenticate (Token, Auth);
--
-- When a security principal is returned, the access token was validated and the
-- request is granted for the application.
--
package Security.OAuth.Servers is
Invalid_Application : exception;
type Application is new Security.OAuth.Application with private;
-- Check if the application has the given permission.
function Has_Permission (App : in Application;
Permission : in Security.Permissions.Permission_Index) return Boolean;
-- Define the status of the grant.
type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant,
Stealed_Grant, Valid_Grant);
-- Define the grant type.
type Grant_Kind is (No_Grant, Access_Grant, Code_Grant,
Implicit_Grant, Password_Grant, Credential_Grant,
Extension_Grant);
-- The <tt>Grant_Type</tt> holds the results of the authorization.
-- When the grant is refused, the type holds information about the refusal.
type Grant_Type is record
-- The request grant type.
Request : Grant_Kind := No_Grant;
-- The response status.
Status : Grant_Status := Invalid_Grant;
-- When success, the token to return.
Token : Ada.Strings.Unbounded.Unbounded_String;
-- When success, the token expiration date.
Expires : Ada.Calendar.Time;
-- When success, the authentication principal.
Auth : Security.Principal_Access;
-- When error, the type of error to return.
Error : Util.Strings.Name_Access;
end record;
type Application_Manager is limited interface;
type Application_Manager_Access is access all Application_Manager'Class;
-- Find the application that correspond to the given client id.
-- The <tt>Invalid_Application</tt> exception should be raised if there is no such application.
function Find_Application (Realm : in Application_Manager;
Client_Id : in String) return Application'Class is abstract;
type Realm_Manager is limited interface;
type Realm_Manager_Access is access all Realm_Manager'Class;
-- Authenticate the token and find the associated authentication principal.
-- The access token has been verified and the token represents the identifier
-- of the Tuple (client_id, user, session) that describes the authentication.
-- The <tt>Authenticate</tt> procedure should look in its database (internal
-- or external) to find the authentication principal that was granted for
-- the token Tuple. When the token was not found (because it was revoked),
-- the procedure should return a null principal. If the authentication
-- principal can be cached, the <tt>Cacheable</tt> value should be set.
-- In that case, the access token and authentication principal are inserted
-- in a cache.
procedure Authenticate (Realm : in out Realm_Manager;
Token : in String;
Auth : out Principal_Access;
Cacheable : out Boolean) is abstract;
-- Create an auth token string that identifies the given principal. The returned
-- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The
-- returned token does not need to be signed. It will be inserted in the public part
-- of the returned access token.
function Authorize (Realm : in Realm_Manager;
App : in Application'Class;
Scope : in String;
Auth : in Principal_Access) return String is abstract;
procedure Verify (Realm : in out Realm_Manager;
Username : in String;
Password : in String;
Auth : out Principal_Access) is abstract;
procedure Verify (Realm : in out Realm_Manager;
Token : in String;
Auth : out Principal_Access) is abstract;
procedure Revoke (Realm : in out Realm_Manager;
Auth : in Principal_Access) is abstract;
type Auth_Manager is tagged limited private;
type Auth_Manager_Access is access all Auth_Manager'Class;
-- Set the auth private key.
procedure Set_Private_Key (Manager : in out Auth_Manager;
Key : in String);
-- Set the application manager to use and and applications.
procedure Set_Application_Manager (Manager : in out Auth_Manager;
Repository : in Application_Manager_Access);
-- Set the realm manager to authentify users.
procedure Set_Realm_Manager (Manager : in out Auth_Manager;
Realm : in Realm_Manager_Access);
-- Authorize the access to the protected resource by the application and for the
-- given principal. The resource owner has been verified and is represented by the
-- <tt>Auth</tt> principal. Extract from the request parameters represented by
-- <tt>Params</tt> the application client id, the scope and the expected response type.
-- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749.
procedure Authorize (Realm : in out Auth_Manager;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
procedure Token (Realm : in out Auth_Manager;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
-- Make the access token from the authorization code that was created by the
-- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the
-- client secret and the validity of the authorization code. Extract from the
-- authorization code the auth principal that was used for the grant and make the
-- access token.
procedure Token_From_Code (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
procedure Authorize_Code (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
procedure Authorize_Token (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
-- Make the access token from the resource owner password credentials. The username,
-- password and scope are extracted from the request and they are verified through the
-- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the
-- principal describes the authorization and it is used to forge the access token.
-- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant.
procedure Token_From_Password (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
-- RFC 6749: 5. Issuing an Access Token
procedure Create_Token (Realm : in Auth_Manager;
Ident : in String;
Grant : in out Grant_Type);
-- Authenticate the access token and get a security principal that identifies the app/user.
-- See RFC 6749, 7. Accessing Protected Resources.
-- The access token is first searched in the cache. If it was found, it means the access
-- token was already verified in the past, it is granted and associated with a principal.
-- Otherwise, we have to verify the token signature first, then the expiration date and
-- we extract from the token public part the auth identification. The <tt>Authenticate</tt>
-- operation is then called to obtain the principal from the auth identification.
-- When access token is invalid or authentification cannot be verified, a null principal
-- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason
-- of failures (if any).
procedure Authenticate (Realm : in out Auth_Manager;
Token : in String;
Grant : out Grant_Type);
procedure Revoke (Realm : in out Auth_Manager;
Token : in String);
private
use Ada.Strings.Unbounded;
function Format_Expire (Expire : in Ada.Calendar.Time) return String;
type Application is new Security.OAuth.Application with record
Expire_Timeout : Duration := 3600.0;
Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET;
end record;
type Cache_Entry is record
Expire : Ada.Calendar.Time;
Auth : Principal_Access;
end record;
package Cache_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Cache_Entry,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
-- The access token cache is used to speed up the access token verification
-- when a request to a protected resource is made.
protected type Token_Cache is
procedure Authenticate (Token : in String;
Grant : in out Grant_Type);
procedure Insert (Token : in String;
Expire : in Ada.Calendar.Time;
Principal : in Principal_Access);
procedure Remove (Token : in String);
procedure Timeout;
private
Entries : Cache_Map.Map;
end Token_Cache;
type Auth_Manager is new Ada.Finalization.Limited_Controlled with record
-- The repository of applications.
Repository : Application_Manager_Access;
-- The realm for user authentication.
Realm : Realm_Manager_Access;
-- The server private key used by the HMAC signature.
Private_Key : Ada.Strings.Unbounded.Unbounded_String;
-- The access token cache.
Cache : Token_Cache;
-- The expiration time for the generated authorization code.
Expire_Code : Duration := 300.0;
end record;
-- The <tt>Token_Validity</tt> record provides information about a token to find out
-- the different components it is made of and verify its validity. The <tt>Validate</tt>
-- procedure is in charge of checking the components and verifying the HMAC signature.
-- The token has the following format:
-- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>)
type Token_Validity is record
Status : Grant_Status := Invalid_Grant;
Ident_Start : Natural := 0;
Ident_End : Natural := 0;
Expire : Ada.Calendar.Time;
end record;
function Validate (Realm : in Auth_Manager;
Client_Id : in String;
Token : in String) return Token_Validity;
end Security.OAuth.Servers;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
fdf21d4bc94db41c8a9116bfe3be23e7c0d62aa2
|
awa/src/awa-events.ads
|
awa/src/awa-events.ads
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- 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.Strings;
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Objects.Maps;
with ADO;
-- == Introduction ==
-- The <b>AWA.Events</b> package defines an event framework for modules to post events
-- and have Ada bean methods be invoked when these events are dispatched. Subscription to
-- events is done through configuration files. This allows to configure the modules and
-- integrate them together easily at configuration time.
--
-- === Declaration ===
-- Modules define the events that they can generate by instantiating the <b>Definition</b>
-- package. This is a static definition of the event. Each event is given a unique name.
--
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- === Posting an event ===
-- The module can post an event to inform other modules or the system that a particular
-- action occurred. The module creates the event instance of type <b>Module_Event</b> and
-- populates that event with useful properties for event receivers.
--
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- === Receiving an event ===
-- Modules or applications interested by a particular event will configure the event manager
-- to dispatch the event to an Ada bean event action. The Ada bean is an object that must
-- implement a procedure that matches the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- The configuration file indicates how to bind the Ada bean action and the event together.
-- The action is specified using an EL Method Expression (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
-- === Event queues and dispatchers ===
-- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them.
-- There are two kinds of dispatchers:
--
-- * Synchronous dispatcher process the event when it is posted. The task which posts
-- the event invokes the Ada bean action. In this dispatching mode, there is no event queue.
-- If the action method raises an exception, it will however be blocked.
--
-- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event
-- queue. A dispatcher task processes the event and invokes the action method at a later
-- time.
--
-- When the event is queued, there are two types of event queues:
--
-- * A Fifo memory queue manages the event and dispatches them in FIFO order.
-- If the application is stopped, the events present in the Fifo queue are lost.
--
-- * A persistent event queue manages the event in a similar way as the FIFO queue but
-- saves them in the database. If the application is stopped, events that have not yet
-- been processed will be dispatched when the application is started again.
--
-- == Data Model ==
-- @include Queues.hbm.xml
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
-- ------------------------------
-- Event kind definition
-- ------------------------------
-- This package must be instantiated for each event that a module can post.
generic
Name : String;
package Definition is
function Kind return Event_Index;
pragma Inline_Always (Kind);
end Definition;
-- Exception raised if an event name is not found.
Not_Found : exception;
-- Identifies an invalid event.
Invalid_Event : constant Event_Index := 0;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String) return Event_Index;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
-- Get the entity identifier associated with the event.
function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier;
-- Set the entity identifier associated with the event.
procedure Set_Entity_Identifier (Event : in out Module_Event;
Id : in ADO.Identifier);
-- Copy the event properties to the map passed in <tt>Into</tt>.
procedure Copy (Event : in Module_Event;
Into : in out Util.Beans.Objects.Maps.Map);
private
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Invalid_Event;
Props : Util.Beans.Objects.Maps.Map;
Entity : ADO.Identifier;
Entity_Type : ADO.Entity_Type;
end record;
-- The index of the last event definition.
Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
-----------------------------------------------------------------------
-- awa-events -- AWA Events
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Events;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Objects.Maps;
with ADO;
-- == Introduction ==
-- The <b>AWA.Events</b> package defines an event framework for modules to post events
-- and have Ada bean methods be invoked when these events are dispatched. Subscription to
-- events is done through configuration files. This allows to configure the modules and
-- integrate them together easily at configuration time.
--
-- === Declaration ===
-- Modules define the events that they can generate by instantiating the <b>Definition</b>
-- package. This is a static definition of the event. Each event is given a unique name.
--
-- package Event_New_User is new AWA.Events.Definition ("new-user");
--
-- === Posting an event ===
-- The module can post an event to inform other modules or the system that a particular
-- action occurred. The module creates the event instance of type <b>Module_Event</b> and
-- populates that event with useful properties for event receivers.
--
-- Event : AWA.Events.Module_Event;
--
-- Event.Set_Event_Kind (Event_New_User.Kind);
-- Event.Set_Parameter ("email", "[email protected]");
--
-- The module will post the event by using the <b>Send_Event</b> operation.
--
-- Manager.Send_Event (Event);
--
-- === Receiving an event ===
-- Modules or applications interested by a particular event will configure the event manager
-- to dispatch the event to an Ada bean event action. The Ada bean is an object that must
-- implement a procedure that matches the prototype:
--
-- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...;
-- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class);
--
-- The Ada bean method and object are registered as other Ada beans.
--
-- The configuration file indicates how to bind the Ada bean action and the event together.
-- The action is specified using an EL Method Expression (See Ada EL or JSR 245).
--
-- <on-event name="new_user">
-- <action>#{ada_bean.action}</action>
-- </on-event>
--
-- === Event queues and dispatchers ===
-- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them.
-- There are two kinds of dispatchers:
--
-- * Synchronous dispatcher process the event when it is posted. The task which posts
-- the event invokes the Ada bean action. In this dispatching mode, there is no event queue.
-- If the action method raises an exception, it will however be blocked.
--
-- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event
-- queue. A dispatcher task processes the event and invokes the action method at a later
-- time.
--
-- When the event is queued, there are two types of event queues:
--
-- * A Fifo memory queue manages the event and dispatches them in FIFO order.
-- If the application is stopped, the events present in the Fifo queue are lost.
--
-- * A persistent event queue manages the event in a similar way as the FIFO queue but
-- saves them in the database. If the application is stopped, events that have not yet
-- been processed will be dispatched when the application is started again.
--
-- == Data Model ==
-- @include Queues.hbm.xml
--
package AWA.Events is
type Queue_Index is new Natural;
type Event_Index is new Natural;
-- ------------------------------
-- Event kind definition
-- ------------------------------
-- This package must be instantiated for each event that a module can post.
generic
Name : String;
package Definition is
function Kind return Event_Index;
pragma Inline_Always (Kind);
end Definition;
-- Exception raised if an event name is not found.
Not_Found : exception;
-- Identifies an invalid event.
Invalid_Event : constant Event_Index := 0;
-- Find the event runtime index given the event name.
-- Raises Not_Found exception if the event name is not recognized.
function Find_Event_Index (Name : in String) return Event_Index;
-- ------------------------------
-- Module event
-- ------------------------------
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private;
type Module_Event_Access is access all Module_Event'Class;
-- Set the event type which identifies the event.
procedure Set_Event_Kind (Event : in out Module_Event;
Kind : in Event_Index);
-- Get the event type which identifies the event.
function Get_Event_Kind (Event : in Module_Event) return Event_Index;
-- Set a parameter on the message.
procedure Set_Parameter (Event : in out Module_Event;
Name : in String;
Value : in String);
-- Get the parameter with the given name.
function Get_Parameter (Event : in Module_Event;
Name : in String) return String;
-- Get the value that corresponds to the parameter with the given name.
overriding
function Get_Value (Event : in Module_Event;
Name : in String) return Util.Beans.Objects.Object;
-- Get the entity identifier associated with the event.
function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier;
-- Set the entity identifier associated with the event.
procedure Set_Entity_Identifier (Event : in out Module_Event;
Id : in ADO.Identifier);
-- Copy the event properties to the map passed in <tt>Into</tt>.
procedure Copy (Event : in Module_Event;
Into : in out Util.Beans.Objects.Maps.Map);
private
type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record
Kind : Event_Index := Invalid_Event;
Props : Util.Beans.Objects.Maps.Map;
Entity : ADO.Identifier := ADO.NO_IDENTIFIER;
Entity_Type : ADO.Entity_Type;
end record;
-- The index of the last event definition.
Last_Event : Event_Index := 0;
-- Get the event type name.
function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access;
-- Make and return a copy of the event.
function Copy (Event : in Module_Event) return Module_Event_Access;
end AWA.Events;
|
Fix uninitialized member 'Entity'
|
Fix uninitialized member 'Entity'
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a139707b876a0b5794acfd6474a0f3ae43554ae8
|
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.Utils;
with ADO.Sessions;
with ADO.Sessions.Entities;
with Util.Beans.Lists.Strings;
with AWA.Tags.Modules;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- 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 Name = "tags" then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.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
declare
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Service.Load_Question (From, Id);
From.Tags.Load_Tags (DB, Id);
end;
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);
Bean.Tags.Update_Tags (Bean.Get_Id);
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;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE);
Object.Tags.Set_Permission ("question-edit");
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_Empty (Value) then
From.Service.Load_Answer (From, From.Question,
ADO.Utils.To_Identifier (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.Utils.To_Identifier (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
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Answer (Answer => Bean);
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;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
Pos : Natural;
begin
if Name = "tags" then
Pos := From.Questions.Get_Row_Index;
if Pos = 0 then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Models.Question_Info := From.Questions.List.Element (Pos - 1);
begin
return From.Tags.Get_Tags (Item.Id);
end;
elsif Name = "questions" then
return Util.Beans.Objects.To_Object (Value => From.Questions_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "tag" then
return Util.Beans.Objects.To_Object (From.Tag);
else
return From.Questions.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "tag" then
From.Tag := Util.Beans.Objects.To_Unbounded_String (Value);
From.Load_List;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of question. If a tag was set, filter the list of questions with the tag.
-- ------------------------------
procedure Load_List (Into : in out Question_List_Bean) is
use AWA.Questions.Models;
use AWA.Services;
use type ADO.Identifier;
Session : ADO.Sessions.Session := Into.Service.Get_Session;
Query : ADO.Queries.Context;
Tag_Id : ADO.Identifier;
begin
AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id);
if Tag_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List);
Query.Bind_Param (Name => "tag", Value => Tag_Id);
else
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
end if;
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Into.Questions, Session, Query);
declare
List : ADO.Utils.Identifier_Vector;
Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First;
begin
while Question_Info_Vectors.Has_Element (Iter) loop
List.Append (Question_Info_Vectors.Element (Iter).Id);
Question_Info_Vectors.Next (Iter);
end loop;
Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all,
List);
end;
end Load_List;
-- ------------------------------
-- 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_List_Bean_Access := new Question_List_Bean;
-- Session : ADO.Sessions.Session := Module.Get_Session;
-- Query : ADO.Queries.Context;
begin
Object.Service := Module;
Object.Questions_Bean := Object.Questions'Unchecked_Access;
-- 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.Questions, Session, Query);
Object.Load_List;
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);
elsif Name = "tags" then
return Util.Beans.Objects.To_Object (Value => From.Tags_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;
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Id);
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);
-- Load the tags if any.
From.Tags.Load_Tags (Session, Id);
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;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE);
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Utils;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Tags.Modules;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- 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 Name = "tags" then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.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
declare
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Service.Load_Question (From, Id);
From.Tags.Load_Tags (DB, Id);
end;
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);
Bean.Tags.Update_Tags (Bean.Get_Id);
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;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE);
Object.Tags.Set_Permission ("question-edit");
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_Empty (Value) then
From.Service.Load_Answer (From, From.Question,
ADO.Utils.To_Identifier (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.Utils.To_Identifier (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
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Answer (Answer => Bean);
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;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
Pos : Natural;
begin
if Name = "tags" then
Pos := From.Questions.Get_Row_Index;
if Pos = 0 then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Models.Question_Info := From.Questions.List.Element (Pos - 1);
begin
return From.Tags.Get_Tags (Item.Id);
end;
elsif Name = "questions" then
return Util.Beans.Objects.To_Object (Value => From.Questions_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "tag" then
return Util.Beans.Objects.To_Object (From.Tag);
else
return From.Questions.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "tag" then
From.Tag := Util.Beans.Objects.To_Unbounded_String (Value);
From.Load_List;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of question. If a tag was set, filter the list of questions with the tag.
-- ------------------------------
procedure Load_List (Into : in out Question_List_Bean) is
use AWA.Questions.Models;
use AWA.Services;
use type ADO.Identifier;
Session : ADO.Sessions.Session := Into.Service.Get_Session;
Query : ADO.Queries.Context;
Tag_Id : ADO.Identifier;
begin
AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id);
if Tag_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List);
Query.Bind_Param (Name => "tag", Value => Tag_Id);
else
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
end if;
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Into.Questions, Session, Query);
declare
List : ADO.Utils.Identifier_Vector;
Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First;
begin
while Question_Info_Vectors.Has_Element (Iter) loop
List.Append (Question_Info_Vectors.Element (Iter).Id);
Question_Info_Vectors.Next (Iter);
end loop;
Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all,
List);
end;
end Load_List;
-- ------------------------------
-- 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_List_Bean_Access := new Question_List_Bean;
-- Session : ADO.Sessions.Session := Module.Get_Session;
-- Query : ADO.Queries.Context;
begin
Object.Service := Module;
Object.Questions_Bean := Object.Questions'Unchecked_Access;
-- 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.Questions, Session, Query);
Object.Load_List;
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);
elsif Name = "tags" then
return Util.Beans.Objects.To_Object (Value => From.Tags_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;
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Id);
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);
-- Load the tags if any.
From.Tags.Load_Tags (Session, Id);
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;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE);
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
50960557680498cc7cbf353a8c37c8f835104f8c
|
src/gen-model-tables.adb
|
src/gen-model-tables.adb
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Util.Strings;
with Util.Log.Loggers;
package body Gen.Model.Tables is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables");
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if Name = "type" then
declare
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T = null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC);
end;
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "index" then
return Util.Beans.Objects.To_Object (From.Number);
elsif Name = "isUnique" then
return Util.Beans.Objects.To_Object (From.Unique);
elsif Name = "isNull" then
return Util.Beans.Objects.To_Object (not From.Not_Null);
elsif Name = "isInserted" then
return Util.Beans.Objects.To_Object (From.Is_Inserted);
elsif Name = "isUpdated" then
return Util.Beans.Objects.To_Object (From.Is_Updated);
elsif Name = "sqlType" then
if Length (From.Sql_Type) > 0 then
return Util.Beans.Objects.To_Object (From.Sql_Type);
end if;
declare
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T = null then
return Util.Beans.Objects.Null_Object;
end if;
return T.Get_Value ("name");
end;
elsif Name = "sqlName" then
return Util.Beans.Objects.To_Object (From.Sql_Name);
elsif Name = "isVersion" then
return Util.Beans.Objects.To_Object (From.Is_Version);
elsif Name = "isReadable" then
return Util.Beans.Objects.To_Object (From.Is_Readable);
elsif Name = "isPrimaryKey" then
return Util.Beans.Objects.To_Object (From.Is_Key);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Is_Basic_Type);
elsif Name = "generator" then
return From.Generator;
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Returns true if the column type is a basic type.
-- ------------------------------
function Is_Basic_Type (From : in Column_Definition) return Boolean is
use type Gen.Model.Mappings.Mapping_Definition_Access;
use type Gen.Model.Mappings.Basic_Type;
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
Name : constant String := To_String (From.Type_Name);
begin
if T /= null then
return T.Kind /= Gen.Model.Mappings.T_BLOB;
end if;
return Name = "int" or Name = "String"
or Name = "ADO.Identifier" or Name = "Timestamp"
or Name = "Integer"
or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time";
end Is_Basic_Type;
-- ------------------------------
-- Returns the column type.
-- ------------------------------
function Get_Type (From : in Column_Definition) return String is
use type Gen.Model.Mappings.Mapping_Definition_Access;
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T /= null then
return To_String (T.Target);
else
return To_String (From.Type_Name);
end if;
end Get_Type;
-- ------------------------------
-- Returns the column type mapping.
-- ------------------------------
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access is
use type Mappings.Mapping_Definition_Access;
Result : Gen.Model.Mappings.Mapping_Definition_Access := null;
Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, ".");
begin
if Pos = 0 then
Result := Gen.Model.Mappings.Find_Type (From.Type_Name);
end if;
if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then
Log.Debug ("Found enum");
end if;
if Result = null then
Result := From.Table.Package_Def.Find_Type (From.Type_Name);
end if;
return Result;
end Get_Type_Mapping;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Column_Definition) is
use type Mappings.Mapping_Definition_Access;
begin
-- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name);
-- if O.Type_Mapping = null then
-- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name);
-- end if;
null;
end Prepare;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
return Column_Definition (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Table_Definition) is
begin
O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access,
Util.Beans.Objects.STATIC);
O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Create a table with the given name.
-- ------------------------------
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is
Table : constant Table_Definition_Access := new Table_Definition;
begin
Table.Name := Name;
Table.Kind := Gen.Model.Mappings.T_TABLE;
declare
Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1);
Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
Table.Table_Name := Table.Type_Name;
end;
return Table;
end Create_Table;
-- ------------------------------
-- Create a table column with the given name and add it to the table.
-- ------------------------------
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access) is
begin
Column := new Column_Definition;
Column.Name := Name;
Column.Sql_Name := Name;
Column.Number := Table.Members.Get_Count;
Column.Table := Table'Unchecked_Access;
Table.Members.Append (Column);
if Name = "version" then
Table.Version_Column := Column;
Column.Is_Version := True;
Column.Is_Updated := False;
Column.Is_Inserted := False;
elsif Name = "id" then
Table.Id_Column := Column;
Column.Is_Key := True;
end if;
end Add_Column;
-- ------------------------------
-- Create a table association with the given name and add it to the table.
-- ------------------------------
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access) is
begin
Assoc := new Association_Definition;
Assoc.Name := Name;
Assoc.Number := Table.Members.Get_Count;
Assoc.Table := Table'Unchecked_Access;
Assoc.Sql_Name := Name;
Table.Members.Append (Assoc.all'Access);
Table.Has_Associations := True;
end Add_Association;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Table_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" or Name = "columns" then
return From.Members_Bean;
elsif Name = "operations" then
return From.Operations_Bean;
elsif Name = "id" and From.Id_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "version" and From.Version_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= From.Version_Column.all'Unchecked_Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "hasAssociations" then
return Util.Beans.Objects.To_Object (From.Has_Associations);
elsif Name = "hasList" then
return Util.Beans.Objects.To_Object (From.Has_List);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "table" then
return Util.Beans.Objects.To_Object (From.Table_Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Table_Definition) is
Iter : Column_List.Cursor := O.Members.First;
begin
while Column_List.Has_Element (Iter) loop
Column_List.Element (Iter).Prepare;
Column_List.Next (Iter);
end loop;
end Prepare;
-- ------------------------------
-- Set the table name and determines the package name.
-- ------------------------------
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
Table.Name := To_Unbounded_String (Name);
if Pos > 0 then
Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1));
Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end Set_Table_Name;
end Gen.Model.Tables;
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Util.Strings;
with Util.Log.Loggers;
package body Gen.Model.Tables is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables");
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Column_Definition;
Name : String) return Util.Beans.Objects.Object is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if Name = "type" then
declare
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T = null then
return Util.Beans.Objects.Null_Object;
end if;
return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC);
end;
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "index" then
return Util.Beans.Objects.To_Object (From.Number);
elsif Name = "isUnique" then
return Util.Beans.Objects.To_Object (From.Unique);
elsif Name = "isNull" then
return Util.Beans.Objects.To_Object (not From.Not_Null);
elsif Name = "isInserted" then
return Util.Beans.Objects.To_Object (From.Is_Inserted);
elsif Name = "isUpdated" then
return Util.Beans.Objects.To_Object (From.Is_Updated);
elsif Name = "sqlType" then
if Length (From.Sql_Type) > 0 then
return Util.Beans.Objects.To_Object (From.Sql_Type);
end if;
declare
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T = null then
return Util.Beans.Objects.Null_Object;
end if;
return T.Get_Value ("name");
end;
elsif Name = "sqlName" then
return Util.Beans.Objects.To_Object (From.Sql_Name);
elsif Name = "isVersion" then
return Util.Beans.Objects.To_Object (From.Is_Version);
elsif Name = "isReadable" then
return Util.Beans.Objects.To_Object (From.Is_Readable);
elsif Name = "isPrimaryKey" then
return Util.Beans.Objects.To_Object (From.Is_Key);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Is_Basic_Type);
elsif Name = "generator" then
return From.Generator;
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Returns true if the column type is a basic type.
-- ------------------------------
function Is_Basic_Type (From : in Column_Definition) return Boolean is
use type Gen.Model.Mappings.Mapping_Definition_Access;
use type Gen.Model.Mappings.Basic_Type;
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
Name : constant String := To_String (From.Type_Name);
begin
if T /= null then
return T.Kind /= Gen.Model.Mappings.T_BLOB;
end if;
return Name = "int" or Name = "String"
or Name = "ADO.Identifier" or Name = "Timestamp"
or Name = "Integer"
or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time";
end Is_Basic_Type;
-- ------------------------------
-- Returns the column type.
-- ------------------------------
function Get_Type (From : in Column_Definition) return String is
use type Gen.Model.Mappings.Mapping_Definition_Access;
T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping;
begin
if T /= null then
return To_String (T.Target);
else
return To_String (From.Type_Name);
end if;
end Get_Type;
-- ------------------------------
-- Returns the column type mapping.
-- ------------------------------
function Get_Type_Mapping (From : in Column_Definition)
return Gen.Model.Mappings.Mapping_Definition_Access is
use type Mappings.Mapping_Definition_Access;
Result : Gen.Model.Mappings.Mapping_Definition_Access := null;
Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, ".");
begin
if Pos = 0 then
Result := Gen.Model.Mappings.Find_Type (From.Type_Name);
end if;
if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then
Log.Debug ("Found enum");
end if;
if Result = null then
Result := From.Table.Package_Def.Find_Type (From.Type_Name);
end if;
return Result;
end Get_Type_Mapping;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Column_Definition) is
use type Mappings.Mapping_Definition_Access;
begin
-- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name);
-- if O.Type_Mapping = null then
-- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name);
-- end if;
null;
end Prepare;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Association_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
return Column_Definition (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Table_Definition) is
begin
O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access,
Util.Beans.Objects.STATIC);
O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Create a table with the given name.
-- ------------------------------
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is
Table : constant Table_Definition_Access := new Table_Definition;
begin
Table.Name := Name;
Table.Kind := Gen.Model.Mappings.T_TABLE;
declare
Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1);
Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
Table.Table_Name := Table.Type_Name;
end;
return Table;
end Create_Table;
-- ------------------------------
-- Create a table column with the given name and add it to the table.
-- ------------------------------
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access) is
begin
Column := new Column_Definition;
Column.Name := Name;
Column.Sql_Name := Name;
Column.Number := Table.Members.Get_Count;
Column.Table := Table'Unchecked_Access;
Table.Members.Append (Column);
if Name = "version" then
Table.Version_Column := Column;
Column.Is_Version := True;
Column.Is_Updated := False;
Column.Is_Inserted := False;
elsif Name = "id" then
Table.Id_Column := Column;
Column.Is_Key := True;
end if;
end Add_Column;
-- ------------------------------
-- Create a table association with the given name and add it to the table.
-- ------------------------------
procedure Add_Association (Table : in out Table_Definition;
Name : in Unbounded_String;
Assoc : out Association_Definition_Access) is
begin
Assoc := new Association_Definition;
Assoc.Name := Name;
Assoc.Number := Table.Members.Get_Count;
Assoc.Table := Table'Unchecked_Access;
Assoc.Sql_Name := Name;
Table.Members.Append (Assoc.all'Access);
Table.Has_Associations := True;
end Add_Association;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Table_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" or Name = "columns" then
return From.Members_Bean;
elsif Name = "operations" then
return From.Operations_Bean;
elsif Name = "id" and From.Id_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "version" and From.Version_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= From.Version_Column.all'Unchecked_Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "hasAssociations" then
return Util.Beans.Objects.To_Object (From.Has_Associations);
elsif Name = "hasList" then
return Util.Beans.Objects.To_Object (From.Has_List);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "table" then
return Util.Beans.Objects.To_Object (From.Table_Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Table_Definition) is
Iter : Column_List.Cursor := O.Members.First;
C : Column_Definition_Access;
begin
Log.Info ("Prepare table {0}", O.Name);
while Column_List.Has_Element (Iter) loop
C := Column_List.Element (Iter);
C.Prepare;
if C.Is_Key then
Log.Info ("Found key {0}", C.Name);
O.Id_Column := C;
end if;
Column_List.Next (Iter);
end loop;
end Prepare;
-- ------------------------------
-- Set the table name and determines the package name.
-- ------------------------------
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
Table.Name := To_Unbounded_String (Name);
if Pos > 0 then
Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1));
Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end Set_Table_Name;
end Gen.Model.Tables;
|
Prepare the table to identify the primary key
|
Prepare the table to identify the primary key
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
94e691a17e7d85f455689e07c784adbf95147b47
|
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.properties", 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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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;
|
Fix the application setup name
|
Fix the application setup name
|
Ada
|
apache-2.0
|
stcarrez/atlas
|
b68c3779eb4d9f2043bb97e60fa34ca4e9a215c5
|
src/asf-helpers-beans.ads
|
src/asf-helpers-beans.ads
|
-----------------------------------------------------------------------
-- asf-helpers-beans -- Helper packages to write ASF applications
-- 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.Beans.Basic;
package ASF.Helpers.Beans is
-- Get a bean instance associated under the given name from the current faces context.
-- A null value is returned if the bean does not exist or is not of the good type.
generic
type Element_Type is new Util.Beans.Basic.Readonly_Bean with private;
type Element_Access is access all Element_Type'Class;
function Get_Bean (Name : in String) return Element_Access;
end ASF.Helpers.Beans;
|
-----------------------------------------------------------------------
-- asf-helpers-beans -- Helper packages to write ASF applications
-- Copyright (C) 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Basic;
with ASF.Requests;
package ASF.Helpers.Beans is
-- Get a bean instance associated under the given name from the current faces context.
-- A null value is returned if the bean does not exist or is not of the good type.
generic
type Element_Type is new Util.Beans.Basic.Readonly_Bean with private;
type Element_Access is access all Element_Type'Class;
function Get_Bean (Name : in String) return Element_Access;
-- Get a bean instance associated under the given name from the request.
-- A null value is returned if the bean does not exist or is not of the good type.
generic
type Element_Type is new Util.Beans.Basic.Readonly_Bean with private;
type Element_Access is access all Element_Type'Class;
function Get_Request_Bean (Request : in ASF.Requests.Request'Class;
Name : in String) return Element_Access;
end ASF.Helpers.Beans;
|
Declare the Get_Request_Bean generic function
|
Declare the Get_Request_Bean generic function
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
3c7c84a44f338648c7619d03497255c967f7a2f8
|
regtests/ado-schemas-tests.adb
|
regtests/ado-schemas-tests.adb
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 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 Util.Test_Caller;
with ADO.Sessions;
with ADO.Schemas.Entities;
with Regtests;
with Regtests.Simple.Model;
package body ADO.Schemas.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "ADO.Schemas");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type",
Test_Find_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)",
Test_Find_Entity_Type_Error'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the entity cache and the Find_Entity_Type operation
-- ------------------------------
procedure Test_Find_Entity_Type (T : in out Test) is
S : ADO.Sessions.Session := Regtests.Get_Database;
C : ADO.Schemas.Entities.Entity_Cache;
begin
ADO.Schemas.Entities.Initialize (Cache => C,
Session => S);
declare
-- T1 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.USER_TABLE'Access);
-- T2 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
T4 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.ALLOCATE_TABLE);
T5 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
begin
-- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value");
-- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value");
T.Assert (T4 /= T5, "Two distinct tables have different entity types");
T.Assert (T4 > 0, "T1.Id must be positive");
T.Assert (T5 > 0, "T2.Id must be positive");
-- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids");
--
-- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4),
-- "Invalid entity type for allocate_table");
-- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5),
-- "Invalid entity type for user_table");
end;
end Test_Find_Entity_Type;
-- ------------------------------
-- Test calling Find_Entity_Type with an invalid table.
-- ------------------------------
procedure Test_Find_Entity_Type_Error (T : in out Test) is
C : ADO.Schemas.Entities.Entity_Cache;
begin
declare
R : ADO.Entity_Type;
pragma Unreferenced (R);
begin
R := Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
end Test_Find_Entity_Type_Error;
end ADO.Schemas.Tests;
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 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 Util.Test_Caller;
with ADO.Drivers;
with ADO.Sessions;
with ADO.Schemas.Entities;
with Regtests;
with Regtests.Simple.Model;
package body ADO.Schemas.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "ADO.Schemas");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type",
Test_Find_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)",
Test_Find_Entity_Type_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema",
Test_Load_Schema'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the entity cache and the Find_Entity_Type operation
-- ------------------------------
procedure Test_Find_Entity_Type (T : in out Test) is
S : ADO.Sessions.Session := Regtests.Get_Database;
C : ADO.Schemas.Entities.Entity_Cache;
begin
ADO.Schemas.Entities.Initialize (Cache => C,
Session => S);
declare
-- T1 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.USER_TABLE'Access);
-- T2 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
T4 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.ALLOCATE_TABLE);
T5 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
begin
-- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value");
-- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value");
T.Assert (T4 /= T5, "Two distinct tables have different entity types");
T.Assert (T4 > 0, "T1.Id must be positive");
T.Assert (T5 > 0, "T2.Id must be positive");
-- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids");
--
-- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4),
-- "Invalid entity type for allocate_table");
-- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5),
-- "Invalid entity type for user_table");
end;
end Test_Find_Entity_Type;
-- ------------------------------
-- Test calling Find_Entity_Type with an invalid table.
-- ------------------------------
procedure Test_Find_Entity_Type_Error (T : in out Test) is
C : ADO.Schemas.Entities.Entity_Cache;
begin
declare
R : ADO.Entity_Type;
pragma Unreferenced (R);
begin
R := Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
end Test_Find_Entity_Type_Error;
-- ------------------------------
-- Test the Load_Schema operation and check the result schema.
-- ------------------------------
procedure Test_Load_Schema (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
begin
S.Load_Schema (Schema);
Table := ADO.Schemas.Find_Table (Schema, "allocate");
T.Assert (Table /= null, "Table schema for test_allocate not found");
Assert_Equals (T, "allocate", Get_Name (Table));
declare
C : Column_Cursor := Get_Columns (Table);
Nb_Columns : Integer := 0;
begin
while Has_Element (C) loop
Nb_Columns := Nb_Columns + 1;
Next (C);
end loop;
Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns");
end;
declare
C : constant Column_Definition := Find_Column (Table, "ID");
begin
T.Assert (C /= null, "Cannot find column 'id' in table schema");
Assert_Equals (T, "ID", Get_Name (C), "Invalid column name");
T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "NAME");
begin
T.Assert (C /= null, "Cannot find column 'NAME' in table schema");
Assert_Equals (T, "NAME", Get_Name (C), "Invalid column name");
T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type");
T.Assert (Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "version");
begin
T.Assert (C /= null, "Cannot find column 'version' in table schema");
Assert_Equals (T, "version", Get_Name (C), "Invalid column name");
T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
end Test_Load_Schema;
end ADO.Schemas.Tests;
|
Implement the Test_Load_Schema procedure to validate the Load_Schema Verify the column name/type/is_null for several columns
|
Implement the Test_Load_Schema procedure to validate the Load_Schema
Verify the column name/type/is_null for several columns
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
44fc14bd1c9bbee51785a378b4e27e9e9c23c658
|
src/asf-servlets-measures.adb
|
src/asf-servlets-measures.adb
|
-----------------------------------------------------------------------
-- asf.servlets.measures -- Dump performance measurements
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Texts;
with ASF.Streams;
package body ASF.Servlets.Measures is
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Measure_Servlet;
Context : in Servlet_Registry'Class) is
pragma Unreferenced (Context);
begin
Server.Current := Server.Measures'Unchecked_Access;
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.
-- ------------------------------
overriding
function Get_Last_Modified (Server : in Measure_Servlet;
Request : in Requests.Request'Class)
return Ada.Calendar.Time is
pragma Unreferenced (Server, Request);
begin
return Ada.Calendar.Clock;
end Get_Last_Modified;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
overriding
procedure Do_Get (Server : in Measure_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Request);
use type Util.Measures.Measure_Set_Access;
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
procedure Print (Into : in out Util.Streams.Texts.Print_Stream'Class);
procedure Print (Into : in out Util.Streams.Texts.Print_Stream'Class) is
begin
Util.Measures.Write (Measures => Server.Current.all,
Title => "",
Stream => Into);
end Print;
begin
Response.Set_Status (Responses.SC_OK);
Response.Set_Content_Type ("text/xml");
Output.Write (Print'Access);
end Do_Get;
-- ------------------------------
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- A typical implementation of this method would follow the following pattern:
-- 1. Examine the request
-- 2. Optionally wrap the request object with a custom implementation to
-- filter content or headers for input filtering
-- 3. Optionally wrap the response object with a custom implementation to
-- filter content or headers for output filtering
-- 4. Either invoke the next entity in the chain using the FilterChain
-- object (chain.Do_Filter()),
-- or, not pass on the request/response pair to the next entity in the
-- filter chain to block the request processing
-- 5. Directly set headers on the response after invocation of the next
-- entity in the filter chain.
-- ------------------------------
overriding
procedure Do_Filter (F : in Measure_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
URI : constant String := Request.Get_Path_Info;
Stamp : Util.Measures.Stamp;
begin
Util.Measures.Set_Current (F.Current);
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
Util.Measures.Report (Measures => F.Current.all,
S => Stamp,
Title => URI);
Util.Measures.Set_Current (null);
exception
when others =>
Util.Measures.Report (Measures => F.Current.all,
S => Stamp,
Title => URI);
Util.Measures.Set_Current (null);
raise;
end Do_Filter;
end ASF.Servlets.Measures;
|
-----------------------------------------------------------------------
-- asf.servlets.measures -- Dump performance measurements
-- Copyright (C) 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Texts;
with ASF.Streams;
package body ASF.Servlets.Measures is
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Measure_Servlet;
Context : in Servlet_Registry'Class) is
pragma Unreferenced (Context);
begin
Server.Current := Server.Measures'Unchecked_Access;
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.
-- ------------------------------
overriding
function Get_Last_Modified (Server : in Measure_Servlet;
Request : in Requests.Request'Class)
return Ada.Calendar.Time is
pragma Unreferenced (Server, Request);
begin
return Ada.Calendar.Clock;
end Get_Last_Modified;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
overriding
procedure Do_Get (Server : in Measure_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Request);
use type Util.Measures.Measure_Set_Access;
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
procedure Print (Into : in out Util.Streams.Texts.Print_Stream'Class);
procedure Print (Into : in out Util.Streams.Texts.Print_Stream'Class) is
begin
Util.Measures.Write (Measures => Server.Current.all,
Title => "",
Stream => Into);
end Print;
begin
Response.Set_Status (Responses.SC_OK);
Response.Set_Content_Type ("text/xml");
Output.Write (Print'Access);
end Do_Get;
-- ------------------------------
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- A typical implementation of this method would follow the following pattern:
-- 1. Examine the request
-- 2. Optionally wrap the request object with a custom implementation to
-- filter content or headers for input filtering
-- 3. Optionally wrap the response object with a custom implementation to
-- filter content or headers for output filtering
-- 4. Either invoke the next entity in the chain using the FilterChain
-- object (chain.Do_Filter()),
-- or, not pass on the request/response pair to the next entity in the
-- filter chain to block the request processing
-- 5. Directly set headers on the response after invocation of the next
-- entity in the filter chain.
-- ------------------------------
overriding
procedure Do_Filter (F : in Measure_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
URI : constant String := Request.Get_Request_URI;
Stamp : Util.Measures.Stamp;
begin
Util.Measures.Set_Current (F.Current);
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
Util.Measures.Report (Measures => F.Current.all,
S => Stamp,
Title => URI);
Util.Measures.Set_Current (null);
exception
when others =>
Util.Measures.Report (Measures => F.Current.all,
S => Stamp,
Title => URI);
Util.Measures.Set_Current (null);
raise;
end Do_Filter;
end ASF.Servlets.Measures;
|
Use Get_Request_URI to obtain the full URI for the performance report
|
Use Get_Request_URI to obtain the full URI for the performance report
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a2fa805d100c7a6f1d51b629171f9454aa4cdb99
|
src/http/util-http-clients.adb
|
src/http/util-http-clients.adb
|
-----------------------------------------------------------------------
-- util-http-clients -- HTTP Clients
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
package body Util.Http.Clients is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients");
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
overriding
function Contains_Header (Reply : in Response;
Name : in String) return Boolean is
begin
if Reply.Delegate = null then
return False;
else
return Reply.Delegate.Contains_Header (Name);
end if;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Reply : in Response;
Name : in String) return String is
begin
if Reply.Delegate = null then
return "";
else
return Reply.Delegate.Get_Header (Name);
end if;
end Get_Header;
-- ------------------------------
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Reply : in out Response;
Name : in String;
Value : in String) is
begin
Reply.Delegate.Set_Header (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Reply : in out Response;
Name : in String;
Value : in String) is
begin
Reply.Delegate.Add_Header (Name, Value);
end Add_Header;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
overriding
procedure Iterate_Headers (Reply : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
if Reply.Delegate /= null then
Reply.Delegate.Iterate_Headers (Process);
end if;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
overriding
function Get_Body (Reply : in Response) return String is
begin
if Reply.Delegate = null then
return "";
else
return Reply.Delegate.Get_Body;
end if;
end Get_Body;
-- ------------------------------
-- Get the response status code.
-- ------------------------------
function Get_Status (Reply : in Response) return Natural is
begin
return Reply.Delegate.Get_Status;
end Get_Status;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
overriding
function Contains_Header (Request : in Client;
Name : in String) return Boolean is
begin
if Request.Delegate = null then
return False;
else
return Request.Delegate.Contains_Header (Name);
end if;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Request : in Client;
Name : in String) return String is
begin
if Request.Delegate = null then
return "";
else
return Request.Delegate.Get_Header (Name);
end if;
end Get_Header;
-- ------------------------------
-- Sets a header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Request : in out Client;
Name : in String;
Value : in String) is
begin
Request.Delegate.Set_Header (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a header with the given name and value.
-- This method allows headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Request : in out Client;
Name : in String;
Value : in String) is
begin
Request.Delegate.Add_Header (Name, Value);
end Add_Header;
-- ------------------------------
-- Iterate over the request headers and executes the <b>Process</b> procedure.
-- ------------------------------
overriding
procedure Iterate_Headers (Request : in Client;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
Request.Delegate.Iterate_Headers (Process);
end Iterate_Headers;
-- ------------------------------
-- Removes all headers with the given name.
-- ------------------------------
procedure Remove_Header (Request : in out Client;
Name : in String) is
begin
null;
end Remove_Header;
-- ------------------------------
-- Initialize the client
-- ------------------------------
overriding
procedure Initialize (Http : in out Client) is
begin
Http.Delegate := null;
Http.Manager := Default_Http_Manager;
if Http.Manager = null then
Log.Error ("No HTTP manager was defined");
raise Program_Error with "No HTTP manager was defined.";
end if;
Http.Manager.Create (Http);
end Initialize;
overriding
procedure Finalize (Http : in out Client) is
procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class,
Http_Request_Access);
begin
Free (Http.Delegate);
end Finalize;
-- ------------------------------
-- Execute an http GET request on the given URL. Additional request parameters,
-- cookies and headers should have been set on the client object.
-- ------------------------------
procedure Get (Request : in out Client;
URL : in String;
Reply : out Response'Class) is
begin
Request.Manager.Do_Get (Request, URL, Reply);
end Get;
-- ------------------------------
-- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>.
-- Additional request cookies and headers should have been set on the client object.
-- ------------------------------
procedure Post (Request : in out Client;
URL : in String;
Data : in String;
Reply : out Response'Class) is
begin
Request.Manager.Do_Post (Request, URL, Data, Reply);
end Post;
-- ------------------------------
-- Adds the specified cookie to the request. This method can be called multiple
-- times to set more than one cookie.
-- ------------------------------
procedure Add_Cookie (Http : in out Client;
Cookie : in Util.Http.Cookies.Cookie) is
begin
null;
end Add_Cookie;
-- ------------------------------
-- Free the resource used by the response.
-- ------------------------------
overriding
procedure Finalize (Reply : in out Response) is
procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class,
Http_Response_Access);
begin
Free (Reply.Delegate);
end Finalize;
end Util.Http.Clients;
|
-----------------------------------------------------------------------
-- util-http-clients -- HTTP Clients
-- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
package body Util.Http.Clients is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients");
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
overriding
function Contains_Header (Reply : in Response;
Name : in String) return Boolean is
begin
if Reply.Delegate = null then
return False;
else
return Reply.Delegate.Contains_Header (Name);
end if;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Reply : in Response;
Name : in String) return String is
begin
if Reply.Delegate = null then
return "";
else
return Reply.Delegate.Get_Header (Name);
end if;
end Get_Header;
-- ------------------------------
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Reply : in out Response;
Name : in String;
Value : in String) is
begin
Reply.Delegate.Set_Header (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Reply : in out Response;
Name : in String;
Value : in String) is
begin
Reply.Delegate.Add_Header (Name, Value);
end Add_Header;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
overriding
procedure Iterate_Headers (Reply : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
if Reply.Delegate /= null then
Reply.Delegate.Iterate_Headers (Process);
end if;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
overriding
function Get_Body (Reply : in Response) return String is
begin
if Reply.Delegate = null then
return "";
else
return Reply.Delegate.Get_Body;
end if;
end Get_Body;
-- ------------------------------
-- Get the response status code.
-- ------------------------------
function Get_Status (Reply : in Response) return Natural is
begin
return Reply.Delegate.Get_Status;
end Get_Status;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
overriding
function Contains_Header (Request : in Client;
Name : in String) return Boolean is
begin
if Request.Delegate = null then
return False;
else
return Request.Delegate.Contains_Header (Name);
end if;
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
overriding
function Get_Header (Request : in Client;
Name : in String) return String is
begin
if Request.Delegate = null then
return "";
else
return Request.Delegate.Get_Header (Name);
end if;
end Get_Header;
-- ------------------------------
-- Sets a header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Request : in out Client;
Name : in String;
Value : in String) is
begin
Request.Delegate.Set_Header (Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a header with the given name and value.
-- This method allows headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Request : in out Client;
Name : in String;
Value : in String) is
begin
Request.Delegate.Add_Header (Name, Value);
end Add_Header;
-- ------------------------------
-- Iterate over the request headers and executes the <b>Process</b> procedure.
-- ------------------------------
overriding
procedure Iterate_Headers (Request : in Client;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
Request.Delegate.Iterate_Headers (Process);
end Iterate_Headers;
-- ------------------------------
-- Removes all headers with the given name.
-- ------------------------------
procedure Remove_Header (Request : in out Client;
Name : in String) is
begin
null;
end Remove_Header;
-- ------------------------------
-- Initialize the client
-- ------------------------------
overriding
procedure Initialize (Http : in out Client) is
begin
Http.Delegate := null;
Http.Manager := Default_Http_Manager;
if Http.Manager = null then
Log.Error ("No HTTP manager was defined");
raise Program_Error with "No HTTP manager was defined.";
end if;
Http.Manager.Create (Http);
end Initialize;
overriding
procedure Finalize (Http : in out Client) is
procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class,
Http_Request_Access);
begin
Free (Http.Delegate);
end Finalize;
-- ------------------------------
-- Execute an http GET request on the given URL. Additional request parameters,
-- cookies and headers should have been set on the client object.
-- ------------------------------
procedure Get (Request : in out Client;
URL : in String;
Reply : out Response'Class) is
begin
Request.Manager.Do_Get (Request, URL, Reply);
end Get;
-- ------------------------------
-- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>.
-- Additional request cookies and headers should have been set on the client object.
-- ------------------------------
procedure Post (Request : in out Client;
URL : in String;
Data : in String;
Reply : out Response'Class) is
begin
Request.Manager.Do_Post (Request, URL, Data, Reply);
end Post;
-- ------------------------------
-- Execute an http PUT request on the given URL. The post data is passed in <b>Data</b>.
-- Additional request cookies and headers should have been set on the client object.
-- ------------------------------
procedure Put (Request : in out Client;
URL : in String;
Data : in String;
Reply : out Response'Class) is
begin
Request.Manager.Do_Put (Request, URL, Data, Reply);
end Put;
-- ------------------------------
-- Adds the specified cookie to the request. This method can be called multiple
-- times to set more than one cookie.
-- ------------------------------
procedure Add_Cookie (Http : in out Client;
Cookie : in Util.Http.Cookies.Cookie) is
begin
null;
end Add_Cookie;
-- ------------------------------
-- Free the resource used by the response.
-- ------------------------------
overriding
procedure Finalize (Reply : in out Response) is
procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class,
Http_Response_Access);
begin
Free (Reply.Delegate);
end Finalize;
end Util.Http.Clients;
|
Implement the Put procedure
|
Implement the Put procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
fd879c954cd14067973a5099bd0abd8da9fbf8bf
|
boards/OpenMV2/src/openmv-sensor.adb
|
boards/OpenMV2/src/openmv-sensor.adb
|
with STM32.DCMI;
with STM32.DMA; use STM32.DMA;
with Ada.Real_Time; use Ada.Real_Time;
with OV2640; use OV2640;
with Interfaces; use Interfaces;
with HAL.I2C; use HAL.I2C;
with HAL.Bitmap; use HAL.Bitmap;
with HAL; use HAL;
package body OpenMV.Sensor is
package DCMI renames STM32.DCMI;
function Probe (Cam_Addr : out UInt10) return Boolean;
REG_PID : constant := 16#0A#;
-- REG_VER : constant := 16#0B#;
CLK_PWM_Mod : PWM_Modulator;
Camera : OV2640_Cam (Sensor_I2C'Access);
Is_Initialized : Boolean := False;
-----------------
-- Initialized --
-----------------
function Initialized return Boolean is (Is_Initialized);
-----------
-- Probe --
-----------
function Probe (Cam_Addr : out UInt10) return Boolean is
Status : I2C_Status;
begin
for Addr in UInt10 range 0 .. 126 loop
Sensor_I2C.Master_Transmit (Addr => Addr,
Data => (0 => 0),
Status => Status,
Timeout => 10_000);
if Status = Ok then
Cam_Addr := Addr;
return True;
end if;
end loop;
return False;
end Probe;
----------------
-- Initialize --
----------------
procedure Initialize is
procedure Initialize_Clock;
procedure Initialize_Camera;
procedure Initialize_IO;
procedure Initialize_DCMI;
procedure Initialize_DMA;
----------------------
-- Initialize_Clock --
----------------------
procedure Initialize_Clock is
begin
Initialise_PWM_Timer (SENSOR_CLK_TIM,
Float (SENSOR_CLK_FREQ));
Attach_PWM_Channel (This => SENSOR_CLK_TIM'Access,
Modulator => CLK_PWM_Mod,
Channel => SENSOR_CLK_CHAN,
Point => SENSOR_CLK_IO,
PWM_AF => SENSOR_CLK_AF);
Set_Duty_Cycle (This => CLK_PWM_Mod,
Value => 50);
Enable_PWM (CLK_PWM_Mod);
end Initialize_Clock;
-----------------------
-- Initialize_Camera --
-----------------------
procedure Initialize_Camera is
Cam_Addr : UInt10;
Data : I2C_Data (1 .. 1);
Status : I2C_Status;
PID : HAL.Byte;
begin
-- Power cycle
Set (DCMI_PWDN);
delay until Clock + Milliseconds (10);
Clear (DCMI_PWDN);
delay until Clock + Milliseconds (10);
Initialize_Clock;
Set (DCMI_RST);
delay until Clock + Milliseconds (10);
Clear (DCMI_RST);
delay until Clock + Milliseconds (10);
if not Probe (Cam_Addr) then
-- Retry with reversed reset polarity
Clear (DCMI_RST);
delay until Clock + Milliseconds (10);
Set (DCMI_RST);
delay until Clock + Milliseconds (10);
if not Probe (Cam_Addr) then
raise Program_Error;
end if;
end if;
-- Select sensor bank
Sensor_I2C.Mem_Write (Addr => Cam_Addr,
Mem_Addr => 16#FF#,
Mem_Addr_Size => Memory_Size_8b,
Data => (0 => 1),
Status => Status);
if Status /= Ok then
raise Program_Error;
end if;
Sensor_I2C.Mem_Read (Addr => Cam_Addr,
Mem_Addr => REG_PID,
Mem_Addr_Size => Memory_Size_8b,
Data => Data,
Status => Status);
if Status /= Ok then
raise Program_Error;
end if;
PID := Data (Data'First);
if PID /= OV2640_PID then
raise Program_Error;
end if;
Initialize (Camera, Cam_Addr);
Set_Pixel_Format (Camera, Pix_RGB565);
Set_Frame_Size (Camera, QQVGA2);
end Initialize_Camera;
-------------------
-- Initialize_IO --
-------------------
procedure Initialize_IO is
GPIO_Conf : GPIO_Port_Configuration;
DCMI_AF_Points : constant GPIO_Points :=
GPIO_Points'(DCMI_D0, DCMI_D1, DCMI_D2, DCMI_D3, DCMI_D4,
DCMI_D5, DCMI_D6, DCMI_D7, DCMI_VSYNC, DCMI_HSYNC,
DCMI_PCLK);
DCMI_Out_Points : GPIO_Points :=
GPIO_Points'(DCMI_PWDN, DCMI_RST, FS_IN);
begin
Enable_Clock (GPIO_Points'(Sensor_I2C_SCL, Sensor_I2C_SDA));
GPIO_Conf.Speed := Speed_25MHz;
GPIO_Conf.Mode := Mode_AF;
GPIO_Conf.Output_Type := Open_Drain;
GPIO_Conf.Resistors := Floating;
Configure_IO
(GPIO_Points'(Sensor_I2C_SCL, Sensor_I2C_SDA), GPIO_Conf);
Configure_Alternate_Function (Sensor_I2C_SCL, Sensor_I2C_SCL_AF);
Configure_Alternate_Function (Sensor_I2C_SDA, Sensor_I2C_SDA_AF);
Enable_Clock (Sensor_I2C);
Reset (Sensor_I2C);
Enable_Clock (Sensor_I2C);
Configure
(Sensor_I2C,
(Mode => I2C_Mode,
Duty_Cycle => DutyCycle_2,
Own_Address => 16#00#,
Addressing_Mode => Addressing_Mode_7bit,
General_Call_Enabled => False,
Clock_Stretching_Enabled => True,
Clock_Speed => 10_000));
Enable_Clock (DCMI_Out_Points);
-- Sensor PowerDown, Reset and FSIN
GPIO_Conf.Mode := Mode_Out;
GPIO_Conf.Output_Type := Push_Pull;
GPIO_Conf.Resistors := Pull_Down;
Configure_IO (DCMI_Out_Points, GPIO_Conf);
Clear (DCMI_Out_Points);
GPIO_Conf.Mode := Mode_AF;
GPIO_Conf.Output_Type := Push_Pull;
GPIO_Conf.Resistors := Pull_Down;
Configure_IO (DCMI_AF_Points, GPIO_Conf);
Configure_Alternate_Function (DCMI_AF_Points, GPIO_AF_13_DCMI);
end Initialize_IO;
---------------------
-- Initialize_DCMI --
---------------------
procedure Initialize_DCMI is
begin
Enable_DCMI_Clock;
DCMI.Configure (Data_Mode => DCMI.DCMI_8bit,
Capture_Rate => DCMI.Capture_All,
-- Sensor specific (OV2640)
Vertical_Polarity => DCMI.Active_Low,
Horizontal_Polarity => DCMI.Active_Low,
Pixel_Clock_Polarity => DCMI.Active_High,
Hardware_Sync => True,
JPEG => False);
DCMI.Disable_Crop;
DCMI.Enable_DCMI;
end Initialize_DCMI;
--------------------
-- Initialize_DMA --
--------------------
procedure Initialize_DMA is
Config : DMA_Stream_Configuration;
begin
Enable_Clock (Sensor_DMA);
Config.Channel := Sensor_DMA_Chan;
Config.Direction := Peripheral_To_Memory;
Config.Increment_Peripheral_Address := False;
Config.Increment_Memory_Address := True;
Config.Peripheral_Data_Format := Words;
Config.Memory_Data_Format := Words;
Config.Operation_Mode := Normal_Mode;
Config.Priority := Priority_High;
Config.FIFO_Enabled := True;
Config.FIFO_Threshold := FIFO_Threshold_Full_Configuration;
Config.Memory_Burst_Size := Memory_Burst_Inc4;
Config.Peripheral_Burst_Size := Peripheral_Burst_Single;
Configure (Sensor_DMA, Sensor_DMA_Stream, Config);
end Initialize_DMA;
begin
Initialize_IO;
Initialize_Camera;
Initialize_DCMI;
Initialize_DMA;
Is_Initialized := True;
end Initialize;
--------------
-- Snapshot --
--------------
procedure Snapshot (BM : HAL.Bitmap.Bitmap_Buffer'Class) is
Status : DMA_Error_Code;
begin
if BM.Width /= Image_Width or else BM.Height /= Image_Height then
raise Program_Error;
end if;
if not Compatible_Alignments (Sensor_DMA,
Sensor_DMA_Stream,
DCMI.Data_Register_Address,
BM.Addr)
then
raise Program_Error;
end if;
Start_Transfer (This => Sensor_DMA,
Stream => Sensor_DMA_Stream,
Source => DCMI.Data_Register_Address,
Destination => BM.Addr,
Data_Count =>
Interfaces.Unsigned_16 ((BM.Width * BM.Height) / 2));
DCMI.Start_Capture (DCMI.Snapshot);
Poll_For_Completion (Sensor_DMA,
Sensor_DMA_Stream,
Full_Transfer,
Milliseconds (1000),
Status);
if Status /= DMA_No_Error then
Abort_Transfer (Sensor_DMA, Sensor_DMA_Stream, Status);
pragma Unreferenced (Status);
raise Program_Error;
end if;
end Snapshot;
end OpenMV.Sensor;
|
with STM32.DCMI;
with STM32.DMA; use STM32.DMA;
with Ada.Real_Time; use Ada.Real_Time;
with OV2640; use OV2640;
with OV7725; use OV7725;
with Interfaces; use Interfaces;
with HAL.I2C; use HAL.I2C;
with HAL.Bitmap; use HAL.Bitmap;
with HAL; use HAL;
package body OpenMV.Sensor is
package DCMI renames STM32.DCMI;
function Probe (Cam_Addr : out UInt10) return Boolean;
REG_PID : constant := 16#0A#;
-- REG_VER : constant := 16#0B#;
CLK_PWM_Mod : PWM_Modulator;
Camera_PID : HAL.Byte := 0;
Camera_2640 : OV2640_Cam (Sensor_I2C'Access);
Camera_7725 : OV7725_Cam (Sensor_I2C'Access);
Is_Initialized : Boolean := False;
-----------------
-- Initialized --
-----------------
function Initialized return Boolean is (Is_Initialized);
-----------
-- Probe --
-----------
function Probe (Cam_Addr : out UInt10) return Boolean is
Status : I2C_Status;
begin
for Addr in UInt10 range 0 .. 126 loop
Sensor_I2C.Master_Transmit (Addr => Addr,
Data => (0 => 0),
Status => Status,
Timeout => 10_000);
if Status = Ok then
Cam_Addr := Addr;
return True;
end if;
delay until Clock + Milliseconds (1);
end loop;
return False;
end Probe;
----------------
-- Initialize --
----------------
procedure Initialize is
procedure Initialize_Clock;
procedure Initialize_Camera;
procedure Initialize_IO;
procedure Initialize_DCMI;
procedure Initialize_DMA;
----------------------
-- Initialize_Clock --
----------------------
procedure Initialize_Clock is
begin
Initialise_PWM_Timer (SENSOR_CLK_TIM,
Float (SENSOR_CLK_FREQ));
Attach_PWM_Channel (This => SENSOR_CLK_TIM'Access,
Modulator => CLK_PWM_Mod,
Channel => SENSOR_CLK_CHAN,
Point => SENSOR_CLK_IO,
PWM_AF => SENSOR_CLK_AF);
Set_Duty_Cycle (This => CLK_PWM_Mod,
Value => 50);
Enable_PWM (CLK_PWM_Mod);
end Initialize_Clock;
-----------------------
-- Initialize_Camera --
-----------------------
procedure Initialize_Camera is
Cam_Addr : UInt10;
Data : I2C_Data (1 .. 1);
Status : I2C_Status;
begin
-- Power cycle
Set (DCMI_PWDN);
delay until Clock + Milliseconds (10);
Clear (DCMI_PWDN);
delay until Clock + Milliseconds (10);
Initialize_Clock;
Set (DCMI_RST);
delay until Clock + Milliseconds (10);
Clear (DCMI_RST);
delay until Clock + Milliseconds (10);
if not Probe (Cam_Addr) then
-- Retry with reversed reset polarity
Set (DCMI_RST);
delay until Clock + Milliseconds (10);
if not Probe (Cam_Addr) then
raise Program_Error;
end if;
end if;
delay until Clock + Milliseconds (10);
-- Select sensor bank
Sensor_I2C.Mem_Write (Addr => Cam_Addr,
Mem_Addr => 16#FF#,
Mem_Addr_Size => Memory_Size_8b,
Data => (0 => 1),
Status => Status);
if Status /= Ok then
raise Program_Error;
end if;
delay until Clock + Milliseconds (10);
Sensor_I2C.Master_Transmit (Addr => Cam_Addr,
Data => (1 => REG_PID),
Status => Status);
if Status /= Ok then
raise Program_Error;
end if;
Sensor_I2C.Master_Receive (Addr => Cam_Addr,
Data => Data,
Status => Status);
if Status /= Ok then
raise Program_Error;
end if;
if Status /= Ok then
raise Program_Error;
end if;
Camera_PID := Data (Data'First);
case Camera_PID is
when OV2640_PID =>
Initialize (Camera_2640, Cam_Addr);
Set_Pixel_Format (Camera_2640, Pix_RGB565);
Set_Frame_Size (Camera_2640, QQVGA2);
when OV7725_PID =>
Initialize (Camera_7725, Cam_Addr);
Set_Pixel_Format (Camera_7725, Pix_RGB565);
Set_Frame_Size (Camera_7725, QQVGA2);
when others =>
raise Program_Error with "Unknown camera module";
end case;
end Initialize_Camera;
-------------------
-- Initialize_IO --
-------------------
procedure Initialize_IO is
GPIO_Conf : GPIO_Port_Configuration;
DCMI_AF_Points : constant GPIO_Points :=
GPIO_Points'(DCMI_D0, DCMI_D1, DCMI_D2, DCMI_D3, DCMI_D4,
DCMI_D5, DCMI_D6, DCMI_D7, DCMI_VSYNC, DCMI_HSYNC,
DCMI_PCLK);
DCMI_Out_Points : GPIO_Points :=
GPIO_Points'(DCMI_PWDN, DCMI_RST, FS_IN);
begin
Enable_Clock (GPIO_Points'(Sensor_I2C_SCL, Sensor_I2C_SDA));
GPIO_Conf.Speed := Speed_25MHz;
GPIO_Conf.Mode := Mode_AF;
GPIO_Conf.Output_Type := Open_Drain;
GPIO_Conf.Resistors := Floating;
Configure_IO
(GPIO_Points'(Sensor_I2C_SCL, Sensor_I2C_SDA), GPIO_Conf);
Configure_Alternate_Function (Sensor_I2C_SCL, Sensor_I2C_SCL_AF);
Configure_Alternate_Function (Sensor_I2C_SDA, Sensor_I2C_SDA_AF);
Enable_Clock (Sensor_I2C);
Reset (Sensor_I2C);
Enable_Clock (Sensor_I2C);
Configure
(Sensor_I2C,
(Mode => I2C_Mode,
Duty_Cycle => DutyCycle_2,
Own_Address => 16#00#,
Addressing_Mode => Addressing_Mode_7bit,
General_Call_Enabled => False,
Clock_Stretching_Enabled => False,
Clock_Speed => 10_000));
Enable_Clock (DCMI_Out_Points);
-- Sensor PowerDown, Reset and FSIN
GPIO_Conf.Mode := Mode_Out;
GPIO_Conf.Output_Type := Push_Pull;
GPIO_Conf.Resistors := Pull_Down;
Configure_IO (DCMI_Out_Points, GPIO_Conf);
Clear (DCMI_Out_Points);
GPIO_Conf.Mode := Mode_AF;
GPIO_Conf.Output_Type := Push_Pull;
GPIO_Conf.Resistors := Pull_Down;
Configure_IO (DCMI_AF_Points, GPIO_Conf);
Configure_Alternate_Function (DCMI_AF_Points, GPIO_AF_13_DCMI);
end Initialize_IO;
---------------------
-- Initialize_DCMI --
---------------------
procedure Initialize_DCMI is
Vertical : DCMI.DCMI_Polarity;
Horizontal : DCMI.DCMI_Polarity;
Pixel_Clock : DCMI.DCMI_Polarity;
begin
case Camera_PID is
when OV2640_PID =>
Vertical := DCMI.Active_Low;
Horizontal := DCMI.Active_Low;
Pixel_Clock := DCMI.Active_High;
when OV7725_PID =>
Vertical := DCMI.Active_High;
Horizontal := DCMI.Active_Low;
Pixel_Clock := DCMI.Active_High;
when others =>
raise Program_Error with "Unknown camera module";
end case;
Enable_DCMI_Clock;
DCMI.Configure (Data_Mode => DCMI.DCMI_8bit,
Capture_Rate => DCMI.Capture_All,
Vertical_Polarity => Vertical,
Horizontal_Polarity => Horizontal,
Pixel_Clock_Polarity => Pixel_Clock,
Hardware_Sync => True,
JPEG => False);
DCMI.Disable_Crop;
DCMI.Enable_DCMI;
end Initialize_DCMI;
--------------------
-- Initialize_DMA --
--------------------
procedure Initialize_DMA is
Config : DMA_Stream_Configuration;
begin
Enable_Clock (Sensor_DMA);
Config.Channel := Sensor_DMA_Chan;
Config.Direction := Peripheral_To_Memory;
Config.Increment_Peripheral_Address := False;
Config.Increment_Memory_Address := True;
Config.Peripheral_Data_Format := Words;
Config.Memory_Data_Format := Words;
Config.Operation_Mode := Normal_Mode;
Config.Priority := Priority_High;
Config.FIFO_Enabled := True;
Config.FIFO_Threshold := FIFO_Threshold_Full_Configuration;
Config.Memory_Burst_Size := Memory_Burst_Inc4;
Config.Peripheral_Burst_Size := Peripheral_Burst_Single;
Configure (Sensor_DMA, Sensor_DMA_Stream, Config);
end Initialize_DMA;
begin
Initialize_IO;
Initialize_Camera;
Initialize_DCMI;
Initialize_DMA;
Is_Initialized := True;
end Initialize;
--------------
-- Snapshot --
--------------
procedure Snapshot (BM : HAL.Bitmap.Bitmap_Buffer'Class) is
Status : DMA_Error_Code;
Cnt : constant Interfaces.Unsigned_16 :=
Interfaces.Unsigned_16 ((BM.Width * BM.Height) / 2);
begin
if BM.Width /= Image_Width or else BM.Height /= Image_Height then
raise Program_Error;
end if;
if not Compatible_Alignments (Sensor_DMA,
Sensor_DMA_Stream,
DCMI.Data_Register_Address,
BM.Addr)
then
raise Program_Error;
end if;
Clear_All_Status (Sensor_DMA, Sensor_DMA_Stream);
Start_Transfer (This => Sensor_DMA,
Stream => Sensor_DMA_Stream,
Source => DCMI.Data_Register_Address,
Destination => BM.Addr,
Data_Count => Cnt);
DCMI.Start_Capture (DCMI.Snapshot);
Poll_For_Completion (Sensor_DMA,
Sensor_DMA_Stream,
Full_Transfer,
Milliseconds (100),
Status);
if Status /= DMA_No_Error then
if Status = DMA_Timeout_Error then
raise Program_Error with "DMA timeout! Transferred: " &
Items_Transferred (Sensor_DMA, Sensor_DMA_Stream)'Img;
else
raise Program_Error;
end if;
end if;
end Snapshot;
end OpenMV.Sensor;
|
Add OV7725 sensor support
|
OpenMV: Add OV7725 sensor support
The "post kickstarter" OpenMV2 modules are using the OV7725 module.
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
|
36109557bcab88f3c03520db4f80cefa173e8e01
|
regtests/asf-routes-tests.adb
|
regtests/asf-routes-tests.adb
|
-----------------------------------------------------------------------
-- asf-routes-tests - Unit tests for ASF.Routes
-- 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 Util.Measures;
with Util.Log.Loggers;
with Util.Test_Caller;
with EL.Contexts.Default;
package body ASF.Routes.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests");
package Caller is new Util.Test_Caller (Test, "Routes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)",
Test_Add_Route_With_Path'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)",
Test_Add_Route_With_Param'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)",
Test_Add_Route_With_Ext'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)",
Test_Add_Route_With_EL'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Iterate",
Test_Iterate'Access);
end Add_Tests;
overriding
function Get_Value (Bean : in Test_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return Util.Beans.Objects.To_Object (Bean.Id);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (Bean.Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
overriding
procedure Set_Value (Bean : in out Test_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" then
Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "name" then
Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
begin
T.Bean := new Test_Bean;
ASF.Tests.EL_Test (T).Set_Up;
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"),
Util.Beans.Objects.To_Object (T.Bean.all'Access));
for I in T.Routes'Range loop
T.Routes (I) := Route_Type_Refs.Create (new Test_Route_Type '(Util.Refs.Ref_Entity with Index => I));
end loop;
end Set_Up;
-- ------------------------------
-- Verify that the path matches the given route.
-- ------------------------------
procedure Verify_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
Route : constant Route_Type_Access := T.Routes (Index).Value;
R : Route_Context_Type;
begin
Router.Find_Route (Path, R);
declare
P : constant String := Get_Path (R);
begin
T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path);
T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path);
T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path);
-- Inject the path parameters in the bean instance.
Inject_Parameters (R, Bean, T.ELContext.all);
end;
end Verify_Route;
-- ------------------------------
-- Add the route associated with the path pattern.
-- ------------------------------
procedure Add_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
begin
Route := T.Routes (Index);
end Insert;
begin
Router.Add_Route (Path, T.ELContext.all, Insert'Access);
Verify_Route (T, Router, Path, Index, Bean);
end Add_Route;
-- ------------------------------
-- Test the Add_Route with simple fixed path components.
-- Example: /list/index.html
-- ------------------------------
procedure Test_Add_Route_With_Path (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/page.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
Verify_Route (T, Router, "/list/index.html", 3, Bean);
end Test_Add_Route_With_Path;
-- ------------------------------
-- Test the Add_Route with extension mapping.
-- Example: /list/*.html
-- ------------------------------
procedure Test_Add_Route_With_Ext (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/*.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean);
Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean);
Add_Route (T, Router, "/view/page/content/*.html", 6, Bean);
Add_Route (T, Router, "/ajax/*", 7, Bean);
Add_Route (T, Router, "*.html", 8, Bean);
-- Verify precedence and wildcard matching.
Verify_Route (T, Router, "/list/index.html", 3, Bean);
Verify_Route (T, Router, "/list/admin.html", 2, Bean);
Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean);
Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean);
Verify_Route (T, Router, "/ajax/form/save", 7, Bean);
Verify_Route (T, Router, "/view/index.html", 8, Bean);
Add_Route (T, Router, "/ajax/timeKeeper/*", 9, Bean);
Verify_Route (T, Router, "/ajax/form/save", 7, Bean);
Verify_Route (T, Router, "/ajax/timeKeeper/save", 9, Bean);
end Test_Add_Route_With_Ext;
-- ------------------------------
-- Test the Add_Route with fixed path components and path parameters.
-- Example: /users/:id/view.html
-- ------------------------------
procedure Test_Add_Route_With_Param (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/users/:id/view.html", 1, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/list.html", 2, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/index.html", 3, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path");
Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name");
Add_Route (T, Router, "/users/list/index.html", 8, Bean);
Verify_Route (T, Router, "/users/1234/view.html", 1, Bean);
T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id");
Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean);
T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_Param;
-- ------------------------------
-- Test the Add_Route with fixed path components and EL path injection.
-- Example: /users/#{user.id}/view.html
-- ------------------------------
procedure Test_Add_Route_With_EL (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : aliased Test_Bean;
begin
Add_Route (T, Router, "/users/#{user.id}", 1, Bean);
Add_Route (T, Router, "/users/view.html", 2, Bean);
Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean);
Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean);
-- Verify that the path parameters are injected in the 'user' bean (= T.Bean).
Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean);
T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_EL;
P_1 : aliased constant String := "/list/index.html";
P_2 : aliased constant String := "/users/:id";
P_3 : aliased constant String := "/users/:id/view";
P_4 : aliased constant String := "/users/index.html";
P_5 : aliased constant String := "/users/:id/:name";
P_6 : aliased constant String := "/users/:id/:name/view.html";
P_7 : aliased constant String := "/users/:id/list";
P_8 : aliased constant String := "/users/test.html";
P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html";
P_10 : aliased constant String := "/admin/*.html";
P_11 : aliased constant String := "/admin/*.png";
P_12 : aliased constant String := "/admin/*.jpg";
P_13 : aliased constant String := "/users/:id/page/*.xml";
P_14 : aliased constant String := "/*.jsf";
type Const_String_Access is access constant String;
type String_Array is array (Positive range <>) of Const_String_Access;
Path_Array : constant String_Array :=
(P_1'Access, P_2'Access, P_3'Access, P_4'Access,
P_5'Access, P_6'Access, P_7'Access, P_8'Access,
P_9'Access, P_10'Access, P_11'Access, P_12'Access,
P_13'Access, P_14'Access);
-- ------------------------------
-- Test the Iterate over several paths.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
procedure Process (Pattern : in String;
Route : in Route_Type_Access) is
begin
T.Assert (Route /= null, "The route is null for " & Pattern);
T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern);
Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index));
T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all,
"Invalid route for " & Pattern);
end Process;
begin
for I in Path_Array'Range loop
Add_Route (T, Router, Path_Array (I).all, I, Bean);
end loop;
Router.Iterate (Process'Access);
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.html", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (fixed path)");
end;
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (extension)");
end;
end Test_Iterate;
end ASF.Routes.Tests;
|
-----------------------------------------------------------------------
-- asf-routes-tests - Unit tests for ASF.Routes
-- Copyright (C) 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Measures;
with Util.Log.Loggers;
with Util.Test_Caller;
package body ASF.Routes.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests");
package Caller is new Util.Test_Caller (Test, "Routes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)",
Test_Add_Route_With_Path'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)",
Test_Add_Route_With_Param'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)",
Test_Add_Route_With_Ext'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)",
Test_Add_Route_With_EL'Access);
Caller.Add_Test (Suite, "Test ASF.Routes.Iterate",
Test_Iterate'Access);
end Add_Tests;
overriding
function Get_Value (Bean : in Test_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return Util.Beans.Objects.To_Object (Bean.Id);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (Bean.Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
overriding
procedure Set_Value (Bean : in out Test_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" then
Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "name" then
Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Setup the test instance.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
begin
T.Bean := new Test_Bean;
ASF.Tests.EL_Test (T).Set_Up;
T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"),
Util.Beans.Objects.To_Object (T.Bean.all'Access));
for I in T.Routes'Range loop
T.Routes (I) := Route_Type_Refs.Create
(new Test_Route_Type '(Util.Refs.Ref_Entity with Index => I));
end loop;
end Set_Up;
-- ------------------------------
-- Verify that the path matches the given route.
-- ------------------------------
procedure Verify_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
Route : constant Route_Type_Access := T.Routes (Index).Value;
R : Route_Context_Type;
begin
Router.Find_Route (Path, R);
declare
P : constant String := Get_Path (R);
begin
T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path);
T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path);
T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path);
-- Inject the path parameters in the bean instance.
Inject_Parameters (R, Bean, T.ELContext.all);
end;
end Verify_Route;
-- ------------------------------
-- Add the route associated with the path pattern.
-- ------------------------------
procedure Add_Route (T : in out Test;
Router : in out Router_Type;
Path : in String;
Index : in Positive;
Bean : in out Test_Bean'Class) is
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
begin
Route := T.Routes (Index);
end Insert;
begin
Router.Add_Route (Path, T.ELContext.all, Insert'Access);
Verify_Route (T, Router, Path, Index, Bean);
end Add_Route;
-- ------------------------------
-- Test the Add_Route with simple fixed path components.
-- Example: /list/index.html
-- ------------------------------
procedure Test_Add_Route_With_Path (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/page.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
Verify_Route (T, Router, "/list/index.html", 3, Bean);
end Test_Add_Route_With_Path;
-- ------------------------------
-- Test the Add_Route with extension mapping.
-- Example: /list/*.html
-- ------------------------------
procedure Test_Add_Route_With_Ext (T : in out Test) is
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/page.html", 1, Bean);
Add_Route (T, Router, "/list/*.html", 2, Bean);
Add_Route (T, Router, "/list/index.html", 3, Bean);
Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean);
Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean);
Add_Route (T, Router, "/view/page/content/*.html", 6, Bean);
Add_Route (T, Router, "/ajax/*", 7, Bean);
Add_Route (T, Router, "*.html", 8, Bean);
-- Verify precedence and wildcard matching.
Verify_Route (T, Router, "/list/index.html", 3, Bean);
Verify_Route (T, Router, "/list/admin.html", 2, Bean);
Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean);
Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean);
Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean);
Verify_Route (T, Router, "/ajax/form/save", 7, Bean);
Verify_Route (T, Router, "/view/index.html", 8, Bean);
Add_Route (T, Router, "/ajax/timeKeeper/*", 9, Bean);
Verify_Route (T, Router, "/ajax/form/save", 7, Bean);
Verify_Route (T, Router, "/ajax/timeKeeper/save", 9, Bean);
end Test_Add_Route_With_Ext;
-- ------------------------------
-- Test the Add_Route with fixed path components and path parameters.
-- Example: /users/:id/view.html
-- ------------------------------
procedure Test_Add_Route_With_Param (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : Test_Bean;
begin
Add_Route (T, Router, "/users/:id/view.html", 1, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/list.html", 2, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/users/:id/index.html", 3, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
Bean.Id := To_Unbounded_String ("");
Add_Route (T, Router, "/view/page/content/index.html", 4, Bean);
Add_Route (T, Router, "/list//page/view.html", 5, Bean);
Add_Route (T, Router, "/list////page/content.html", 6, Bean);
T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path");
Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean);
T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name");
Add_Route (T, Router, "/users/list/index.html", 8, Bean);
Verify_Route (T, Router, "/users/1234/view.html", 1, Bean);
T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id");
Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean);
T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_Param;
-- ------------------------------
-- Test the Add_Route with fixed path components and EL path injection.
-- Example: /users/#{user.id}/view.html
-- ------------------------------
procedure Test_Add_Route_With_EL (T : in out Test) is
use Ada.Strings.Unbounded;
Router : Router_Type;
Bean : aliased Test_Bean;
begin
Add_Route (T, Router, "/users/#{user.id}", 1, Bean);
Add_Route (T, Router, "/users/view.html", 2, Bean);
Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean);
Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean);
-- Verify that the path parameters are injected in the 'user' bean (= T.Bean).
Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean);
T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id");
T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name");
end Test_Add_Route_With_EL;
P_1 : aliased constant String := "/list/index.html";
P_2 : aliased constant String := "/users/:id";
P_3 : aliased constant String := "/users/:id/view";
P_4 : aliased constant String := "/users/index.html";
P_5 : aliased constant String := "/users/:id/:name";
P_6 : aliased constant String := "/users/:id/:name/view.html";
P_7 : aliased constant String := "/users/:id/list";
P_8 : aliased constant String := "/users/test.html";
P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html";
P_10 : aliased constant String := "/admin/*.html";
P_11 : aliased constant String := "/admin/*.png";
P_12 : aliased constant String := "/admin/*.jpg";
P_13 : aliased constant String := "/users/:id/page/*.xml";
P_14 : aliased constant String := "/*.jsf";
type Const_String_Access is access constant String;
type String_Array is array (Positive range <>) of Const_String_Access;
Path_Array : constant String_Array :=
(P_1'Access, P_2'Access, P_3'Access, P_4'Access,
P_5'Access, P_6'Access, P_7'Access, P_8'Access,
P_9'Access, P_10'Access, P_11'Access, P_12'Access,
P_13'Access, P_14'Access);
-- ------------------------------
-- Test the Iterate over several paths.
-- ------------------------------
procedure Test_Iterate (T : in out Test) is
procedure Process (Pattern : in String;
Route : in Route_Type_Access);
Router : Router_Type;
Bean : Test_Bean;
procedure Process (Pattern : in String;
Route : in Route_Type_Access) is
begin
T.Assert (Route /= null, "The route is null for " & Pattern);
T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern);
Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index));
T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all,
"Invalid route for " & Pattern);
end Process;
begin
for I in Path_Array'Range loop
Add_Route (T, Router, Path_Array (I).all, I, Bean);
end loop;
Router.Iterate (Process'Access);
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.html", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (fixed path)");
end;
declare
St : Util.Measures.Stamp;
begin
for I in 1 .. 1000 loop
declare
R : Route_Context_Type;
begin
Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R);
end;
end loop;
Util.Measures.Report (St, "Find 1000 routes (extension)");
end;
end Test_Iterate;
end ASF.Routes.Tests;
|
Fix compilation warnings on the unit test
|
Fix compilation warnings on the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
dd4a29b931d8f13f08696480d4e3e4f7f5d5dcda
|
src/asf-servlets-mappers.adb
|
src/asf-servlets-mappers.adb
|
-----------------------------------------------------------------------
-- asf-servlets-mappers -- Read servlet configuration files
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with EL.Utils;
package body ASF.Servlets.Mappers is
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
use type Ada.Containers.Count_Type;
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String);
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Filter_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Filter_Name));
end Add_Filter;
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Servlet_Name));
end Add_Mapping;
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String) is
Last : constant Ada.Containers.Count_Type := N.URL_Patterns.Length;
begin
if Last = 0 then
raise Util.Serialize.Mappers.Field_Error with Message;
end if;
for I in 0 .. Last - 1 loop
N.URL_Patterns.Query_Element (Natural (I), Handler);
end loop;
N.URL_Patterns.Clear;
end Add_Mapping;
begin
-- <context-param>
-- <param-name>property</param-name>
-- <param-value>false</param-value>
-- </context-param>
-- <filter-mapping>
-- <filter-name>Dump Filter</filter-name>
-- <servlet-name>Faces Servlet</servlet-name>
-- </filter-mapping>
case Field is
when FILTER_NAME =>
N.Filter_Name := Value;
when SERVLET_NAME =>
N.Servlet_Name := Value;
when URL_PATTERN =>
N.URL_Patterns.Append (Value);
when PARAM_NAME =>
N.Param_Name := Value;
when PARAM_VALUE =>
N.Param_Value := EL.Utils.Eval (To_String (Value), N.Context.all);
when MIME_TYPE =>
N.Mime_Type := Value;
when EXTENSION =>
N.Extension := Value;
when ERROR_CODE =>
N.Error_Code := Value;
when LOCATION =>
N.Location := Value;
when FILTER_MAPPING =>
Add_Mapping (Add_Filter'Access, "Missing url-pattern for the filter mapping");
when SERVLET_MAPPING =>
Add_Mapping (Add_Mapping'Access, "Missing url-pattern for the servlet mapping");
when CONTEXT_PARAM =>
declare
Name : constant String := To_String (N.Param_Name);
begin
-- If the context parameter already has a value, do not set it again.
-- The value comes from an application setting and we want to keep it.
if N.Override_Context
or else String '(N.Handler.all.Get_Init_Parameter (Name)) = "" then
if Util.Beans.Objects.Is_Null (N.Param_Value) then
N.Handler.Set_Init_Parameter (Name => Name,
Value => "");
else
N.Handler.Set_Init_Parameter (Name => Name,
Value => To_String (N.Param_Value));
end if;
end if;
end;
when MIME_MAPPING =>
null;
when ERROR_PAGE =>
N.Handler.Set_Error_Page (Error => To_Integer (N.Error_Code),
Page => To_String (N.Location));
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>,
-- <b>filter-mapping</b> and <b>servlet-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("faces-config", SMapper'Access);
Reader.Add_Mapping ("module", SMapper'Access);
Reader.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("filter-mapping", FILTER_MAPPING);
SMapper.Add_Mapping ("filter-mapping/filter-name", FILTER_NAME);
SMapper.Add_Mapping ("filter-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("filter-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("servlet-mapping", SERVLET_MAPPING);
SMapper.Add_Mapping ("servlet-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("servlet-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("context-param", CONTEXT_PARAM);
SMapper.Add_Mapping ("context-param/param-name", PARAM_NAME);
SMapper.Add_Mapping ("context-param/param-value", PARAM_VALUE);
SMapper.Add_Mapping ("error-page", ERROR_PAGE);
SMapper.Add_Mapping ("error-page/error-code", ERROR_CODE);
SMapper.Add_Mapping ("error-page/location", LOCATION);
end ASF.Servlets.Mappers;
|
-----------------------------------------------------------------------
-- asf-servlets-mappers -- Read servlet configuration files
-- Copyright (C) 2011, 2012, 2013, 2015, 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 EL.Utils;
package body ASF.Servlets.Mappers is
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
use type Ada.Containers.Count_Type;
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String);
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Filter_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Filter_Name));
end Add_Filter;
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Servlet_Name));
end Add_Mapping;
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String) is
Last : constant Ada.Containers.Count_Type := N.URL_Patterns.Length;
begin
if Last = 0 then
raise Util.Serialize.Mappers.Field_Error with Message;
end if;
for I in 0 .. Last - 1 loop
N.URL_Patterns.Query_Element (Natural (I), Handler);
end loop;
N.URL_Patterns.Clear;
end Add_Mapping;
begin
-- <context-param>
-- <param-name>property</param-name>
-- <param-value>false</param-value>
-- </context-param>
-- <filter-mapping>
-- <filter-name>Dump Filter</filter-name>
-- <servlet-name>Faces Servlet</servlet-name>
-- </filter-mapping>
case Field is
when FILTER_NAME =>
N.Filter_Name := Value;
when SERVLET_NAME =>
N.Servlet_Name := Value;
when URL_PATTERN =>
N.URL_Patterns.Append (Value);
when PARAM_NAME =>
N.Param_Name := Value;
when PARAM_VALUE =>
N.Param_Value := EL.Utils.Eval (To_String (Value), N.Context.all);
when MIME_TYPE =>
N.Mime_Type := Value;
when EXTENSION =>
N.Extension := Value;
when ERROR_CODE =>
N.Error_Code := Value;
when LOCATION =>
N.Location := Value;
when FILTER_MAPPING =>
Add_Mapping (Add_Filter'Access, "Missing url-pattern for the filter mapping");
when SERVLET_MAPPING =>
Add_Mapping (Add_Mapping'Access, "Missing url-pattern for the servlet mapping");
when CONTEXT_PARAM =>
declare
Name : constant String := To_String (N.Param_Name);
begin
-- If the context parameter already has a value, do not set it again.
-- The value comes from an application setting and we want to keep it.
if N.Override_Context
or else String '(N.Handler.all.Get_Init_Parameter (Name)) = ""
then
if Util.Beans.Objects.Is_Null (N.Param_Value) then
N.Handler.Set_Init_Parameter (Name => Name,
Value => "");
else
N.Handler.Set_Init_Parameter (Name => Name,
Value => To_String (N.Param_Value));
end if;
end if;
end;
when MIME_MAPPING =>
null;
when ERROR_PAGE =>
N.Handler.Set_Error_Page (Error => To_Integer (N.Error_Code),
Page => To_String (N.Location));
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>,
-- <b>filter-mapping</b> and <b>servlet-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("faces-config", SMapper'Access);
Reader.Add_Mapping ("module", SMapper'Access);
Reader.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("filter-mapping", FILTER_MAPPING);
SMapper.Add_Mapping ("filter-mapping/filter-name", FILTER_NAME);
SMapper.Add_Mapping ("filter-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("filter-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("servlet-mapping", SERVLET_MAPPING);
SMapper.Add_Mapping ("servlet-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("servlet-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("context-param", CONTEXT_PARAM);
SMapper.Add_Mapping ("context-param/param-name", PARAM_NAME);
SMapper.Add_Mapping ("context-param/param-value", PARAM_VALUE);
SMapper.Add_Mapping ("error-page", ERROR_PAGE);
SMapper.Add_Mapping ("error-page/error-code", ERROR_CODE);
SMapper.Add_Mapping ("error-page/location", LOCATION);
end ASF.Servlets.Mappers;
|
Fix style compilation warning
|
Fix style compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
11d46c2b175f0da68c3ffdb8631257262474557e
|
src/security-policies-roles.adb
|
src/security-policies-roles.adb
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
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
use Security.Controllers.Roles;
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.
-- ------------------------------
procedure Set_Reader_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Set_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.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
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
use Security.Controllers.Roles;
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 : 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.
-- ------------------------------
procedure Set_Reader_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Set_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.Policies.Roles;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
46ca4d9ae556f1783d447a6fafd602e512d93f95
|
regtests/util-encoders-kdf-tests.adb
|
regtests/util-encoders-kdf-tests.adb
|
-----------------------------------------------------------------------
-- util-encodes-kdf-tests - Key derivative function tests
-- Copyright (C) 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with Util.Strings.Transforms;
with Ada.Text_IO;
with Util.Encoders.SHA1;
with Util.Encoders.SHA256;
with Util.Encoders.HMAC.SHA1;
with Util.Encoders.HMAC.SHA256;
with Util.Encoders.Base16;
with Util.Encoders.Base64;
with Util.Encoders.AES;
with Util.Encoders.KDF.PBKDF2;
package body Util.Encoders.KDF.Tests is
use Util.Tests;
procedure PBKDF2_HMAC_SHA256 is
new KDF.PBKDF2 (Length => Util.Encoders.SHA256.HASH_SIZE,
Hash => Util.Encoders.HMAC.SHA256.Sign);
procedure PBKDF2_HMAC_SHA1 is
new KDF.PBKDF2 (Length => Util.Encoders.SHA1.HASH_SIZE,
Hash => Util.Encoders.HMAC.SHA1.Sign);
package Caller is new Util.Test_Caller (Test, "Encoders.KDF");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Encoders.KDF.PBKDF2.HMAC_SHA1",
Test_PBKDF2_HMAC_SHA1'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.KDF.PBKDF2.HMAC_SHA256",
Test_PBKDF2_HMAC_SHA256'Access);
end Add_Tests;
-- ------------------------------
-- Test derived key generation with HMAC-SHA1.
-- ------------------------------
procedure Test_PBKDF2_HMAC_SHA1 (T : in out Test) is
Pass : Secret_Key := Create (Password => "password");
Salt : Secret_Key := Create (Password => "salt");
Key : Secret_Key (Length => 20);
B : Util.Encoders.Base64.Encoder;
Hex : Util.Encoders.Base16.Encoder;
begin
-- RFC6070 - test vector 1
PBKDF2_HMAC_SHA1 (Pass, Salt, 1, Key);
Util.Tests.Assert_Equals (T, "0C60C80F961F0E71F3A9B524AF6012062FE037A6",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA1 test vector 1");
-- RFC6070 - test vector 2
PBKDF2_HMAC_SHA1 (Pass, Salt, 2, Key);
Util.Tests.Assert_Equals (T, "EA6C014DC72D6F8CCD1ED92ACE1D41F0D8DE8957",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA1 test vector 2");
-- RFC6070 - test vector 3
PBKDF2_HMAC_SHA1 (Pass, Salt, 4096, Key);
Util.Tests.Assert_Equals (T, "4B007901B765489ABEAD49D926F721D065A429C1",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA1 test vector 3");
end Test_PBKDF2_HMAC_SHA1;
-- ------------------------------
-- Test derived key generation with HMAC-SHA1.
-- ------------------------------
procedure Test_PBKDF2_HMAC_SHA256 (T : in out Test) is
Pass : Secret_Key := Create (Password => "password");
Salt : Secret_Key := Create (Password => "salt");
Key : Secret_Key (Length => 32);
B : Util.Encoders.Base64.Encoder;
Hex : Util.Encoders.Base16.Encoder;
begin
-- RFC6070 - test vector 1
PBKDF2_HMAC_SHA256 (Pass, Salt, 1, Key);
Util.Tests.Assert_Equals (T, "120FB6CFFCF8B32C43E7225256C4F837A8"
& "6548C92CCC35480805987CB70BE17B",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA256 test vector 1");
-- RFC6070 - test vector 2
PBKDF2_HMAC_SHA256 (Pass, Salt, 2, Key);
Util.Tests.Assert_Equals (T, "AE4D0C95AF6B46D32D0ADFF928F06DD02A"
& "303F8EF3C251DFD6E2D85A95474C43",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA256 test vector 2");
-- RFC6070 - test vector 3
PBKDF2_HMAC_SHA256 (Pass, Salt, 4096, Key);
Util.Tests.Assert_Equals (T, "C5E478D59288C841AA530DB6845C4C8D96"
& "2893A001CE4E11A4963873AA98134A",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA256 test vector 3");
end Test_PBKDF2_HMAC_SHA256;
end Util.Encoders.KDF.Tests;
|
-----------------------------------------------------------------------
-- util-encodes-kdf-tests - Key derivative function tests
-- Copyright (C) 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Encoders.SHA1;
with Util.Encoders.SHA256;
with Util.Encoders.HMAC.SHA1;
with Util.Encoders.HMAC.SHA256;
with Util.Encoders.Base16;
with Util.Encoders.AES;
with Util.Encoders.KDF.PBKDF2;
package body Util.Encoders.KDF.Tests is
procedure PBKDF2_HMAC_SHA256 is
new KDF.PBKDF2 (Length => Util.Encoders.SHA256.HASH_SIZE,
Hash => Util.Encoders.HMAC.SHA256.Sign);
procedure PBKDF2_HMAC_SHA1 is
new KDF.PBKDF2 (Length => Util.Encoders.SHA1.HASH_SIZE,
Hash => Util.Encoders.HMAC.SHA1.Sign);
package Caller is new Util.Test_Caller (Test, "Encoders.KDF");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Encoders.KDF.PBKDF2.HMAC_SHA1",
Test_PBKDF2_HMAC_SHA1'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.KDF.PBKDF2.HMAC_SHA256",
Test_PBKDF2_HMAC_SHA256'Access);
end Add_Tests;
-- ------------------------------
-- Test derived key generation with HMAC-SHA1.
-- ------------------------------
procedure Test_PBKDF2_HMAC_SHA1 (T : in out Test) is
Pass : Secret_Key := Create (Password => "password");
Salt : Secret_Key := Create (Password => "salt");
Key : Secret_Key (Length => 20);
Hex : Util.Encoders.Base16.Encoder;
begin
-- RFC6070 - test vector 1
PBKDF2_HMAC_SHA1 (Pass, Salt, 1, Key);
Util.Tests.Assert_Equals (T, "0C60C80F961F0E71F3A9B524AF6012062FE037A6",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA1 test vector 1");
-- RFC6070 - test vector 2
PBKDF2_HMAC_SHA1 (Pass, Salt, 2, Key);
Util.Tests.Assert_Equals (T, "EA6C014DC72D6F8CCD1ED92ACE1D41F0D8DE8957",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA1 test vector 2");
-- RFC6070 - test vector 3
PBKDF2_HMAC_SHA1 (Pass, Salt, 4096, Key);
Util.Tests.Assert_Equals (T, "4B007901B765489ABEAD49D926F721D065A429C1",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA1 test vector 3");
end Test_PBKDF2_HMAC_SHA1;
-- ------------------------------
-- Test derived key generation with HMAC-SHA1.
-- ------------------------------
procedure Test_PBKDF2_HMAC_SHA256 (T : in out Test) is
Pass : Secret_Key := Create (Password => "password");
Salt : Secret_Key := Create (Password => "salt");
Key : Secret_Key (Length => 32);
Hex : Util.Encoders.Base16.Encoder;
begin
-- RFC6070 - test vector 1
PBKDF2_HMAC_SHA256 (Pass, Salt, 1, Key);
Util.Tests.Assert_Equals (T, "120FB6CFFCF8B32C43E7225256C4F837A8"
& "6548C92CCC35480805987CB70BE17B",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA256 test vector 1");
-- RFC6070 - test vector 2
PBKDF2_HMAC_SHA256 (Pass, Salt, 2, Key);
Util.Tests.Assert_Equals (T, "AE4D0C95AF6B46D32D0ADFF928F06DD02A"
& "303F8EF3C251DFD6E2D85A95474C43",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA256 test vector 2");
-- RFC6070 - test vector 3
PBKDF2_HMAC_SHA256 (Pass, Salt, 4096, Key);
Util.Tests.Assert_Equals (T, "C5E478D59288C841AA530DB6845C4C8D96"
& "2893A001CE4E11A4963873AA98134A",
Hex.Transform (Key.Secret),
"PBKDF2-HMAC-SHA256 test vector 3");
end Test_PBKDF2_HMAC_SHA256;
end Util.Encoders.KDF.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
728467e9d5f1a958b728b9522c9e60ec172636f6
|
src/babel-stores-local.adb
|
src/babel-stores-local.adb
|
-----------------------------------------------------------------------
-- bkp-stores-local -- Store management for local files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Interfaces.C.Strings;
with System.OS_Constants;
with Util.Log.Loggers;
with Util.Files;
with Util.Systems.Os;
with Util.Streams.Raw;
with Util.Systems.Types;
with Util.Systems.Os;
with Interfaces;
package body Babel.Stores.Local is
function Errno return Integer;
pragma Import (C, errno, "__get_errno");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local");
function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Babel.Files.File_Size is
Size : Ada.Directories.File_Size;
begin
Size := Ada.Directories.Size (Ent);
return Babel.Files.File_Size (Size);
exception
when Constraint_Error =>
return Babel.Files.File_Size (Interfaces.Unsigned_32'Last);
end Get_File_Size;
-- ------------------------------
-- Get the absolute path to access the local file.
-- ------------------------------
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String is
begin
if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then
return Path;
else
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path);
end if;
end Get_Absolute_Path;
-- Open a file in the store to read its content with a stream.
overriding
procedure Open_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Stream_Access) is
begin
null;
end Open_File;
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path);
Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last);
Ada.Streams.Stream_IO.Close (File);
Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last));
end Read;
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String) is
use Util.Systems.Os;
use type Interfaces.C.int;
File : Util.Systems.Os.File_Type;
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
begin
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
end if;
end if;
if File < 0 then
Log.Error ("Cannot create {0}", Path);
raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path;
end if;
Stream.Initialize (File);
Interfaces.C.Strings.Free (Name);
end Open;
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
Stream : Util.Streams.Raw.Raw_Stream;
begin
Log.Info ("Write {0}", Abs_Path);
Store.Open (Stream, Abs_Path);
Stream.Write (Into.Data (Into.Data'First .. Into.Last));
Stream.Close;
end Write;
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is
use Ada.Directories;
use type Babel.Files.File_Type;
use type Babel.Files.Directory_Type;
function Sys_Stat (Path : in System.Address;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, "stat");
Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
Stat : aliased Util.Systems.Types.Stat_Type;
begin
Log.Info ("Scan directory {0}", Path);
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
use Util.Systems.Types;
use Interfaces.C;
use Babel.Files;
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
File : Babel.Files.File_Type;
Dir : Babel.Files.Directory_Type;
Res : Integer;
Fpath : String (1 .. Path'Length + Name'Length + 3);
begin
Fpath (Path'Range) := Path;
Fpath (Path'Last + 1) := '/';
Fpath (Path'Last + 2 .. Path'Last + 2 + Name'Length - 1) := Name;
Fpath (Path'Last + 2 + Name'Length) := ASCII.NUL;
Res := Sys_Stat (Fpath'Address, Stat'Unchecked_Access);
if (Stat.st_mode and S_IFMT) = S_IFREG then
if Filter.Is_Accepted (Kind, Path, Name) then
File := Into.Find (Name);
if File = Babel.Files.NO_FILE then
File := Into.Create (Name);
end if;
Babel.Files.Set_Size (File, Babel.Files.File_Size (Stat.st_size));
Babel.Files.Set_Owner (File, Uid_Type (Stat.st_uid), Gid_Type (Stat.st_gid));
Babel.Files.Set_Date (File, Stat.st_mtim);
Log.Debug ("Adding {0}", Name);
Into.Add_File (File);
end if;
elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then
Dir := Into.Find (Name);
if Dir = Babel.Files.NO_DIRECTORY then
Dir := Into.Create (Name);
end if;
Into.Add_Directory (Dir);
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
-- ------------------------------
-- Set the root directory for the local store.
-- ------------------------------
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String) is
begin
Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path);
end Set_Root_Directory;
end Babel.Stores.Local;
|
-----------------------------------------------------------------------
-- bkp-stores-local -- Store management for local files
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Interfaces.C.Strings;
with System.OS_Constants;
with Util.Log.Loggers;
with Util.Files;
with Util.Systems.Os;
with Util.Streams.Raw;
with Util.Systems.Types;
with Util.Systems.Os;
with Interfaces;
with Babel.Streams.Files;
package body Babel.Stores.Local is
function Errno return Integer;
pragma Import (C, errno, "__get_errno");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local");
function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Babel.Files.File_Size is
Size : Ada.Directories.File_Size;
begin
Size := Ada.Directories.Size (Ent);
return Babel.Files.File_Size (Size);
exception
when Constraint_Error =>
return Babel.Files.File_Size (Interfaces.Unsigned_32'Last);
end Get_File_Size;
-- ------------------------------
-- Get the absolute path to access the local file.
-- ------------------------------
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String is
begin
if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then
return Path;
else
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path);
end if;
end Get_Absolute_Path;
-- Open a file in the store to read its content with a stream.
overriding
procedure Open_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Stream_Access) is
begin
null;
end Open_File;
-- ------------------------------
-- Open a file in the store to read its content with a stream.
-- ------------------------------
overriding
procedure Read_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Refs.Stream_Ref) is
File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type;
Buffer : Babel.Files.Buffers.Buffer_Access;
begin
Log.Info ("Read file {0}", Path);
Stream := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access);
Store.Pool.Get_Buffer (Buffer);
File.Open (Path, Buffer);
end Read_File;
-- ------------------------------
-- Write a file in the store with a stream.
-- ------------------------------
overriding
procedure Write_File (Store : in out Local_Store_Type;
Path : in String;
Stream : in Babel.Streams.Refs.Stream_Ref;
Mode : in Util.Systems.Types.mode_t) is
File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type;
Output : Babel.Streams.Refs.Stream_Ref;
begin
Log.Info ("Write file {0}", Path);
Output := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access);
File.Create (Path, Mode);
Babel.Streams.Refs.Copy (From => Stream,
Into => Output);
end Write_File;
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path);
Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last);
Ada.Streams.Stream_IO.Close (File);
Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last));
end Read;
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String) is
use Util.Systems.Os;
use type Interfaces.C.int;
File : Util.Systems.Os.File_Type;
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
begin
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
end if;
end if;
if File < 0 then
Log.Error ("Cannot create {0}", Path);
raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path;
end if;
Stream.Initialize (File);
Interfaces.C.Strings.Free (Name);
end Open;
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
Stream : Util.Streams.Raw.Raw_Stream;
begin
Log.Info ("Write {0}", Abs_Path);
Store.Open (Stream, Abs_Path);
Stream.Write (Into.Data (Into.Data'First .. Into.Last));
Stream.Close;
end Write;
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is
use Ada.Directories;
use type Babel.Files.File_Type;
use type Babel.Files.Directory_Type;
function Sys_Stat (Path : in System.Address;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, "stat");
Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
Stat : aliased Util.Systems.Types.Stat_Type;
begin
Log.Info ("Scan directory {0}", Path);
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
use Util.Systems.Types;
use Interfaces.C;
use Babel.Files;
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
File : Babel.Files.File_Type;
Dir : Babel.Files.Directory_Type;
Res : Integer;
Fpath : String (1 .. Path'Length + Name'Length + 3);
begin
Fpath (Path'Range) := Path;
Fpath (Path'Last + 1) := '/';
Fpath (Path'Last + 2 .. Path'Last + 2 + Name'Length - 1) := Name;
Fpath (Path'Last + 2 + Name'Length) := ASCII.NUL;
Res := Sys_Stat (Fpath'Address, Stat'Unchecked_Access);
if (Stat.st_mode and S_IFMT) = S_IFREG then
if Filter.Is_Accepted (Kind, Path, Name) then
File := Into.Find (Name);
if File = Babel.Files.NO_FILE then
File := Into.Create (Name);
end if;
Babel.Files.Set_Size (File, Babel.Files.File_Size (Stat.st_size));
Babel.Files.Set_Owner (File, Uid_Type (Stat.st_uid), Gid_Type (Stat.st_gid));
Babel.Files.Set_Date (File, Stat.st_mtim);
Log.Debug ("Adding {0}", Name);
Into.Add_File (File);
end if;
elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then
Dir := Into.Find (Name);
if Dir = Babel.Files.NO_DIRECTORY then
Dir := Into.Create (Name);
end if;
Into.Add_Directory (Dir);
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
-- ------------------------------
-- Set the root directory for the local store.
-- ------------------------------
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String) is
begin
Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path);
end Set_Root_Directory;
-- ------------------------------
-- Set the buffer pool to be used by local store.
-- ------------------------------
procedure Set_Buffers (Store : in out Local_Store_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is
begin
Store.Pool := Buffers;
end Set_Buffers;
end Babel.Stores.Local;
|
Implement the Read_File, Write_File and Set_Buffers procedures
|
Implement the Read_File, Write_File and Set_Buffers procedures
|
Ada
|
apache-2.0
|
stcarrez/babel
|
8659c66a9acfb6956f6bbd9f3f5f42596fc7702c
|
src/util-concurrent-fifos.adb
|
src/util-concurrent-fifos.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : constant Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
Fix compilation warning reported by gcc 4.7
|
Fix compilation warning reported by gcc 4.7
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
|
856244d8c26ebae7fb7b226d897f1c959900d4da
|
src/util-serialize-io-csv.adb
|
src/util-serialize-io-csv.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Write the attribute with a null value.
-- ------------------------------
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Entity (Name, "");
end Write_Null_Attribute;
-- ------------------------------
-- Write an entity with a null value.
-- ------------------------------
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Null_Attribute (Name);
end Write_Null_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Handler.Sink.Finish_Object ("", Handler);
else
Handler.Sink.Start_Array ("", Handler);
end if;
Handler.Sink.Start_Object ("", Handler);
end if;
Handler.Row := Row;
Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler);
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
begin
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
Handler.Sink := Sink'Unchecked_Access;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Handler.Sink := null;
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Write the attribute with a null value.
-- ------------------------------
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Entity (Name, "");
end Write_Null_Attribute;
-- ------------------------------
-- Write an entity with a null value.
-- ------------------------------
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Stream.Write_Null_Attribute (Name);
end Write_Null_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Handler.Sink.Finish_Object ("", Handler);
else
Handler.Sink.Start_Array ("", Handler);
end if;
Handler.Sink.Start_Object ("", Handler);
end if;
Handler.Row := Row;
Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler);
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class;
Sink : in out Reader'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
begin
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
Handler.Sink := Sink'Unchecked_Access;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Handler.Sink := null;
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
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
|
7c014e98c2e0b208d92f9efdf010536c3501cd8f
|
src/portscan.ads
|
src/portscan.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
-- pragma Suppress (All_Checks);
-- too new: Container_Checks, Tampering_Check
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Characters.Latin_1;
with Ada.Directories;
with JohnnyText;
with Parameters;
with Definitions; use Definitions;
package PortScan is
package JT renames JohnnyText;
package AC renames Ada.Containers;
package CAL renames Ada.Calendar;
package AD renames Ada.Directories;
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
package PM renames Parameters;
type count_type is (total, success, failure, ignored, skipped);
type dim_handlers is array (count_type) of TIO.File_Type;
type port_id is private;
port_match_failed : constant port_id;
-- Scan the entire ports tree in order with a single, non-recursive pass
-- Return True on success
function scan_entire_ports_tree (portsdir : String) return Boolean;
-- Starting with a single port, recurse to determine a limited but complete
-- dependency tree. Repeated calls will augment already existing data.
-- Return True on success
function scan_single_port (repository, portsdir, catport : String)
return Boolean;
-- This procedure causes the reverse dependencies to be calculated, and
-- then the extended (recursive) reverse dependencies. The former is
-- used progressively to determine when a port is free to build and the
-- latter sets the build priority.
procedure set_build_priority;
-- Wipe out all scan data so new scan can be performed
procedure reset_ports_tree;
-- Returns the number of cores. The set_cores procedure must be run first.
-- set_cores was private previously, but we need the information to set
-- intelligent defaults for the configuration file.
procedure set_cores;
function cores_available return cpu_range;
private
max_ports : constant := 28000;
type port_id is range -1 .. max_ports - 1;
subtype port_index is port_id range 0 .. port_id'Last;
port_match_failed : constant port_id := port_id'First;
-- skip "package" because every port has same dependency on ports-mgmt/pkg
-- except for pkg itself. Skip "test" because these dependencies are
-- not required to build packages.
type dependency_type is (fetch, extract, patch, build, library, runtime);
subtype LR_set is dependency_type range library .. runtime;
bmake_execution : exception;
pkgng_execution : exception;
make_garbage : exception;
nonexistent_port : exception;
circular_logic : exception;
seek_failure : exception;
unknown_format : exception;
package subqueue is new AC.Vectors
(Element_Type => port_index,
Index_Type => port_index);
package string_crate is new AC.Vectors
(Element_Type => JT.Text,
Index_Type => port_index,
"=" => JT.SU."=");
type queue_record is
record
ap_index : port_index;
reverse_score : port_index;
end record;
-- Functions for ranking_crate definitions
function "<" (L, R : queue_record) return Boolean;
package ranking_crate is new AC.Ordered_Sets (Element_Type => queue_record);
-- Functions for portkey_crate and package_crate definitions
function port_hash (key : JT.Text) return AC.Hash_Type;
package portkey_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => port_index,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
package package_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => Boolean,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
-- Functions for block_crate definitions
function block_hash (key : port_index) return AC.Hash_Type;
function block_ekey (left, right : port_index) return Boolean;
package block_crate is new AC.Hashed_Maps
(Key_Type => port_index,
Element_Type => port_index,
Hash => block_hash,
Equivalent_Keys => block_ekey);
type port_record is
record
sequence_id : port_index := 0;
key_cursor : portkey_crate.Cursor := portkey_crate.No_Element;
jobs : builders := 1;
ignore_reason : JT.Text := JT.blank;
port_version : JT.Text := JT.blank;
package_name : JT.Text := JT.blank;
ignored : Boolean := False;
scanned : Boolean := False;
rev_scanned : Boolean := False;
unlist_failed : Boolean := False;
work_locked : Boolean := False;
reverse_score : port_index := 0;
librun : block_crate.Map;
blocked_by : block_crate.Map;
blocks : block_crate.Map;
all_reverse : block_crate.Map;
options : package_crate.Map;
end record;
type port_record_access is access all port_record;
type dim_make_queue is array (scanners) of subqueue.Vector;
type dim_progress is array (scanners) of port_index;
type dim_all_ports is array (port_index) of aliased port_record;
all_ports : dim_all_ports;
ports_keys : portkey_crate.Map;
make_queue : dim_make_queue;
mq_progress : dim_progress := (others => 0);
rank_queue : ranking_crate.Set;
number_cores : cpu_range := cpu_range'First;
lot_number : scanners := 1;
lot_counter : port_index := 0;
last_port : port_index := 0;
prescanned : Boolean := False;
procedure iterate_reverse_deps;
procedure iterate_drill_down;
procedure populate_port_data (portsdir : String;
target : port_index);
procedure drill_down (next_target : port_index;
original_target : port_index);
-- subroutines for populate_port_data
procedure prescan_ports_tree (portsdir : String);
procedure grep_Makefile (portsdir, category : String);
procedure walk_all_subdirectories (portsdir, category : String);
procedure parallel_deep_scan (portsdir : String; success : out Boolean);
procedure wipe_make_queue;
-- some helper routines
function find_colon (Source : String) return Natural;
function scrub_phase (Source : String) return JT.Text;
function get_catport (PR : port_record) return String;
function scan_progress return String;
function get_ccache return String;
function get_max_lots return scanners;
type dim_counters is array (count_type) of Natural;
-- bulk run variables
Flog : dim_handlers;
start_time : CAL.Time;
stop_time : CAL.Time;
bld_counter : dim_counters := (0, 0, 0, 0, 0);
end PortScan;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
-- GCC 6.0 only (skip Container_Checks until identified need arises)
pragma Suppress (Tampering_Check);
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Characters.Latin_1;
with Ada.Directories;
with JohnnyText;
with Parameters;
with Definitions; use Definitions;
package PortScan is
package JT renames JohnnyText;
package AC renames Ada.Containers;
package CAL renames Ada.Calendar;
package AD renames Ada.Directories;
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
package PM renames Parameters;
type count_type is (total, success, failure, ignored, skipped);
type dim_handlers is array (count_type) of TIO.File_Type;
type port_id is private;
port_match_failed : constant port_id;
-- Scan the entire ports tree in order with a single, non-recursive pass
-- Return True on success
function scan_entire_ports_tree (portsdir : String) return Boolean;
-- Starting with a single port, recurse to determine a limited but complete
-- dependency tree. Repeated calls will augment already existing data.
-- Return True on success
function scan_single_port (repository, portsdir, catport : String)
return Boolean;
-- This procedure causes the reverse dependencies to be calculated, and
-- then the extended (recursive) reverse dependencies. The former is
-- used progressively to determine when a port is free to build and the
-- latter sets the build priority.
procedure set_build_priority;
-- Wipe out all scan data so new scan can be performed
procedure reset_ports_tree;
-- Returns the number of cores. The set_cores procedure must be run first.
-- set_cores was private previously, but we need the information to set
-- intelligent defaults for the configuration file.
procedure set_cores;
function cores_available return cpu_range;
private
max_ports : constant := 28000;
type port_id is range -1 .. max_ports - 1;
subtype port_index is port_id range 0 .. port_id'Last;
port_match_failed : constant port_id := port_id'First;
-- skip "package" because every port has same dependency on ports-mgmt/pkg
-- except for pkg itself. Skip "test" because these dependencies are
-- not required to build packages.
type dependency_type is (fetch, extract, patch, build, library, runtime);
subtype LR_set is dependency_type range library .. runtime;
bmake_execution : exception;
pkgng_execution : exception;
make_garbage : exception;
nonexistent_port : exception;
circular_logic : exception;
seek_failure : exception;
unknown_format : exception;
package subqueue is new AC.Vectors
(Element_Type => port_index,
Index_Type => port_index);
package string_crate is new AC.Vectors
(Element_Type => JT.Text,
Index_Type => port_index,
"=" => JT.SU."=");
type queue_record is
record
ap_index : port_index;
reverse_score : port_index;
end record;
-- Functions for ranking_crate definitions
function "<" (L, R : queue_record) return Boolean;
package ranking_crate is new AC.Ordered_Sets (Element_Type => queue_record);
-- Functions for portkey_crate and package_crate definitions
function port_hash (key : JT.Text) return AC.Hash_Type;
package portkey_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => port_index,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
package package_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => Boolean,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
-- Functions for block_crate definitions
function block_hash (key : port_index) return AC.Hash_Type;
function block_ekey (left, right : port_index) return Boolean;
package block_crate is new AC.Hashed_Maps
(Key_Type => port_index,
Element_Type => port_index,
Hash => block_hash,
Equivalent_Keys => block_ekey);
type port_record is
record
sequence_id : port_index := 0;
key_cursor : portkey_crate.Cursor := portkey_crate.No_Element;
jobs : builders := 1;
ignore_reason : JT.Text := JT.blank;
port_version : JT.Text := JT.blank;
package_name : JT.Text := JT.blank;
ignored : Boolean := False;
scanned : Boolean := False;
rev_scanned : Boolean := False;
unlist_failed : Boolean := False;
work_locked : Boolean := False;
reverse_score : port_index := 0;
librun : block_crate.Map;
blocked_by : block_crate.Map;
blocks : block_crate.Map;
all_reverse : block_crate.Map;
options : package_crate.Map;
end record;
type port_record_access is access all port_record;
type dim_make_queue is array (scanners) of subqueue.Vector;
type dim_progress is array (scanners) of port_index;
type dim_all_ports is array (port_index) of aliased port_record;
all_ports : dim_all_ports;
ports_keys : portkey_crate.Map;
make_queue : dim_make_queue;
mq_progress : dim_progress := (others => 0);
rank_queue : ranking_crate.Set;
number_cores : cpu_range := cpu_range'First;
lot_number : scanners := 1;
lot_counter : port_index := 0;
last_port : port_index := 0;
prescanned : Boolean := False;
procedure iterate_reverse_deps;
procedure iterate_drill_down;
procedure populate_port_data (portsdir : String;
target : port_index);
procedure drill_down (next_target : port_index;
original_target : port_index);
-- subroutines for populate_port_data
procedure prescan_ports_tree (portsdir : String);
procedure grep_Makefile (portsdir, category : String);
procedure walk_all_subdirectories (portsdir, category : String);
procedure parallel_deep_scan (portsdir : String; success : out Boolean);
procedure wipe_make_queue;
-- some helper routines
function find_colon (Source : String) return Natural;
function scrub_phase (Source : String) return JT.Text;
function get_catport (PR : port_record) return String;
function scan_progress return String;
function get_ccache return String;
function get_max_lots return scanners;
type dim_counters is array (count_type) of Natural;
-- bulk run variables
Flog : dim_handlers;
start_time : CAL.Time;
stop_time : CAL.Time;
bld_counter : dim_counters := (0, 0, 0, 0, 0);
end PortScan;
|
Enable Tampering_Check pragma (gcc6-aux only)
|
Enable Tampering_Check pragma (gcc6-aux only)
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
adb7d1b0158dd3a61ac468965d7c97f28e002be4
|
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.Nodes;
with Wiki.Streams;
with Wiki.Render;
-- == 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);
type Parser is tagged limited private;
-- Add the plugin to the wiki engine.
procedure Add_Plugin (Engine : in out Parser;
Name : in String;
Plugin : in Wiki.Plugins.Wiki_Plugin_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax configured
-- on the wiki engine. The document reader operations are invoked while parsing the wiki
-- text.
procedure Parse (Engine : in out Parser;
Text : in Wide_Wide_String;
Render : in Wiki.Render.Renderer_Access);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine. The wiki is then rendered by using the renderer.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Render : in Wiki.Render.Renderer_Access);
private
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 Parser is tagged limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Syntax : Wiki_Syntax_Type;
Document : Wiki.Nodes.Document;
Filters : Wiki.Filters.Filter_Type_Access;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Token : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_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);
-- 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 Wide_Wide_Character);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wide_Wide_String) return Boolean;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type);
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.Nodes;
with Wiki.Streams;
with Wiki.Render;
-- == 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);
type Parser is tagged limited private;
-- Add the plugin to the wiki engine.
procedure Add_Plugin (Engine : in out Parser;
Name : in String;
Plugin : in Wiki.Plugins.Wiki_Plugin_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wide_Wide_String);
-- 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);
private
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 Parser is tagged limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Syntax : Wiki_Syntax_Type;
Document : Wiki.Nodes.Document;
Filters : Wiki.Filters.Filter_Chain;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Token : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_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);
-- 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 Wide_Wide_Character);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wide_Wide_String) return Boolean;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in out Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type);
end Wiki.Parsers;
|
Use the Filter_Chain to maintain the filters
|
Use the Filter_Chain to maintain the filters
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
5d74db6ed411013d50f5229bd0d6dd6e338516d9
|
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
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;
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);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- 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 Ada.Containers.Vectors;
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;
package Wide_Wide_String_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Unbounded_Wide_Wide_String);
subtype Wide_Wide_String_Vector is Wide_Wide_String_Vectors.Vector;
subtype Wide_Wide_String_Cursor is Wide_Wide_String_Vectors.Cursor;
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;
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;
Html_Stack : Wide_Wide_String_Vector;
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);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
procedure Start_Element (P : in out Parser;
Name : in Ada.Strings.Wide_Wide_Unbounded.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);
-- Flush the pending HTML stack elements.
procedure Flush_Stack (P : in out Parser);
end Wiki.Parsers;
|
Declare Wide_Wide_String_Vectors package to maintain a stack of HTML elements that have been created
|
Declare Wide_Wide_String_Vectors package to maintain a stack of HTML elements that have been created
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
ed9b093af0c18b9d43f9cd62fafa6ee84d9f882e
|
awa/plugins/awa-votes/src/awa-votes-beans.ads
|
awa/plugins/awa-votes/src/awa-votes-beans.ads
|
-----------------------------------------------------------------------
-- awa-votes-beans -- Beans for module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with AWA.Votes.Modules;
with AWA.Votes.Models;
-- === Vote Beans ===
-- The <b>Vote_Bean</b> is a bean intended to be used in presentation files (facelet files)
-- to vote for an item. The managed bean can be easily configured in the application XML
-- configuration file. The <b>permission</b> and <b>entity_type</b> are the two properties
-- that should be defined in the configuration. The <b>permission</b> is the name of the
-- permission that must be used to verify that the user is allowed to vote for the item.
-- The <b>entity_type</b> is the name of the entity (table name) used by the item.
-- The example below defines the bean <tt>questionVote</tt> defined by the question module.
--
-- <managed-bean>
-- <description>The vote bean that allows to vote for a question.</description>
-- <managed-bean-name>questionVote</managed-bean-name>
-- <managed-bean-class>AWA.Votes.Beans.Votes_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>answer-create</value>
-- </managed-property>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
-- The vote concerns entities for the <tt>awa_question</tt> entity table.
-- The permission <tt>answer-create</tt> is used to verify for the vote.
--
-- [http://ada-awa.googlecode.com/svn/wiki/awa_votes_bean.png]
--
package AWA.Votes.Beans is
type Vote_Bean is new AWA.Votes.Models.Vote_Bean with private;
type Vote_Bean_Access is access all Vote_Bean'Class;
-- Action to vote up.
overriding
procedure Vote_Up (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Action to vote down.
overriding
procedure Vote_Down (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Action to vote.
overriding
procedure Vote (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Votes_Bean bean instance.
function Create_Vote_Bean (Module : in AWA.Votes.Modules.Vote_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
private
type Vote_Bean is new AWA.Votes.Models.Vote_Bean with record
Module : AWA.Votes.Modules.Vote_Module_Access := null;
end record;
end AWA.Votes.Beans;
|
-----------------------------------------------------------------------
-- awa-votes-beans -- Beans for module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with AWA.Votes.Modules;
with AWA.Votes.Models;
-- === Vote Beans ===
-- The <tt>Vote_Bean</tt> is a bean intended to be used in presentation files (XHTML facelet
-- files) to vote for an item. The managed bean can be easily configured in the application XML
-- configuration file. The <b>permission</b> and <b>entity_type</b> are the two properties
-- that should be defined in the configuration. The <b>permission</b> is the name of the
-- permission that must be used to verify that the user is allowed to vote for the item.
-- The <b>entity_type</b> is the name of the entity (table name) used by the item.
-- The example below defines the bean <tt>questionVote</tt> defined by the question module.
--
-- <managed-bean>
-- <description>The vote bean that allows to vote for a question.</description>
-- <managed-bean-name>questionVote</managed-bean-name>
-- <managed-bean-class>AWA.Votes.Beans.Votes_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>answer-create</value>
-- </managed-property>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
-- The vote concerns entities for the <tt>awa_question</tt> entity table.
-- The permission <tt>answer-create</tt> is used to verify that the vote is allowed.
--
-- [http://ada-awa.googlecode.com/svn/wiki/awa_votes_bean.png]
--
-- The managed bean defines three operations that can be called: <tt>vote_up</tt>,
-- <tt>vote_down</tt> and <tt>vote</tt> to setup specific ratings.
package AWA.Votes.Beans is
type Vote_Bean is new AWA.Votes.Models.Vote_Bean with private;
type Vote_Bean_Access is access all Vote_Bean'Class;
-- Action to vote up.
overriding
procedure Vote_Up (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Action to vote down.
overriding
procedure Vote_Down (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Action to vote.
overriding
procedure Vote (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Votes_Bean bean instance.
function Create_Vote_Bean (Module : in AWA.Votes.Modules.Vote_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
private
type Vote_Bean is new AWA.Votes.Models.Vote_Bean with record
Module : AWA.Votes.Modules.Vote_Module_Access := null;
end record;
end AWA.Votes.Beans;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3c7fad00a9242cf6a6e94423238c430e9bb4e076
|
awa/awaunit/awa-tests-helpers-users.adb
|
awa/awaunit/awa-tests-helpers-users.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2011, 2012, 2013, 2014, 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 Ada.Unchecked_Deallocation;
with Util.Tests;
with Util.Log.Loggers;
with ASF.Principals;
with ASF.Tests;
with ASF.Responses.Mockup;
with AWA.Applications;
with AWA.Tests;
with AWA.Users.Modules;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Tests.Helpers.Users is
use AWA.Users.Services;
use type AWA.Users.Principals.Principal_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users");
MAX_USERS : constant Positive := 10;
Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class,
Name => AWA.Users.Principals.Principal_Access);
-- ------------------------------
-- Initialize the service context.
-- ------------------------------
procedure Initialize (Principal : in out Test_User) is
begin
-- Setup the service context.
Principal.Context.Set_Context (AWA.Tests.Get_Application, null);
if Principal.Manager = null then
Principal.Manager := AWA.Users.Modules.Get_User_Manager;
if Principal.Manager = null then
Log.Error ("There is no User_Manager in the application.");
end if;
end if;
end Initialize;
-- ------------------------------
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
-- ------------------------------
procedure Create_User (Principal : in out Test_User;
Email : in String) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the user
Query.Set_Join ("inner join awa_email e on e.user_id = o.id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Principal.User.Find (DB, Query, Found);
if not Found then
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
else
Principal.Manager.Authenticate (Email => Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
end if;
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Create a test user for a new test and get an open session.
-- ------------------------------
procedure Create_User (Principal : in out Test_User) is
Key : AWA.Users.Models.Access_Key_Ref;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
begin
Initialize (Principal);
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Find the access key associated with a user (if any).
-- ------------------------------
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Signup_Kind : constant Integer
:= AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.SIGNUP_KEY);
Password_Kind : constant Integer
:= AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.RESET_PASSWORD_KEY);
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the access key
Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id");
Query.Set_Filter ("e.email = ? AND o.kind = ?");
Query.Bind_Param (1, Email);
Query.Bind_Param (2, Signup_Kind);
Key.Find (DB, Query, Found);
if not Found then
Query.Bind_Param (2, Password_Kind);
Key.Find (DB, Query, Found);
if not Found then
Log.Error ("Cannot find access key for email {0}", Email);
end if;
end if;
end Find_Access_Key;
-- ------------------------------
-- Login a user and create a session
-- ------------------------------
procedure Login (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Authenticate (Email => Principal.Email.Get_Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Login;
-- ------------------------------
-- Logout the user and closes the current session.
-- ------------------------------
procedure Logout (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Close_Session (Principal.Session.Get_Id, True);
end Logout;
-- ------------------------------
-- Simulate a user login in the given service context.
-- ------------------------------
procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String) is
User : Test_User;
Principal : AWA.Users.Principals.Principal_Access;
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Create_User (User, Email);
Principal := AWA.Users.Principals.Create (User.User, User.Session);
Context.Set_Context (App, Principal);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => Principal.all'Access);
-- Keep track of the Principal instance so that Tear_Down will release it.
-- Most tests will call Login but don't call Logout because there is no real purpose
-- for the test in doing that and it allows to keep the unit test simple. This creates
-- memory leak because the Principal instance is not freed.
for I in Logged_Users'Range loop
if Logged_Users (I) = null then
Logged_Users (I) := Principal;
exit;
end if;
end loop;
end Login;
-- ------------------------------
-- Simulate a user login on the request. Upon successful login, a session that is
-- authentified is associated with the request object.
-- ------------------------------
procedure Login (Email : in String;
Request : in out ASF.Requests.Mockup.Request'Class) is
User : Test_User;
Reply : ASF.Responses.Mockup.Response;
begin
Create_User (User, Email);
ASF.Tests.Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("login", "1");
Request.Set_Parameter ("login-button", "1");
ASF.Tests.Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html");
end Login;
-- ------------------------------
-- Setup the context and security context to simulate an anonymous user.
-- ------------------------------
procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context) is
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Context.Set_Context (App, null);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => null);
end Anonymous;
-- ------------------------------
-- Simulate the recovery password process for the given user.
-- ------------------------------
procedure Recover_Password (Email : in String) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("lost-password", "1");
Request.Set_Parameter ("lost-password-button", "1");
ASF.Tests.Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html");
if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then
Log.Error ("Invalid redirect after lost password");
end if;
-- Now, get the access key and simulate a click on the reset password link.
declare
Principal : AWA.Tests.Helpers.Users.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Set_Application_Context;
AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key);
if not Key.Is_Null then
Log.Error ("There is no access key associated with the user");
end if;
-- Simulate user clicking on the reset password link.
-- This verifies the key, login the user and redirect him to the change-password page
Request.Set_Parameter ("key", Key.Get_Access_Key);
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("reset-password", "1");
ASF.Tests.Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html");
if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then
Log.Error ("Invalid response");
end if;
-- Check that the user is logged and we have a user principal now.
if Request.Get_User_Principal = null then
Log.Error ("A user principal should be defined");
end if;
end;
end Recover_Password;
overriding
procedure Finalize (Principal : in out Test_User) is
begin
Free (Principal.Principal);
end Finalize;
-- ------------------------------
-- Cleanup and release the Principal that have been allocated from the Login session
-- but not released because the Logout is not called from the unit test.
-- ------------------------------
procedure Tear_Down is
begin
for I in Logged_Users'Range loop
if Logged_Users (I) /= null then
Free (Logged_Users (I));
end if;
end loop;
end Tear_Down;
end AWA.Tests.Helpers.Users;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Tests;
with Util.Log.Loggers;
with ASF.Principals;
with ASF.Tests;
with ASF.Responses.Mockup;
with AWA.Applications;
with AWA.Users.Modules;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Tests.Helpers.Users is
use AWA.Users.Services;
use type AWA.Users.Principals.Principal_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users");
MAX_USERS : constant Positive := 10;
Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class,
Name => AWA.Users.Principals.Principal_Access);
-- ------------------------------
-- Initialize the service context.
-- ------------------------------
procedure Initialize (Principal : in out Test_User) is
begin
-- Setup the service context.
Principal.Context.Set_Context (AWA.Tests.Get_Application, null);
if Principal.Manager = null then
Principal.Manager := AWA.Users.Modules.Get_User_Manager;
if Principal.Manager = null then
Log.Error ("There is no User_Manager in the application.");
end if;
end if;
end Initialize;
-- ------------------------------
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
-- ------------------------------
procedure Create_User (Principal : in out Test_User;
Email : in String) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the user
Query.Set_Join ("inner join awa_email e on e.user_id = o.id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Principal.User.Find (DB, Query, Found);
if not Found then
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
else
Principal.Manager.Authenticate (Email => Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
end if;
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Create a test user for a new test and get an open session.
-- ------------------------------
procedure Create_User (Principal : in out Test_User) is
Key : AWA.Users.Models.Access_Key_Ref;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
begin
Initialize (Principal);
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Find the access key associated with a user (if any).
-- ------------------------------
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Signup_Kind : constant Integer
:= AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.SIGNUP_KEY);
Password_Kind : constant Integer
:= AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.RESET_PASSWORD_KEY);
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the access key
Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id");
Query.Set_Filter ("e.email = ? AND o.kind = ?");
Query.Bind_Param (1, Email);
Query.Bind_Param (2, Signup_Kind);
Key.Find (DB, Query, Found);
if not Found then
Query.Bind_Param (2, Password_Kind);
Key.Find (DB, Query, Found);
if not Found then
Log.Error ("Cannot find access key for email {0}", Email);
end if;
end if;
end Find_Access_Key;
-- ------------------------------
-- Login a user and create a session
-- ------------------------------
procedure Login (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Authenticate (Email => Principal.Email.Get_Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Login;
-- ------------------------------
-- Logout the user and closes the current session.
-- ------------------------------
procedure Logout (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Close_Session (Principal.Session.Get_Id, True);
end Logout;
-- ------------------------------
-- Simulate a user login in the given service context.
-- ------------------------------
procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String) is
User : Test_User;
Principal : AWA.Users.Principals.Principal_Access;
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Create_User (User, Email);
Principal := AWA.Users.Principals.Create (User.User, User.Session);
Context.Set_Context (App, Principal);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => Principal.all'Access);
-- Keep track of the Principal instance so that Tear_Down will release it.
-- Most tests will call Login but don't call Logout because there is no real purpose
-- for the test in doing that and it allows to keep the unit test simple. This creates
-- memory leak because the Principal instance is not freed.
for I in Logged_Users'Range loop
if Logged_Users (I) = null then
Logged_Users (I) := Principal;
exit;
end if;
end loop;
end Login;
-- ------------------------------
-- Simulate a user login on the request. Upon successful login, a session that is
-- authentified is associated with the request object.
-- ------------------------------
procedure Login (Email : in String;
Request : in out ASF.Requests.Mockup.Request'Class) is
User : Test_User;
Reply : ASF.Responses.Mockup.Response;
begin
Create_User (User, Email);
ASF.Tests.Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("login", "1");
Request.Set_Parameter ("login-button", "1");
ASF.Tests.Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html");
end Login;
-- ------------------------------
-- Setup the context and security context to simulate an anonymous user.
-- ------------------------------
procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context) is
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Context.Set_Context (App, null);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => null);
end Anonymous;
-- ------------------------------
-- Simulate the recovery password process for the given user.
-- ------------------------------
procedure Recover_Password (Email : in String) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("lost-password", "1");
Request.Set_Parameter ("lost-password-button", "1");
ASF.Tests.Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html");
if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then
Log.Error ("Invalid redirect after lost password");
end if;
-- Now, get the access key and simulate a click on the reset password link.
declare
Principal : AWA.Tests.Helpers.Users.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Set_Application_Context;
AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key);
if not Key.Is_Null then
Log.Error ("There is no access key associated with the user");
end if;
-- Simulate user clicking on the reset password link.
-- This verifies the key, login the user and redirect him to the change-password page
Request.Set_Parameter ("key", Key.Get_Access_Key);
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("reset-password", "1");
ASF.Tests.Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html");
if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then
Log.Error ("Invalid response");
end if;
-- Check that the user is logged and we have a user principal now.
if Request.Get_User_Principal = null then
Log.Error ("A user principal should be defined");
end if;
end;
end Recover_Password;
overriding
procedure Finalize (Principal : in out Test_User) is
begin
Free (Principal.Principal);
end Finalize;
-- ------------------------------
-- Cleanup and release the Principal that have been allocated from the Login session
-- but not released because the Logout is not called from the unit test.
-- ------------------------------
procedure Tear_Down is
begin
for I in Logged_Users'Range loop
if Logged_Users (I) /= null then
Free (Logged_Users (I));
end if;
end loop;
end Tear_Down;
end AWA.Tests.Helpers.Users;
|
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
|
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
fb1bffefc1b92bb3a3eccda6b9384661b676b092
|
awa/awaunit/awa-tests-helpers-users.ads
|
awa/awaunit/awa-tests-helpers-users.ads
|
-----------------------------------------------------------------------
-- users-tests-helpers -- Helpers for user creation
-- 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.Finalization;
with Security.Contexts;
with ASF.Requests.Mockup;
with AWA.Users.Models;
with AWA.Users.Services;
with AWA.Services.Contexts;
with AWA.Users.Principals;
package AWA.Tests.Helpers.Users is
type Test_User is new Ada.Finalization.Limited_Controlled with record
Context : AWA.Services.Contexts.Service_Context;
Manager : AWA.Users.Services.User_Service_Access := null;
User : AWA.Users.Models.User_Ref;
Email : AWA.Users.Models.Email_Ref;
Session : AWA.Users.Models.Session_Ref;
Principal : AWA.Users.Principals.Principal_Access;
end record;
-- Initialize the service context.
procedure Initialize (Principal : in out Test_User);
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
procedure Create_User (Principal : in out Test_User;
Email : in String);
-- Create a test user for a new test and get an open session.
procedure Create_User (Principal : in out Test_User);
-- Find the access key associated with a user (if any).
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref);
-- Login a user and create a session
procedure Login (Principal : in out Test_User);
-- Logout the user and closes the current session.
procedure Logout (Principal : in out Test_User);
-- Simulate a user login in the given service context.
procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String);
-- Simulate a user login on the request. Upon successful login, a session that is
-- authentified is associated with the request object.
procedure Login (Email : in String;
Request : in out ASF.Requests.Mockup.Request);
-- Setup the context and security context to simulate an anonymous user.
procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context);
overriding
procedure Finalize (Principal : in out Test_User);
-- Cleanup and release the Principal that have been allocated from the Login session
-- but not released because the Logout is not called from the unit test.
procedure Tear_Down;
end AWA.Tests.Helpers.Users;
|
-----------------------------------------------------------------------
-- users-tests-helpers -- Helpers for user creation
-- 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.Finalization;
with Security.Contexts;
with ASF.Requests.Mockup;
with AWA.Users.Models;
with AWA.Users.Services;
with AWA.Services.Contexts;
with AWA.Users.Principals;
package AWA.Tests.Helpers.Users is
type Test_User is new Ada.Finalization.Limited_Controlled with record
Context : AWA.Services.Contexts.Service_Context;
Manager : AWA.Users.Services.User_Service_Access := null;
User : AWA.Users.Models.User_Ref;
Email : AWA.Users.Models.Email_Ref;
Session : AWA.Users.Models.Session_Ref;
Principal : AWA.Users.Principals.Principal_Access;
end record;
-- Initialize the service context.
procedure Initialize (Principal : in out Test_User);
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
procedure Create_User (Principal : in out Test_User;
Email : in String);
-- Create a test user for a new test and get an open session.
procedure Create_User (Principal : in out Test_User);
-- Find the access key associated with a user (if any).
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref);
-- Login a user and create a session
procedure Login (Principal : in out Test_User);
-- Logout the user and closes the current session.
procedure Logout (Principal : in out Test_User);
-- Simulate a user login in the given service context.
procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String);
-- Simulate a user login on the request. Upon successful login, a session that is
-- authentified is associated with the request object.
procedure Login (Email : in String;
Request : in out ASF.Requests.Mockup.Request);
-- Setup the context and security context to simulate an anonymous user.
procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class;
Sec_Context : in out Security.Contexts.Security_Context);
-- Simulate the recovery password process for the given user.
procedure Recover_Password (Email : in String);
overriding
procedure Finalize (Principal : in out Test_User);
-- Cleanup and release the Principal that have been allocated from the Login session
-- but not released because the Logout is not called from the unit test.
procedure Tear_Down;
end AWA.Tests.Helpers.Users;
|
Declare the Recover_Password procedure
|
Declare the Recover_Password procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3a7bbcb02d0acac34f7c172ad3ced39c149ee605
|
awa/src/awa-services-contexts.adb
|
awa/src/awa-services-contexts.adb
|
-----------------------------------------------------------------------
-- awa-services -- Services
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with ADO.Databases;
package body AWA.Services.Contexts is
use type ADO.Databases.Connection_Status;
use type AWA.Users.Principals.Principal_Access;
package Task_Context is new Ada.Task_Attributes
(Service_Context_Access, null);
-- ------------------------------
-- Get the application associated with the current service operation.
-- ------------------------------
function Get_Application (Ctx : in Service_Context)
return AWA.Applications.Application_Access is
begin
return Ctx.Application;
end Get_Application;
-- ------------------------------
-- Get the current database connection for reading.
-- ------------------------------
function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is
begin
-- If a master database session was created, use it.
if Ctx.Master.Get_Status = ADO.Databases.OPEN then
return ADO.Sessions.Session (Ctx.Master);
elsif Ctx.Slave.Get_Status /= ADO.Databases.OPEN then
Ctx.Slave := Ctx.Application.Get_Session;
end if;
return Ctx.Slave;
end Get_Session;
-- ------------------------------
-- Get the current database connection for reading and writing.
-- ------------------------------
function Get_Master_Session (Ctx : in Service_Context_Access)
return ADO.Sessions.Master_Session is
begin
if Ctx.Master.Get_Status /= ADO.Databases.OPEN then
Ctx.Master := Ctx.Application.Get_Master_Session;
end if;
return Ctx.Master;
end Get_Master_Session;
-- ------------------------------
-- Get the current user invoking the service operation.
-- Returns a null user if there is none.
-- ------------------------------
function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is
begin
if Ctx.Principal = null then
return AWA.Users.Models.Null_User;
else
return Ctx.Principal.Get_User;
end if;
end Get_User;
-- ------------------------------
-- Get the current user identifier invoking the service operation.
-- Returns NO_IDENTIFIER if there is none.
-- ------------------------------
function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is
begin
if Ctx.Principal = null then
return ADO.NO_IDENTIFIER;
else
return Ctx.Principal.Get_User_Identifier;
end if;
end Get_User_Identifier;
-- ------------------------------
-- Get the current user session from the user invoking the service operation.
-- Returns a null session if there is none.
-- ------------------------------
function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is
begin
if Ctx.Principal = null then
return AWA.Users.Models.Null_Session;
else
return Ctx.Principal.Get_Session;
end if;
end Get_User_Session;
-- ------------------------------
-- Starts a transaction.
-- ------------------------------
procedure Start (Ctx : in out Service_Context) is
begin
if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then
Ctx.Master.Begin_Transaction;
Ctx.Active_Transaction := True;
end if;
Ctx.Transaction := Ctx.Transaction + 1;
end Start;
-- ------------------------------
-- Commits the current transaction. The database transaction is really committed by the
-- last <b>Commit</b> called.
-- ------------------------------
procedure Commit (Ctx : in out Service_Context) is
begin
Ctx.Transaction := Ctx.Transaction - 1;
if Ctx.Transaction = 0 and then Ctx.Active_Transaction then
Ctx.Master.Commit;
Ctx.Active_Transaction := False;
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction. The database transaction is rollback at the first
-- call to <b>Rollback</b>.
-- ------------------------------
procedure Rollback (Ctx : in out Service_Context) is
begin
null;
end Rollback;
-- ------------------------------
-- Get the attribute registered under the given name in the HTTP session.
-- ------------------------------
function Get_Session_Attribute (Ctx : in Service_Context;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Ctx, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Session_Attribute;
-- ------------------------------
-- Set the attribute registered under the given name in the HTTP session.
-- ------------------------------
procedure Set_Session_Attribute (Ctx : in out Service_Context;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
null;
end Set_Session_Attribute;
-- ------------------------------
-- Set the current application and user context.
-- ------------------------------
procedure Set_Context (Ctx : in out Service_Context;
Application : in AWA.Applications.Application_Access;
Principal : in AWA.Users.Principals.Principal_Access) is
begin
Ctx.Application := Application;
Ctx.Principal := Principal;
end Set_Context;
-- ------------------------------
-- Initializes the service context.
-- ------------------------------
overriding
procedure Initialize (Ctx : in out Service_Context) is
use type AWA.Applications.Application_Access;
begin
Ctx.Previous := Task_Context.Value;
Task_Context.Set_Value (Ctx'Unchecked_Access);
if Ctx.Previous /= null and then Ctx.Application = null then
Ctx.Application := Ctx.Previous.Application;
end if;
end Initialize;
-- ------------------------------
-- Finalize the service context, rollback non-committed transaction, releases any object.
-- ------------------------------
overriding
procedure Finalize (Ctx : in out Service_Context) is
begin
-- When the service context is released, we must not have any active transaction.
-- This means we are leaving the service in an abnormal way such as when an
-- exception is raised. If this is the case, rollback the transaction.
if Ctx.Active_Transaction then
Ctx.Master.Rollback;
end if;
Task_Context.Set_Value (Ctx.Previous);
end Finalize;
-- ------------------------------
-- Get the current service context.
-- Returns null if the current thread is not associated with any service context.
-- ------------------------------
function Current return Service_Context_Access is
begin
return Task_Context.Value;
end Current;
end AWA.Services.Contexts;
|
-----------------------------------------------------------------------
-- awa-services -- Services
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with ADO.Databases;
package body AWA.Services.Contexts is
use type ADO.Databases.Connection_Status;
use type AWA.Users.Principals.Principal_Access;
package Task_Context is new Ada.Task_Attributes
(Service_Context_Access, null);
-- ------------------------------
-- Get the application associated with the current service operation.
-- ------------------------------
function Get_Application (Ctx : in Service_Context)
return AWA.Applications.Application_Access is
begin
return Ctx.Application;
end Get_Application;
-- ------------------------------
-- Get the current database connection for reading.
-- ------------------------------
function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is
begin
-- If a master database session was created, use it.
if Ctx.Master.Get_Status = ADO.Databases.OPEN then
return ADO.Sessions.Session (Ctx.Master);
elsif Ctx.Slave.Get_Status /= ADO.Databases.OPEN then
Ctx.Slave := Ctx.Application.Get_Session;
end if;
return Ctx.Slave;
end Get_Session;
-- ------------------------------
-- Get the current database connection for reading and writing.
-- ------------------------------
function Get_Master_Session (Ctx : in Service_Context_Access)
return ADO.Sessions.Master_Session is
begin
if Ctx.Master.Get_Status /= ADO.Databases.OPEN then
Ctx.Master := Ctx.Application.Get_Master_Session;
end if;
return Ctx.Master;
end Get_Master_Session;
-- ------------------------------
-- Get the current user invoking the service operation.
-- Returns a null user if there is none.
-- ------------------------------
function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is
begin
if Ctx.Principal = null then
return AWA.Users.Models.Null_User;
else
return Ctx.Principal.Get_User;
end if;
end Get_User;
-- ------------------------------
-- Get the current user identifier invoking the service operation.
-- Returns NO_IDENTIFIER if there is none.
-- ------------------------------
function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is
begin
if Ctx.Principal = null then
return ADO.NO_IDENTIFIER;
else
return Ctx.Principal.Get_User_Identifier;
end if;
end Get_User_Identifier;
-- ------------------------------
-- Get the current user session from the user invoking the service operation.
-- Returns a null session if there is none.
-- ------------------------------
function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is
begin
if Ctx.Principal = null then
return AWA.Users.Models.Null_Session;
else
return Ctx.Principal.Get_Session;
end if;
end Get_User_Session;
-- ------------------------------
-- Starts a transaction.
-- ------------------------------
procedure Start (Ctx : in out Service_Context) is
begin
if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then
Ctx.Master.Begin_Transaction;
Ctx.Active_Transaction := True;
end if;
Ctx.Transaction := Ctx.Transaction + 1;
end Start;
-- ------------------------------
-- Commits the current transaction. The database transaction is really committed by the
-- last <b>Commit</b> called.
-- ------------------------------
procedure Commit (Ctx : in out Service_Context) is
begin
Ctx.Transaction := Ctx.Transaction - 1;
if Ctx.Transaction = 0 and then Ctx.Active_Transaction then
Ctx.Master.Commit;
Ctx.Active_Transaction := False;
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction. The database transaction is rollback at the first
-- call to <b>Rollback</b>.
-- ------------------------------
procedure Rollback (Ctx : in out Service_Context) is
begin
null;
end Rollback;
-- ------------------------------
-- Get the attribute registered under the given name in the HTTP session.
-- ------------------------------
function Get_Session_Attribute (Ctx : in Service_Context;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Ctx, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Session_Attribute;
-- ------------------------------
-- Set the attribute registered under the given name in the HTTP session.
-- ------------------------------
procedure Set_Session_Attribute (Ctx : in out Service_Context;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
null;
end Set_Session_Attribute;
-- ------------------------------
-- Set the current application and user context.
-- ------------------------------
procedure Set_Context (Ctx : in out Service_Context;
Application : in AWA.Applications.Application_Access;
Principal : in AWA.Users.Principals.Principal_Access) is
begin
Ctx.Application := Application;
Ctx.Principal := Principal;
end Set_Context;
-- ------------------------------
-- Initializes the service context.
-- ------------------------------
overriding
procedure Initialize (Ctx : in out Service_Context) is
use type AWA.Applications.Application_Access;
begin
Ctx.Previous := Task_Context.Value;
Task_Context.Set_Value (Ctx'Unchecked_Access);
if Ctx.Previous /= null and then Ctx.Application = null then
Ctx.Application := Ctx.Previous.Application;
end if;
end Initialize;
-- ------------------------------
-- Finalize the service context, rollback non-committed transaction, releases any object.
-- ------------------------------
overriding
procedure Finalize (Ctx : in out Service_Context) is
begin
-- When the service context is released, we must not have any active transaction.
-- This means we are leaving the service in an abnormal way such as when an
-- exception is raised. If this is the case, rollback the transaction.
if Ctx.Active_Transaction then
Ctx.Master.Rollback;
end if;
Task_Context.Set_Value (Ctx.Previous);
end Finalize;
-- ------------------------------
-- Get the current service context.
-- Returns null if the current thread is not associated with any service context.
-- ------------------------------
function Current return Service_Context_Access is
begin
return Task_Context.Value;
end Current;
-- ------------------------------
-- Run the process procedure on behalf of the specific user and session.
-- This operation changes temporarily the identity of the current user principal and
-- executes the <tt>Process</tt> procedure.
-- ------------------------------
procedure Run_As (User : in AWA.Users.Models.User_Ref;
Session : in AWA.Users.Models.Session_Ref) is
Ctx : Service_Context;
Principal : aliased AWA.Users.Principals.Principal
:= AWA.Users.Principals.Create (User, Session);
begin
Ctx.Principal := Principal'Unchecked_Access;
Process;
end Run_As;
end AWA.Services.Contexts;
|
Implement the Run_As by creating a local service context with a user principal and calling the process procedure. When we return (normal return or from an exception), the previous service context is restored
|
Implement the Run_As by creating a local service context with a user
principal and calling the process procedure. When we return (normal
return or from an exception), the previous service context is restored
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
68f2185fecd5c3c357c465ea7e1f41d31dbd3d93
|
awa/awaunit/awa-tests.adb
|
awa/awaunit/awa-tests.adb
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
with AWA.Tests.Helpers.Users;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
-- ------------------------------
-- Cleanup after the test execution.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
begin
AWA.Tests.Helpers.Users.Tear_Down;
end Tear_Down;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
pragma Unreferenced (Add_Modules);
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access);
end Initialize_Filters;
end AWA.Tests;
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Termination;
with Ada.Task_Identification;
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with ASF.Server.Tests;
with Util.Log.Loggers;
with ASF.Tests;
with AWA.Applications.Factory;
with AWA.Tests.Helpers.Users;
package body AWA.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests");
protected Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence);
end Shutdown;
Application_Created : Boolean := False;
Application : AWA.Applications.Application_Access := null;
Factory : AWA.Applications.Factory.Application_Factory;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
protected body Shutdown is
procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination;
Id : in Ada.Task_Identification.Task_Id;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Cause, Id, Ex);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
Free (Application);
end Termination;
end Shutdown;
-- ------------------------------
-- Setup the service context before executing the test.
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Up;
-- ------------------------------
-- Cleanup after the test execution.
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
begin
AWA.Tests.Helpers.Users.Tear_Down;
end Tear_Down;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Called when the testsuite execution has finished.
-- ------------------------------
procedure Finish (Status : in Util.XUnit.Status) is
pragma Unreferenced (Status);
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class,
Name => AWA.Applications.Application_Access);
begin
if Application_Created then
Free (Application);
end if;
end Finish;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
pragma Unreferenced (Add_Modules);
use AWA.Applications;
begin
-- Create the application unless it is specified as argument.
-- Install a shutdown hook to delete the application when the primary task exits.
-- This allows to stop the event threads if any.
if App = null then
Application_Created := True;
Application := new Test_Application;
Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task,
Shutdown.Termination'Access);
else
Application := App;
end if;
ASF.Tests.Initialize (Props, Application.all'Access, Factory);
Application.Add_Filter ("service", Service_Filter'Access);
Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html");
Application.Start;
end Initialize;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return AWA.Applications.Application_Access is
begin
return Application;
end Get_Application;
-- ------------------------------
-- Set the application context to simulate a web request context.
-- ------------------------------
procedure Set_Application_Context is
begin
ASF.Server.Tests.Set_Context (Application.all'Access);
end Set_Application_Context;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Test_Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access);
App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access);
App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access);
-- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access);
-- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Test_Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access);
end Initialize_Filters;
end AWA.Tests;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
cfbce7672fd1e1c4f9186f50778c7c83c98cafea
|
mat/src/memory/mat-memory-targets.adb
|
mat/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
Memory.Frames := Frames.Create_Root;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in Target_Memory;
Sizes : in out Size_Info_Map) is
Iter : Allocation_Cursor := Memory.Memory_Slots.First;
procedure Update_Count (Size : in MAT.Types.Target_Size;
Info : in out Size_Info_Type) is
begin
Info.Count := Info.Count + 1;
end Update_Count;
procedure Collect (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Pos : Size_Info_Cursor := Sizes.Find (Slot.Size);
begin
if Size_Info_Maps.Has_Element (Pos) then
Sizes.Update_Element (Pos, Update_Count'Access);
else
declare
Info : Size_Info_Type;
begin
Info.Count := 1;
Sizes.Insert (Slot.Size, Info);
end;
end if;
end Collect;
begin
while Allocation_Maps.Has_Element (Iter) loop
Allocation_Maps.Query_Element (Iter, Collect'Access);
Allocation_Maps.Next (Iter);
end loop;
end Size_Information;
protected body Memory_Allocator is
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Slot.Size);
Item : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Item := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Item.Size) > Addr then
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
Used_Slots.Insert (Addr, Slot);
end Probe_Malloc;
end Memory_Allocator;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
Memory.Frames := Frames.Create_Root;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in Target_Memory;
Sizes : in out Size_Info_Map) is
Iter : Allocation_Cursor := Memory.Memory_Slots.First;
procedure Update_Count (Size : in MAT.Types.Target_Size;
Info : in out Size_Info_Type) is
begin
Info.Count := Info.Count + 1;
end Update_Count;
procedure Collect (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Pos : Size_Info_Cursor := Sizes.Find (Slot.Size);
begin
if Size_Info_Maps.Has_Element (Pos) then
Sizes.Update_Element (Pos, Update_Count'Access);
else
declare
Info : Size_Info_Type;
begin
Info.Count := 1;
Sizes.Insert (Slot.Size, Info);
end;
end if;
end Collect;
begin
while Allocation_Maps.Has_Element (Iter) loop
Allocation_Maps.Query_Element (Iter, Collect'Access);
Allocation_Maps.Next (Iter);
end loop;
end Size_Information;
protected body Memory_Allocator is
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Slot.Size);
Item : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Item := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Item.Size) > Addr then
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
Used_Slots.Insert (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
end Memory_Allocator;
end MAT.Memory.Targets;
|
Implement the protected operation Probe_Free
|
Implement the protected operation Probe_Free
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
578eca95a97ebc332c02cf567b3ecf1565bfee88
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Abstract_Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Role_Type) return Boolean is abstract;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Abstract_Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Abstract_Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Abstract_Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Role_Type) return Boolean is abstract;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Abstract_Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Abstract_Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
Document the permission
|
Document the permission
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
c76c399c35d6aec4febf2c69e756df6e1d4930b5
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Abstract_Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Abstract_Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Abstract_Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
-- type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
Rename Abstract_Permission into Permission
|
Rename Abstract_Permission into Permission
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
663861e9b253a8efef23f721a63e0874ab08d4aa
|
src/util-streams-buffered.ads
|
src/util-streams-buffered.ads
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2013, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
package Util.Streams.Buffered is
pragma Preelaborate;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- -----------------------
-- Output buffer stream
-- -----------------------
-- The <b>Output_Buffer_Stream</b> is an output stream which uses
-- an intermediate buffer to write the data.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the output buffer stream.
type Output_Buffer_Stream is limited new Output_Stream with private;
-- Initialize the stream to write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : in Output_Stream_Access;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Buffer_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Output_Buffer_Stream);
-- Get the number of element in the stream.
function Get_Size (Stream : in Output_Buffer_Stream) return Natural;
type Input_Buffer_Stream is limited new Input_Stream with private;
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String);
-- Initialize the stream to read the given streams.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : in Input_Stream_Access;
Size : in Positive);
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Input_Buffer_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean;
private
use Ada.Streams;
type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : Output_Stream_Access := null;
No_Flush : Boolean := False;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Output_Buffer_Stream);
type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The input stream to use to fill the buffer.
Input : Input_Stream_Access := null;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Release the buffer.
overriding
procedure Finalize (Object : in out Input_Buffer_Stream);
end Util.Streams.Buffered;
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2013, 2015, 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.Strings.Unbounded;
with Ada.Finalization;
package Util.Streams.Buffered is
pragma Preelaborate;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- -----------------------
-- Output buffer stream
-- -----------------------
-- The <b>Output_Buffer_Stream</b> is an output stream which uses
-- an intermediate buffer to write the data.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the output buffer stream.
type Output_Buffer_Stream is limited new Output_Stream with private;
-- Initialize the stream to write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : in Output_Stream_Access;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Buffer_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Output_Buffer_Stream);
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Get the number of element in the stream.
function Get_Size (Stream : in Output_Buffer_Stream) return Natural;
type Input_Buffer_Stream is limited new Input_Stream with private;
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String);
-- Initialize the stream to read the given streams.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : in Input_Stream_Access;
Size : in Positive);
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Input_Buffer_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean;
private
use Ada.Streams;
type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : Output_Stream_Access := null;
No_Flush : Boolean := False;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Output_Buffer_Stream);
type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The input stream to use to fill the buffer.
Input : Input_Stream_Access := null;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Release the buffer.
overriding
procedure Finalize (Object : in out Input_Buffer_Stream);
end Util.Streams.Buffered;
|
Declare a Flush procedure that allows to flush the output buffer into an array passed as parameter
|
Declare a Flush procedure that allows to flush the output buffer into an array passed as parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
5d65d7307efaed789e072377dc639dc358e5c6f0
|
awa/src/awa-services-filters.adb
|
awa/src/awa-services-filters.adb
|
-----------------------------------------------------------------------
-- awa-services-filters -- Setup service context in request processing flow
-- 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 AWA.Services.Contexts;
with AWA.Applications;
with AWA.Users.Principals;
with ASF.Principals;
with ASF.Sessions;
with Util.Beans.Objects;
package body AWA.Services.Filters is
-- ------------------------------
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- Before passing the control to the next filter, initialize the service
-- context to give access to the current application, current user and
-- manage possible transaction rollbacks.
-- ------------------------------
procedure Do_Filter (F : in Service_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
pragma Unreferenced (F);
use type ASF.Principals.Principal_Access;
type Context_Type is new AWA.Services.Contexts.Service_Context with null record;
-- Get the attribute registered under the given name in the HTTP session.
overriding
function Get_Session_Attribute (Ctx : in Context_Type;
Name : in String) return Util.Beans.Objects.Object;
-- Set the attribute registered under the given name in the HTTP session.
overriding
procedure Set_Session_Attribute (Ctx : in out Context_Type;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
function Get_Session_Attribute (Ctx : in Context_Type;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Ctx);
begin
return Request.Get_Session.Get_Attribute (Name);
end Get_Session_Attribute;
-- Set the attribute registered under the given name in the HTTP session.
overriding
procedure Set_Session_Attribute (Ctx : in out Context_Type;
Name : in String;
Value : in Util.Beans.Objects.Object) is
S : ASF.Sessions.Session := Request.Get_Session;
begin
S.Set_Attribute (Name, Value);
end Set_Session_Attribute;
App : constant ASF.Servlets.Servlet_Registry_Access
:= ASF.Servlets.Get_Servlet_Context (Chain);
P : constant ASF.Principals.Principal_Access := Request.Get_User_Principal;
Context : aliased Context_Type;
Principal : AWA.Users.Principals.Principal_Access;
Application : AWA.Applications.Application_Access;
begin
-- Get the user
if P /= null and then P.all in AWA.Users.Principals.Principal'Class then
Principal := AWA.Users.Principals.Principal'Class (P.all)'Access;
else
Principal := null;
end if;
-- Get the application
if App.all in AWA.Applications.Application'Class then
Application := AWA.Applications.Application'Class (App.all)'Access;
else
Application := null;
end if;
-- Setup the service context.
Context.Set_Context (Application, Principal);
-- Give the control to the next chain up to the servlet.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
-- By leaving this scope, the active database transactions are rollbacked
-- (finalization of Service_Context)
end Do_Filter;
end AWA.Services.Filters;
|
-----------------------------------------------------------------------
-- awa-services-filters -- Setup service context in request processing flow
-- 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 AWA.Services.Contexts;
with AWA.Applications;
with AWA.Users.Principals;
with ASF.Principals;
with ASF.Sessions;
with Util.Beans.Objects;
package body AWA.Services.Filters is
-- ------------------------------
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- Before passing the control to the next filter, initialize the service
-- context to give access to the current application, current user and
-- manage possible transaction rollbacks.
-- ------------------------------
procedure Do_Filter (F : in Service_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
pragma Unreferenced (F);
use type ASF.Principals.Principal_Access;
type Context_Type is new AWA.Services.Contexts.Service_Context with null record;
-- Get the attribute registered under the given name in the HTTP session.
overriding
function Get_Session_Attribute (Ctx : in Context_Type;
Name : in String) return Util.Beans.Objects.Object;
-- Set the attribute registered under the given name in the HTTP session.
overriding
procedure Set_Session_Attribute (Ctx : in out Context_Type;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
function Get_Session_Attribute (Ctx : in Context_Type;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Ctx);
begin
return Request.Get_Session.Get_Attribute (Name);
end Get_Session_Attribute;
-- Set the attribute registered under the given name in the HTTP session.
overriding
procedure Set_Session_Attribute (Ctx : in out Context_Type;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Ctx);
S : ASF.Sessions.Session := Request.Get_Session;
begin
S.Set_Attribute (Name, Value);
end Set_Session_Attribute;
App : constant ASF.Servlets.Servlet_Registry_Access
:= ASF.Servlets.Get_Servlet_Context (Chain);
P : constant ASF.Principals.Principal_Access := Request.Get_User_Principal;
Context : aliased Context_Type;
Principal : AWA.Users.Principals.Principal_Access;
Application : AWA.Applications.Application_Access;
begin
-- Get the user
if P /= null and then P.all in AWA.Users.Principals.Principal'Class then
Principal := AWA.Users.Principals.Principal'Class (P.all)'Access;
else
Principal := null;
end if;
-- Get the application
if App.all in AWA.Applications.Application'Class then
Application := AWA.Applications.Application'Class (App.all)'Access;
else
Application := null;
end if;
-- Setup the service context.
Context.Set_Context (Application, Principal);
-- Give the control to the next chain up to the servlet.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
-- By leaving this scope, the active database transactions are rollbacked
-- (finalization of Service_Context)
end Do_Filter;
end AWA.Services.Filters;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
08e09ac48e526a8d473794fb1e9f7d52183e6f93
|
tests/natools-smaz-tests.adb
|
tests/natools-smaz-tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Natools.Smaz.Original;
package body Natools.Smaz.Tests is
function Dict_Without_VLV return Dictionary;
function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Dict_Without_VLV return Dictionary is
begin
return Dict : Dictionary := Original.Dictionary do
Dict.Variable_Length_Verbatim := False;
end return;
end Dict_Without_VLV;
function Image (S : Ada.Streams.Stream_Element_Array) return String is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Image;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
begin
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Decompressed);
begin
First_OK := True;
if Buffer /= Compressed then
Test.Fail ("Bad compression of """ & Decompressed & '"');
Test.Info ("Found: " & Image (Buffer));
Test.Info ("Expected:" & Image (Compressed));
declare
Round : constant String := Decompress (Dict, Buffer);
begin
if Round /= Decompressed then
Test.Info ("Roundtrip failed, got: """ & Round & '"');
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of """ & Decompressed & '"');
end if;
Test.Report_Exception (Error, NT.Fail);
end;
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant String := Decompress (Dict, Compressed);
begin
First_OK := True;
if Buffer /= Decompressed then
Test.Fail ("Bad decompression of " & Image (Compressed));
Test.Info ("Found: """ & Buffer & '"');
Test.Info ("Expected:""" & Decompressed & '"');
declare
Round : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Buffer);
begin
if Round /= Compressed then
Test.Info ("Roundtrip failed, got: " & Image (Round));
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of " & Image (Compressed));
end if;
Test.Report_Exception (Error, NT.Fail);
end;
end Roundtrip_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Sample_Strings (Report);
Sample_Strings_Without_VLV (Report);
end All_Tests;
----------------------
-- Individual Tests --
----------------------
procedure Sample_Strings (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109,
112, 108, 51, 51, 51));
Roundtrip_Test (Test, Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
Roundtrip_Test (Test, Original.Dictionary,
": : : :",
(255, 6, 58, 32, 58, 32, 58, 32, 58));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings;
procedure Sample_Strings_Without_VLV (Report : in out NT.Reporter'Class) is
Test : NT.Test
:= Report.Item ("Roundtrip on sample strings without VLV");
Dict : constant Dictionary := Dict_Without_VLV;
begin
Roundtrip_Test (Test, Dict,
"This is a small string",
(255, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Dict,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Dict,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Dict,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 254, 48, 48, 24, 204, 255, 69, 250, 4, 45,
60, 22, 254, 51, 51, 255, 51));
Roundtrip_Test (Test, Dict,
"Smaz is a simple compression library",
(255, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Dict,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(255, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Dict,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 255,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Dict,
"1000 numbers 2000 will 10 20 30 compress very little",
(254, 49, 48, 254, 48, 48, 236, 38, 45, 92, 221, 0, 254, 50, 48,
254, 48, 48, 243, 152, 0, 254, 49, 48, 0, 254, 50, 48, 0, 254, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
Roundtrip_Test (Test, Dict,
": : : :",
(254, 58, 32, 254, 58, 32, 254, 58, 32, 255, 58));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings_Without_VLV;
end Natools.Smaz.Tests;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Natools.Smaz.Original;
package body Natools.Smaz.Tests is
function Dict_Without_VLV return Dictionary;
function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Dict_Without_VLV return Dictionary is
begin
return Dict : Dictionary := Original.Dictionary do
Dict.Variable_Length_Verbatim := False;
end return;
end Dict_Without_VLV;
function Image (S : Ada.Streams.Stream_Element_Array) return String is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Image;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
begin
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Decompressed);
begin
First_OK := True;
if Buffer /= Compressed then
Test.Fail ("Bad compression of """ & Decompressed & '"');
Test.Info ("Found: " & Image (Buffer));
Test.Info ("Expected:" & Image (Compressed));
declare
Round : constant String := Decompress (Dict, Buffer);
begin
if Round /= Decompressed then
Test.Info ("Roundtrip failed, got: """ & Round & '"');
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of """ & Decompressed & '"');
end if;
Test.Report_Exception (Error, NT.Fail);
end;
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant String := Decompress (Dict, Compressed);
begin
First_OK := True;
if Buffer /= Decompressed then
Test.Fail ("Bad decompression of " & Image (Compressed));
Test.Info ("Found: """ & Buffer & '"');
Test.Info ("Expected:""" & Decompressed & '"');
declare
Round : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Buffer);
begin
if Round /= Compressed then
Test.Info ("Roundtrip failed, got: " & Image (Round));
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of " & Image (Compressed));
end if;
Test.Report_Exception (Error, NT.Fail);
end;
end Roundtrip_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Sample_Strings (Report);
Sample_Strings_Without_VLV (Report);
end All_Tests;
----------------------
-- Individual Tests --
----------------------
procedure Sample_Strings (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109,
112, 108, 51, 51, 51));
Roundtrip_Test (Test, Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
Roundtrip_Test (Test, Original.Dictionary,
": : : :",
(255, 6, 58, 32, 58, 32, 58, 32, 58));
Roundtrip_Test (Test, Original.Dictionary,
(1 .. 300 => ':'),
(1 .. 2 => 255, 3 .. 258 => 58,
259 => 255, 260 => 43, 261 .. 304 => 58));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings;
procedure Sample_Strings_Without_VLV (Report : in out NT.Reporter'Class) is
Test : NT.Test
:= Report.Item ("Roundtrip on sample strings without VLV");
Dict : constant Dictionary := Dict_Without_VLV;
begin
Roundtrip_Test (Test, Dict,
"This is a small string",
(255, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Dict,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Dict,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Dict,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 254, 48, 48, 24, 204, 255, 69, 250, 4, 45,
60, 22, 254, 51, 51, 255, 51));
Roundtrip_Test (Test, Dict,
"Smaz is a simple compression library",
(255, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Dict,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(255, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Dict,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 255,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Dict,
"1000 numbers 2000 will 10 20 30 compress very little",
(254, 49, 48, 254, 48, 48, 236, 38, 45, 92, 221, 0, 254, 50, 48,
254, 48, 48, 243, 152, 0, 254, 49, 48, 0, 254, 50, 48, 0, 254, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
Roundtrip_Test (Test, Dict,
": : : :",
(254, 58, 32, 254, 58, 32, 254, 58, 32, 255, 58));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings_Without_VLV;
end Natools.Smaz.Tests;
|
add a test of multi-block verbatim sequence
|
smaz-tests: add a test of multi-block verbatim sequence
|
Ada
|
isc
|
faelys/natools
|
30d4f96fbd78b1b14a60f6c730c930ea8bead712
|
src/babel-base-text.ads
|
src/babel-base-text.ads
|
-----------------------------------------------------------------------
-- babel-base -- Database for files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Babel.Files.Sets;
with Babel.Files.Lifecycles;
package Babel.Base.Text is
type Text_Database is new Database with private;
-- Insert the file in the database.
overriding
procedure Insert (Into : in out Text_Database;
File : in Babel.Files.File_Type);
overriding
procedure Iterate (From : in Text_Database;
Process : not null access procedure (File : in Babel.Files.File_Type));
--
-- -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item.
-- procedure On_Create (Instance : in Text_Database;
-- Item : in Babel.Files.File_Type);
--
-- -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item.
-- procedure On_Update (Instance : in Text_Database;
-- Item : in Babel.Files.File_Type);
--
-- -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item.
-- procedure On_Delete (Instance : in Text_Database;
-- Item : in Babel.Files.File_Type);
-- Write the SHA1 checksum for the files stored in the map.
-- ------------------------------
procedure Save (Database : in Text_Database;
Path : in String);
private
type Text_Database is new Database with record
Files : Babel.Files.Sets.File_Set;
end record;
end Babel.Base.Text;
|
-----------------------------------------------------------------------
-- babel-base -- Database for files
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Babel.Files.Sets;
with Babel.Files.Lifecycles;
package Babel.Base.Text is
type Text_Database is new Database with private;
-- Insert the file in the database.
overriding
procedure Insert (Into : in out Text_Database;
File : in Babel.Files.File_Type);
overriding
procedure Iterate (From : in Text_Database;
Process : not null access procedure (File : in Babel.Files.File_Type));
-- Save the database file description in the file.
procedure Save (Database : in Text_Database;
Path : in String);
-- Load the database file description from the file.
procedure Load (Database : in out Text_Database;
Path : in String);
private
type Text_Database is new Database with record
Files : Babel.Files.Sets.File_Set;
end record;
end Babel.Base.Text;
|
Declare the Load procedure
|
Declare the Load procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
ea95b4f0e9c882d40de49d1b184c42a3d41a5f75
|
src/gl/interface/gl-pixels-extensions.ads
|
src/gl/interface/gl-pixels-extensions.ads
|
-- Copyright (c) 2018 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.Unchecked_Conversion;
package GL.Pixels.Extensions is
pragma Preelaborate;
subtype Floating_Point_Format is Format range Red .. RG;
subtype Integer_Format is Format range RG_Integer .. BGRA_Integer
with Static_Predicate => Integer_Format /= Depth_Stencil;
-----------------------------------------------------------------------------
subtype Non_Packed_Data_Type is Data_Type range Byte .. Half_Float;
subtype Packed_Data_Type is Data_Type
range Unsigned_Byte_3_3_2 .. Float_32_Unsigned_Int_24_8_Rev;
subtype Floating_Point_Data_Type is Data_Type
with Static_Predicate => Floating_Point_Data_Type in
Half_Float | Float | Unsigned_Int_10F_11F_11F_Rev | Unsigned_Int_5_9_9_9_Rev;
-----------------------------------------------------------------------------
function Compatible
(Format : Pixels.Format;
Data_Type : Pixels.Data_Type) return Boolean
is (not (Format in Integer_Format and Data_Type in Floating_Point_Data_Type));
-- Floating point types are incompatible with integer formats according
-- to table 8.2 of the OpenGL specification
function Components (Format : Pixels.Format) return Component_Count is
(case Format is
when Red | Green | Blue | Red_Integer | Green_Integer | Blue_Integer => 1,
when RG | RG_Integer => 2,
when RGB | BGR | RGB_Integer | BGR_Integer => 3,
when RGBA | BGRA | RGBA_Integer | BGRA_Integer => 4,
when others => raise Constraint_Error);
function Bytes (Data_Type : Non_Packed_Data_Type) return Byte_Count is
(case Data_Type is
when Byte | Unsigned_Byte => 1,
when Short | Unsigned_Short | Half_Float => 2,
when Int | Unsigned_Int | Float => 4);
function Byte_Alignment (Value : Alignment) return Byte_Count;
-----------------------------------------------------------------------------
subtype Compressed_Byte_Count is Types.Int range 8 .. 16
with Static_Predicate => Compressed_Byte_Count in 8 | 16;
function Block_Bytes (Format : Pixels.Compressed_Format) return Compressed_Byte_Count is
(Case Format is
-- RGTC
when Compressed_Red_RGTC1 => 8,
when Compressed_Signed_Red_RGTC1 => 8,
when Compressed_RG_RGTC2 => 16,
when Compressed_Signed_RG_RGTC2 => 16,
-- BPTC
when Compressed_RGBA_BPTC_Unorm => 16,
when Compressed_SRGB_Alpha_BPTC_UNorm => 16,
when Compressed_RGB_BPTC_Signed_Float => 16,
when Compressed_RGB_BPTC_Unsigned_Float => 16,
-- EAC / ETC
when Compressed_R11_EAC => 8,
when Compressed_Signed_R11_EAC => 8,
when Compressed_RG11_EAC => 16,
when Compressed_Signed_RG11_EAC => 16,
when Compressed_RGB8_ETC2 => 8,
when Compressed_SRGB8_ETC2 => 8,
when Compressed_RGB8_Punchthrough_Alpha1_ETC2 => 8,
when Compressed_SRGB8_Punchthrough_Alpha1_ETC2 => 8,
when Compressed_RGBA8_ETC2_EAC => 16,
when Compressed_SRGB8_Alpha8_ETC2_EAC => 16);
private
function Convert is new Ada.Unchecked_Conversion
(Source => Alignment, Target => Types.Int);
function Byte_Alignment (Value : Alignment) return Byte_Count is
(Convert (Value));
end GL.Pixels.Extensions;
|
-- Copyright (c) 2018 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.Unchecked_Conversion;
package GL.Pixels.Extensions is
pragma Preelaborate;
subtype Floating_Point_Format is Format range Red .. RG;
subtype Integer_Format is Format range RG_Integer .. BGRA_Integer
with Static_Predicate => Integer_Format /= Depth_Stencil;
-----------------------------------------------------------------------------
subtype Non_Packed_Data_Type is Data_Type range Byte .. Half_Float;
subtype Packed_Data_Type is Data_Type
range Unsigned_Byte_3_3_2 .. Float_32_Unsigned_Int_24_8_Rev;
subtype Floating_Point_Data_Type is Data_Type
with Static_Predicate => Floating_Point_Data_Type in
Half_Float | Float | Unsigned_Int_10F_11F_11F_Rev | Unsigned_Int_5_9_9_9_Rev;
-----------------------------------------------------------------------------
function Compatible
(Format : Pixels.Format;
Data_Type : Pixels.Data_Type) return Boolean
is (not (Format in Integer_Format and Data_Type in Floating_Point_Data_Type));
-- Floating point types are incompatible with integer formats according
-- to table 8.2 of the OpenGL specification
function Components (Format : Pixels.Format) return Component_Count is
(case Format is
when Red | Green | Blue | Red_Integer | Green_Integer | Blue_Integer => 1,
when RG | RG_Integer => 2,
when RGB | BGR | RGB_Integer | BGR_Integer => 3,
when RGBA | BGRA | RGBA_Integer | BGRA_Integer => 4,
when others => raise Constraint_Error);
function Bytes (Data_Type : Non_Packed_Data_Type) return Byte_Count is
(case Data_Type is
when Byte | Unsigned_Byte => 1,
when Short | Unsigned_Short | Half_Float => 2,
when Int | Unsigned_Int | Float => 4);
function Byte_Alignment (Value : Alignment) return Byte_Count;
-----------------------------------------------------------------------------
subtype Compressed_Byte_Count is Types.Int range 8 .. 16
with Static_Predicate => Compressed_Byte_Count in 8 | 16;
function Block_Bytes (Format : Pixels.Compressed_Format) return Compressed_Byte_Count is
(case Format is
-- RGTC
when Compressed_Red_RGTC1 => 8,
when Compressed_Signed_Red_RGTC1 => 8,
when Compressed_RG_RGTC2 => 16,
when Compressed_Signed_RG_RGTC2 => 16,
-- BPTC
when Compressed_RGBA_BPTC_Unorm => 16,
when Compressed_SRGB_Alpha_BPTC_UNorm => 16,
when Compressed_RGB_BPTC_Signed_Float => 16,
when Compressed_RGB_BPTC_Unsigned_Float => 16,
-- EAC / ETC
when Compressed_R11_EAC => 8,
when Compressed_Signed_R11_EAC => 8,
when Compressed_RG11_EAC => 16,
when Compressed_Signed_RG11_EAC => 16,
when Compressed_RGB8_ETC2 => 8,
when Compressed_SRGB8_ETC2 => 8,
when Compressed_RGB8_Punchthrough_Alpha1_ETC2 => 8,
when Compressed_SRGB8_Punchthrough_Alpha1_ETC2 => 8,
when Compressed_RGBA8_ETC2_EAC => 16,
when Compressed_SRGB8_Alpha8_ETC2_EAC => 16);
private
function Convert is new Ada.Unchecked_Conversion
(Source => Alignment, Target => Types.Int);
function Byte_Alignment (Value : Alignment) return Byte_Count is
(Convert (Value));
end GL.Pixels.Extensions;
|
Fix style warning
|
Fix style warning
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
b5d6ef9981dd6bf3a7b2d2b44ccf9980fd5b7fd9
|
mat/src/mat-formats.adb
|
mat/src/mat-formats.adb
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : constant Boolean := True;
Hex_Length : Positive := 16;
Conversion : constant String (1 .. 10) := "0123456789";
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String;
-- Format a short description of a malloc event.
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- Format a short description of a realloc event.
function Event_Realloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- Format a short description of a free event.
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- ------------------------------
-- Set the size of a target address to format them.
-- ------------------------------
procedure Set_Address_Size (Size : in Positive) is
begin
Hex_Length := Size;
end Set_Address_Size;
-- ------------------------------
-- Format the PID into a string.
-- ------------------------------
function Pid (Value : in MAT.Types.Target_Process_Ref) return String is
begin
return Util.Strings.Image (Natural (Value));
end Pid;
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value, Hex_Length);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the memory growth size into a string.
-- ------------------------------
function Size (Alloced : in MAT.Types.Target_Size;
Freed : in MAT.Types.Target_Size) return String is
use type MAT.Types.Target_Size;
begin
if Alloced > Freed then
return "+" & Size (Alloced - Freed);
elsif Alloced < Freed then
return "-" & Size (Freed - Alloced);
else
return "=" & Size (Alloced);
end if;
end Size;
-- ------------------------------
-- Format the time relative to the start time.
-- ------------------------------
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : constant Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- Format a file, line, function information into a string.
-- ------------------------------
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
-- ------------------------------
-- Format an event range description.
-- ------------------------------
function Event (First : in MAT.Events.Target_Event_Type;
Last : in MAT.Events.Target_Event_Type) return String is
use type MAT.Events.Event_Id_Type;
Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id);
Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id);
begin
if First.Id = Last.Id then
return Id1 (Id1'First + 1 .. Id1'Last);
else
return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last);
end if;
end Event;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Mode : in Format_Type := NORMAL) return String is
use type MAT.Types.Target_Addr;
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
if Mode = BRIEF then
return "malloc";
else
return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr);
end if;
when MAT.Events.MSG_REALLOC =>
if Mode = BRIEF then
if Item.Old_Addr = 0 then
return "realloc";
else
return "realloc";
end if;
else
if Item.Old_Addr = 0 then
return "realloc(0," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
else
return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
end if;
end if;
when MAT.Events.MSG_FREE =>
if Mode = BRIEF then
return "free";
else
return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size);
end if;
when MAT.Events.MSG_BEGIN =>
return "begin";
when MAT.Events.MSG_END =>
return "end";
when MAT.Events.MSG_LIBRARY =>
return "library";
end case;
end Event;
-- ------------------------------
-- Format a short description of a malloc event.
-- ------------------------------
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Free_Event : MAT.Events.Target_Event_Type;
begin
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
;
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes allocated (never freed)";
end Event_Malloc;
-- ------------------------------
-- Format a short description of a realloc event.
-- ------------------------------
function Event_Realloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
use type MAT.Events.Event_Id_Type;
Free_Event : MAT.Events.Target_Event_Type;
begin
if Item.Next_Id = 0 and Item.Prev_Id = 0 then
return Size (Item.Size) & " bytes reallocated after " & Duration (Item.Time - Start_Time)
& " (never freed)";
end if;
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes reallocated after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
& " " & Size (Item.Size, Item.Old_Size) & " bytes";
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes reallocated after " & Duration (Item.Time - Start_Time)
& " (never freed) " & Size (Item.Size, Item.Old_Size) & " bytes";
end Event_Realloc;
-- ------------------------------
-- Format a short description of a free event.
-- ------------------------------
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Alloc_Event : MAT.Events.Target_Event_Type;
begin
Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_MALLOC);
return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time)
& ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Alloc_Event.Id);
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes freed";
end Event_Free;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.MSG_REALLOC =>
return Event_Realloc (Item, Related, Start_Time);
when MAT.Events.MSG_FREE =>
return Event_Free (Item, Related, Start_Time);
when MAT.Events.MSG_BEGIN =>
return "Begin event";
when MAT.Events.MSG_END =>
return "End event";
when MAT.Events.MSG_LIBRARY =>
return "Library information event";
end case;
end Event;
-- ------------------------------
-- Format the difference between two event IDs (offset).
-- ------------------------------
function Offset (First : in MAT.Events.Event_Id_Type;
Second : in MAT.Events.Event_Id_Type) return String is
use type MAT.Events.Event_Id_Type;
begin
if First = Second or First = 0 or Second = 0 then
return "";
elsif First > Second then
return "+" & Util.Strings.Image (Natural (First - Second));
else
return "-" & Util.Strings.Image (Natural (Second - First));
end if;
end Offset;
-- ------------------------------
-- Format a short description of the memory allocation slot.
-- ------------------------------
function Slot (Value : in MAT.Types.Target_Addr;
Item : in MAT.Memory.Allocation;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
return Addr (Value) & " is " & Size (Item.Size)
& " bytes allocated after " & Duration (Item.Time - Start_Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Item.Event);
end Slot;
end MAT.Formats;
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : constant Boolean := True;
Hex_Length : Positive := 16;
Conversion : constant String (1 .. 10) := "0123456789";
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String;
-- Format a short description of a malloc event.
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- Format a short description of a realloc event.
function Event_Realloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- Format a short description of a free event.
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- ------------------------------
-- Set the size of a target address to format them.
-- ------------------------------
procedure Set_Address_Size (Size : in Positive) is
begin
Hex_Length := Size;
end Set_Address_Size;
-- ------------------------------
-- Format the PID into a string.
-- ------------------------------
function Pid (Value : in MAT.Types.Target_Process_Ref) return String is
begin
return Util.Strings.Image (Natural (Value));
end Pid;
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value, Hex_Length);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the memory growth size into a string.
-- ------------------------------
function Size (Alloced : in MAT.Types.Target_Size;
Freed : in MAT.Types.Target_Size) return String is
use type MAT.Types.Target_Size;
begin
if Alloced > Freed then
return "+" & Size (Alloced - Freed);
elsif Alloced < Freed then
return "-" & Size (Freed - Alloced);
else
return "=" & Size (Alloced);
end if;
end Size;
-- ------------------------------
-- Format the time relative to the start time.
-- ------------------------------
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : constant Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- Format a file, line, function information into a string.
-- ------------------------------
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
-- ------------------------------
-- Format an event range description.
-- ------------------------------
function Event (First : in MAT.Events.Target_Event_Type;
Last : in MAT.Events.Target_Event_Type) return String is
use type MAT.Events.Event_Id_Type;
Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id);
Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id);
begin
if First.Id = Last.Id then
return Id1 (Id1'First + 1 .. Id1'Last);
else
return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last);
end if;
end Event;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Mode : in Format_Type := NORMAL) return String is
use type MAT.Types.Target_Addr;
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
if Mode = BRIEF then
return "malloc";
else
return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr);
end if;
when MAT.Events.MSG_REALLOC =>
if Mode = BRIEF then
if Item.Old_Addr = 0 then
return "realloc";
else
return "realloc";
end if;
else
if Item.Old_Addr = 0 then
return "realloc(0," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
else
return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
end if;
end if;
when MAT.Events.MSG_FREE =>
if Mode = BRIEF then
return "free";
else
return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size);
end if;
when MAT.Events.MSG_BEGIN =>
return "begin";
when MAT.Events.MSG_END =>
return "end";
when MAT.Events.MSG_LIBRARY =>
return "library";
end case;
end Event;
-- ------------------------------
-- Format a short description of a malloc event.
-- ------------------------------
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Free_Event : MAT.Events.Target_Event_Type;
Slot_Addr : constant String := Addr (Item.Addr);
begin
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes allocated at "
& Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
;
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes allocated at " & Slot_Addr & " (never freed)";
end Event_Malloc;
-- ------------------------------
-- Format a short description of a realloc event.
-- ------------------------------
function Event_Realloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
use type MAT.Events.Event_Id_Type;
Free_Event : MAT.Events.Target_Event_Type;
Slot_Addr : constant String := Addr (Item.Addr);
begin
if Item.Next_Id = 0 and Item.Prev_Id = 0 then
return Size (Item.Size) & " bytes reallocated at " & Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& " (never freed)";
end if;
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes reallocated at " & Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
& " " & Size (Item.Size, Item.Old_Size) & " bytes";
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes reallocated at " & Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& " (never freed) " & Size (Item.Size, Item.Old_Size) & " bytes";
end Event_Realloc;
-- ------------------------------
-- Format a short description of a free event.
-- ------------------------------
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Alloc_Event : MAT.Events.Target_Event_Type;
Slot_Addr : constant String := Addr (Item.Addr);
begin
Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_MALLOC);
return Size (Alloc_Event.Size) & " bytes freed at " & Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Alloc_Event.Id);
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes freed at " & Slot_Addr;
end Event_Free;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.MSG_REALLOC =>
return Event_Realloc (Item, Related, Start_Time);
when MAT.Events.MSG_FREE =>
return Event_Free (Item, Related, Start_Time);
when MAT.Events.MSG_BEGIN =>
return "Begin event";
when MAT.Events.MSG_END =>
return "End event";
when MAT.Events.MSG_LIBRARY =>
return "Library information event";
end case;
end Event;
-- ------------------------------
-- Format the difference between two event IDs (offset).
-- ------------------------------
function Offset (First : in MAT.Events.Event_Id_Type;
Second : in MAT.Events.Event_Id_Type) return String is
use type MAT.Events.Event_Id_Type;
begin
if First = Second or First = 0 or Second = 0 then
return "";
elsif First > Second then
return "+" & Util.Strings.Image (Natural (First - Second));
else
return "-" & Util.Strings.Image (Natural (Second - First));
end if;
end Offset;
-- ------------------------------
-- Format a short description of the memory allocation slot.
-- ------------------------------
function Slot (Value : in MAT.Types.Target_Addr;
Item : in MAT.Memory.Allocation;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
return Addr (Value) & " is " & Size (Item.Size)
& " bytes allocated after " & Duration (Item.Time - Start_Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Item.Event);
end Slot;
end MAT.Formats;
|
Update to print the slot address in the event description
|
Update to print the slot address in the event description
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f65537f50e658c7a3bf476879ec857d63571b5a2
|
asfunit/asf-tests.adb
|
asfunit/asf-tests.adb
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Regpat;
with Ada.Strings.Unbounded;
with Util.Files;
with Util.Log.Loggers;
with ASF.Streams;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Servlets.Measures;
with ASF.Responses;
with ASF.Responses.Tools;
with ASF.Filters.Dump;
package body ASF.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Tests");
CONTEXT_PATH : constant String := "/asfunit";
Server : access ASF.Server.Container;
App : ASF.Applications.Main.Application_Access := null;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- Save the response headers and content in a file
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response);
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
begin
if Application /= null then
App := Application;
else
App := new ASF.Applications.Main.Application;
end if;
Server := new ASF.Server.Container;
Server.Register_Application (CONTEXT_PATH, App.all'Access);
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "files", Server => Files'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
App.Add_Servlet (Name => "measures", Server => Measures'Access);
App.Add_Filter (Name => "dump", Filter => Dump'Access);
App.Add_Filter (Name => "measures", Filter => Measures'Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.properties");
App.Add_Mapping (Name => "files", Pattern => "*.xhtml");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
App.Add_Mapping (Name => "measures", Pattern => "stats.xml");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*");
end Initialize;
-- ------------------------------
-- Get the server
-- ------------------------------
function Get_Server return access ASF.Server.Container is
begin
return Server;
end Get_Server;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Save the response headers and content in a file
-- ------------------------------
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response) is
use ASF.Responses;
Info : constant String := Tools.To_String (Reply => Response,
Html => False,
Print_Headers => True);
Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result");
Content : Unbounded_String;
Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Response.Read_Content (Content);
Stream.Write (Content);
Insert (Content, 1, Info);
Util.Files.Write_File (Result_Path & "/" & Name, Content);
end Save_Response;
-- ------------------------------
-- Simulate a raw request. The URI and method must have been set on the Request object.
-- ------------------------------
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response) is
begin
-- For the purpose of writing tests, clear the buffer before invoking the service.
Response.Clear;
Server.Service (Request => Request,
Response => Response);
end Do_Req;
-- ------------------------------
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "GET");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Get;
-- ------------------------------
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "POST");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Post;
-- ------------------------------
-- Check that the response body contains the string
-- ------------------------------
procedure Assert_Contains (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Index (Content, Value) > 0,
Message => Message & ": value '" & Value & "' not found",
Source => Source,
Line => Line);
end Assert_Contains;
-- ------------------------------
-- Check that the response body matches the regular expression
-- ------------------------------
procedure Assert_Matches (T : in Util.Tests.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
use GNAT.Regpat;
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
Regexp : constant Pattern_Matcher := Compile (Expression => Pattern,
Flags => Multiple_Lines);
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Match (Regexp, To_String (Content)),
Message => Message & ": does not match '" & Pattern & "'",
Source => Source,
Line => Line);
end Assert_Matches;
-- ------------------------------
-- Check that the response body is a redirect to the given URI.
-- ------------------------------
procedure Assert_Redirect (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
begin
Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status,
"Invalid response", Source, Line);
Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"),
Message & ": missing Location",
Source, Line);
end Assert_Redirect;
end ASF.Tests;
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Regpat;
with Ada.Strings.Unbounded;
with Util.Files;
with ASF.Streams;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Servlets.Measures;
with ASF.Responses;
with ASF.Responses.Tools;
with ASF.Filters.Dump;
package body ASF.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
Server : access ASF.Server.Container;
App : ASF.Applications.Main.Application_Access := null;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- Save the response headers and content in a file
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response);
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
begin
if Application /= null then
App := Application;
else
App := new ASF.Applications.Main.Application;
end if;
Server := new ASF.Server.Container;
Server.Register_Application (CONTEXT_PATH, App.all'Access);
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "files", Server => Files'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
App.Add_Servlet (Name => "measures", Server => Measures'Access);
App.Add_Filter (Name => "dump", Filter => Dump'Access);
App.Add_Filter (Name => "measures", Filter => Measures'Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.properties");
App.Add_Mapping (Name => "files", Pattern => "*.xhtml");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
App.Add_Mapping (Name => "measures", Pattern => "stats.xml");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*");
end Initialize;
-- ------------------------------
-- Get the server
-- ------------------------------
function Get_Server return access ASF.Server.Container is
begin
return Server;
end Get_Server;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Save the response headers and content in a file
-- ------------------------------
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response) is
use ASF.Responses;
Info : constant String := Tools.To_String (Reply => Response,
Html => False,
Print_Headers => True);
Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result");
Content : Unbounded_String;
Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Response.Read_Content (Content);
Stream.Write (Content);
Insert (Content, 1, Info);
Util.Files.Write_File (Result_Path & "/" & Name, Content);
end Save_Response;
-- ------------------------------
-- Simulate a raw request. The URI and method must have been set on the Request object.
-- ------------------------------
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response) is
begin
-- For the purpose of writing tests, clear the buffer before invoking the service.
Response.Clear;
Server.Service (Request => Request,
Response => Response);
end Do_Req;
-- ------------------------------
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "GET");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Get;
-- ------------------------------
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "POST");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Post;
-- ------------------------------
-- Check that the response body contains the string
-- ------------------------------
procedure Assert_Contains (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Index (Content, Value) > 0,
Message => Message & ": value '" & Value & "' not found",
Source => Source,
Line => Line);
end Assert_Contains;
-- ------------------------------
-- Check that the response body matches the regular expression
-- ------------------------------
procedure Assert_Matches (T : in Util.Tests.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
use GNAT.Regpat;
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
Regexp : constant Pattern_Matcher := Compile (Expression => Pattern,
Flags => Multiple_Lines);
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Match (Regexp, To_String (Content)),
Message => Message & ": does not match '" & Pattern & "'",
Source => Source,
Line => Line);
end Assert_Matches;
-- ------------------------------
-- Check that the response body is a redirect to the given URI.
-- ------------------------------
procedure Assert_Redirect (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
begin
Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status,
"Invalid response", Source, Line);
Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"),
Message & ": missing Location",
Source, Line);
end Assert_Redirect;
end ASF.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
dc81de93fa086104f24d7e883c1f6b79e1598741
|
asfunit/asf-tests.ads
|
asfunit/asf-tests.ads
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- 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.Properties;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Server;
with ASF.Applications.Main;
with Util.Tests;
with EL.Contexts.Default;
with EL.Variables;
with GNAT.Source_Info;
-- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test
-- on top of ASF.
package ASF.Tests is
-- Initialize the asf test framework mockup. If the application is not specified,
-- a default ASF application is created.
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Get the server
function Get_Server return access ASF.Server.Container;
-- Get the test application.
function Get_Application return ASF.Applications.Main.Application_Access;
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "");
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "");
-- Simulate a raw request. The URI and method must have been set on the Request object.
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response);
-- Check that the response body contains the string
procedure Assert_Contains (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
-- Check that the response body matches the regular expression
procedure Assert_Matches (T : in Util.Tests.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Status : in Natural := ASF.Responses.SC_OK;
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
-- Check that the response body is a redirect to the given URI.
procedure Assert_Redirect (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
-- Check that the response contains the given header.
procedure Assert_Header (T : in Util.Tests.Test'Class;
Header : in String;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Status : in Natural := ASF.Responses.SC_OK;
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
type EL_Test is new Util.Tests.Test with record
-- The ELContext, Variables, Resolver, Form area controlled object.
-- Due to AUnit implementation, we cannot store a controlled object in the Test object.
-- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate
-- a test object.
-- The application object is allocated dyanmically by Set_Up.
ELContext : EL.Contexts.Default.Default_Context_Access;
Variables : EL.Variables.Variable_Mapper_Access;
Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access;
end record;
-- Cleanup the test instance.
overriding
procedure Tear_Down (T : in out EL_Test);
-- Setup the test instance.
overriding
procedure Set_Up (T : in out EL_Test);
end ASF.Tests;
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- 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.Properties;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Server;
with ASF.Applications.Main;
with Util.Tests;
with Util.XUnit;
with EL.Contexts.Default;
with EL.Variables;
with GNAT.Source_Info;
-- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test
-- on top of ASF.
package ASF.Tests is
-- Initialize the asf test framework mockup. If the application is not specified,
-- a default ASF application is created.
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Called when the testsuite execution has finished.
procedure Finish (Status : in Util.XUnit.Status);
-- Get the server
function Get_Server return access ASF.Server.Container;
-- Get the test application.
function Get_Application return ASF.Applications.Main.Application_Access;
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "");
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "");
-- Simulate a raw request. The URI and method must have been set on the Request object.
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response);
-- Check that the response body contains the string
procedure Assert_Contains (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
-- Check that the response body matches the regular expression
procedure Assert_Matches (T : in Util.Tests.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Status : in Natural := ASF.Responses.SC_OK;
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
-- Check that the response body is a redirect to the given URI.
procedure Assert_Redirect (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
-- Check that the response contains the given header.
procedure Assert_Header (T : in Util.Tests.Test'Class;
Header : in String;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Status : in Natural := ASF.Responses.SC_OK;
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
type EL_Test is new Util.Tests.Test with record
-- The ELContext, Variables, Resolver, Form area controlled object.
-- Due to AUnit implementation, we cannot store a controlled object in the Test object.
-- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate
-- a test object.
-- The application object is allocated dyanmically by Set_Up.
ELContext : EL.Contexts.Default.Default_Context_Access;
Variables : EL.Variables.Variable_Mapper_Access;
Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access;
end record;
-- Cleanup the test instance.
overriding
procedure Tear_Down (T : in out EL_Test);
-- Setup the test instance.
overriding
procedure Set_Up (T : in out EL_Test);
end ASF.Tests;
|
Declare the Finish procedure to cleanup ASF tests global allocations
|
Declare the Finish procedure to cleanup ASF tests global allocations
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
c98e8256cec36fef573035eaee58dd4aac7aac0f
|
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
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
431d39042769bfb6005b2b9ea0350bb3982b4dac
|
src/gen-commands-layout.ads
|
src/gen-commands-layout.ads
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- Copyright (C) 2011, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Layout is
-- ------------------------------
-- Layout Creation Command
-- ------------------------------
-- This command adds a XHTML layout to the web application.
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Layout;
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- Copyright (C) 2011, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Layout is
-- ------------------------------
-- Layout Creation Command
-- ------------------------------
-- This command adds a XHTML layout to the web application.
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Name : in String;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Layout;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
e7732f50282c45fcac9661ceb46eed045b9abd3a
|
src/orka/interface/orka-ktx.ads
|
src/orka/interface/orka-ktx.ads
|
-- 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.Containers.Indefinite_Hashed_Maps;
with Ada.Streams;
with Ada.Strings.Hash;
with GL.Low_Level.Enums;
with GL.Objects.Textures;
with GL.Pixels;
with GL.Types;
with Orka.Resources;
private package Orka.KTX is
pragma Preelaborate;
package String_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => String,
Element_Type => String,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
use GL.Low_Level.Enums;
use type GL.Types.Size;
type Header (Compressed : Boolean) is record
Kind : GL.Low_Level.Enums.Texture_Kind;
Width : GL.Types.Size;
Height : GL.Types.Size;
Depth : GL.Types.Size;
Array_Elements : GL.Types.Size;
Mipmap_Levels : GL.Objects.Textures.Mipmap_Level;
Bytes_Key_Value : GL.Types.Size;
case Compressed is
when True =>
Compressed_Format : GL.Pixels.Compressed_Format;
when False =>
Data_Type : GL.Pixels.Data_Type;
Format : GL.Pixels.Format;
Internal_Format : GL.Pixels.Internal_Format;
end case;
end record
with Dynamic_Predicate => Header.Width > 0
and (if Header.Depth > 0 then Header.Height > 0)
and (if Header.Height = 0 then Header.Depth = 0)
and (if Header.Compressed then Header.Mipmap_Levels > 0)
and (case Header.Kind is
when Texture_1D | Texture_2D | Texture_3D => Header.Array_Elements = 0,
when Texture_Cube_Map => Header.Array_Elements = 0,
when others => Header.Array_Elements > 0)
and (case Header.Kind is
when Texture_1D | Texture_1D_Array => Header.Height = 0,
when Texture_2D | Texture_2D_Array => Header.Height > 0 and Header.Depth = 0,
when Texture_3D => Header.Depth > 0,
when Texture_Cube_Map => Header.Width = Header.Height and Header.Depth = 0,
when Texture_Cube_Map_Array => Header.Width = Header.Height and Header.Depth = 0,
when others => raise Constraint_Error);
subtype Bytes_Reference is Resources.Byte_Array_Pointers.Constant_Reference;
function Valid_Identifier (Bytes : Bytes_Reference) return Boolean;
function Get_Header (Bytes : Bytes_Reference) return Header;
function Get_Key_Value_Map
(Bytes : Bytes_Reference;
Length : GL.Types.Size) return String_Maps.Map;
function Get_Length
(Bytes : Bytes_Reference;
Offset : Ada.Streams.Stream_Element_Offset) return Natural;
function Get_Data_Offset
(Bytes : Bytes_Reference;
Bytes_Key_Value : GL.Types.Size) return Ada.Streams.Stream_Element_Offset;
Invalid_Enum_Error : exception;
function Create_KTX_Bytes
(KTX_Header : Header;
Data : Bytes_Reference) return Resources.Byte_Array_Pointers.Pointer;
end Orka.KTX;
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Streams;
with Ada.Strings.Hash;
with GL.Low_Level.Enums;
with GL.Objects.Textures;
with GL.Pixels;
with GL.Types;
with Orka.Resources;
private package Orka.KTX is
pragma Preelaborate;
package String_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => String,
Element_Type => String,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
use GL.Low_Level.Enums;
use type GL.Types.Size;
type Header (Compressed : Boolean) is record
Kind : GL.Low_Level.Enums.Texture_Kind;
Width : GL.Types.Size;
Height : GL.Types.Size;
Depth : GL.Types.Size;
Array_Elements : GL.Types.Size;
Mipmap_Levels : GL.Objects.Textures.Mipmap_Level;
Bytes_Key_Value : GL.Types.Size;
case Compressed is
when True =>
Compressed_Format : GL.Pixels.Compressed_Format;
when False =>
Data_Type : GL.Pixels.Data_Type;
Format : GL.Pixels.Format;
Internal_Format : GL.Pixels.Internal_Format;
end case;
end record
with Dynamic_Predicate => Header.Width > 0
and not (Header.Height = 0 and Header.Depth > 0)
and (if Header.Compressed then Header.Mipmap_Levels > 0)
and (case Header.Kind is
when Texture_1D | Texture_2D | Texture_3D => Header.Array_Elements = 0,
when Texture_Cube_Map => Header.Array_Elements = 0,
when others => Header.Array_Elements > 0)
and (case Header.Kind is
when Texture_1D | Texture_1D_Array => Header.Height = 0,
when Texture_2D | Texture_2D_Array => Header.Height > 0 and Header.Depth = 0,
when Texture_3D => Header.Depth > 0,
when Texture_Cube_Map => Header.Width = Header.Height and Header.Depth = 0,
when Texture_Cube_Map_Array => Header.Width = Header.Height and Header.Depth = 0,
when others => raise Constraint_Error);
subtype Bytes_Reference is Resources.Byte_Array_Pointers.Constant_Reference;
function Valid_Identifier (Bytes : Bytes_Reference) return Boolean;
function Get_Header (Bytes : Bytes_Reference) return Header;
function Get_Key_Value_Map
(Bytes : Bytes_Reference;
Length : GL.Types.Size) return String_Maps.Map;
function Get_Length
(Bytes : Bytes_Reference;
Offset : Ada.Streams.Stream_Element_Offset) return Natural;
function Get_Data_Offset
(Bytes : Bytes_Reference;
Bytes_Key_Value : GL.Types.Size) return Ada.Streams.Stream_Element_Offset;
Invalid_Enum_Error : exception;
function Create_KTX_Bytes
(KTX_Header : Header;
Data : Bytes_Reference) return Resources.Byte_Array_Pointers.Pointer;
end Orka.KTX;
|
Simplify Dynamic_Predicate of KTX header a bit
|
orka: Simplify Dynamic_Predicate of KTX header a bit
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
eee980d32a6e91c74b49d3f478bb7c6aa78c964f
|
src/util-encoders-hmac-sha1.adb
|
src/util-encoders-hmac-sha1.adb
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code
-- 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.Encoders.Base16;
with Util.Encoders.Base64;
-- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package body Util.Encoders.HMAC.SHA1 is
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code in binary.
-- ------------------------------
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Hash_Array is
Ctx : Context;
Result : Util.Encoders.SHA1.Hash_Array;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
return Result;
end Sign;
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string.
-- ------------------------------
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Digest is
Ctx : Context;
Result : Util.Encoders.SHA1.Digest;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
return Result;
end Sign;
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
-- ------------------------------
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest is
Ctx : Context;
Result : Util.Encoders.SHA1.Base64_Digest;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish_Base64 (Ctx, Result, URL);
return Result;
end Sign_Base64;
-- ------------------------------
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
-- ------------------------------
procedure Set_Key (E : in out Context;
Key : in String) is
Buf : Ada.Streams.Stream_Element_Array (1 .. Key'Length);
for Buf'Address use Key'Address;
pragma Import (Ada, Buf);
begin
Set_Key (E, Buf);
end Set_Key;
IPAD : constant Ada.Streams.Stream_Element := 16#36#;
OPAD : constant Ada.Streams.Stream_Element := 16#5c#;
-- ------------------------------
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
-- ------------------------------
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array) is
use type Ada.Streams.Stream_Element_Offset;
use type Ada.Streams.Stream_Element;
begin
-- Reduce the key
if Key'Length > 64 then
Util.Encoders.SHA1.Update (E.SHA, Key);
Util.Encoders.SHA1.Finish (E.SHA, E.Key (0 .. 19));
E.Key_Len := 19;
else
E.Key_Len := Key'Length - 1;
E.Key (0 .. E.Key_Len) := Key;
end if;
-- Hash the key in the SHA1 context.
declare
Block : Ada.Streams.Stream_Element_Array (0 .. 63);
begin
for I in 0 .. E.Key_Len loop
Block (I) := IPAD xor E.Key (I);
end loop;
for I in E.Key_Len + 1 .. 63 loop
Block (I) := IPAD;
end loop;
Util.Encoders.SHA1.Update (E.SHA, Block);
end;
end Set_Key;
-- ------------------------------
-- Update the hash with the string.
-- ------------------------------
procedure Update (E : in out Context;
S : in String) is
begin
Util.Encoders.SHA1.Update (E.SHA, S);
end Update;
-- ------------------------------
-- Update the hash with the string.
-- ------------------------------
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array) is
begin
Util.Encoders.SHA1.Update (E.SHA, S);
end Update;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Hash_Array) is
use type Ada.Streams.Stream_Element;
use type Ada.Streams.Stream_Element_Offset;
begin
Util.Encoders.SHA1.Finish (E.SHA, Hash);
-- Hash the key in the SHA1 context.
declare
Block : Ada.Streams.Stream_Element_Array (0 .. 63);
begin
for I in 0 .. E.Key_Len loop
Block (I) := OPAD xor E.Key (I);
end loop;
if E.Key_Len < 63 then
for I in E.Key_Len + 1 .. 63 loop
Block (I) := OPAD;
end loop;
end if;
Util.Encoders.SHA1.Update (E.SHA, Block);
end;
Util.Encoders.SHA1.Update (E.SHA, Hash);
Util.Encoders.SHA1.Finish (E.SHA, Hash);
end Finish;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Digest) is
Buf : Ada.Streams.Stream_Element_Array (1 .. Hash'Length);
for Buf'Address use Hash'Address;
pragma Import (Ada, Buf);
H : Util.Encoders.SHA1.Hash_Array;
B : Util.Encoders.Base16.Encoder;
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
begin
Finish (E, H);
B.Transform (Data => H, Into => Buf, Last => Last, Encoded => Encoded);
end Finish;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
-- ------------------------------
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA1.Base64_Digest;
URL : in Boolean := False) is
Buf : Ada.Streams.Stream_Element_Array (1 .. Hash'Length);
for Buf'Address use Hash'Address;
pragma Import (Ada, Buf);
H : Util.Encoders.SHA1.Hash_Array;
B : Util.Encoders.Base64.Encoder;
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
begin
Finish (E, H);
B.Set_URL_Mode (URL);
B.Transform (Data => H, Into => Buf, Last => Last, Encoded => Encoded);
end Finish_Base64;
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
begin
null;
end Transform;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context) is
begin
null;
end Initialize;
end Util.Encoders.HMAC.SHA1;
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code
-- Copyright (C) 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base16;
with Util.Encoders.Base64;
-- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package body Util.Encoders.HMAC.SHA1 is
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code in binary.
-- ------------------------------
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Hash_Array is
Ctx : Context;
Result : Util.Encoders.SHA1.Hash_Array;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
return Result;
end Sign;
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string.
-- ------------------------------
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA1.Digest is
Ctx : Context;
Result : Util.Encoders.SHA1.Digest;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish (Ctx, Result);
return Result;
end Sign;
-- ------------------------------
-- Sign the data string with the key and return the HMAC-SHA1 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
-- ------------------------------
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest is
Ctx : Context;
Result : Util.Encoders.SHA1.Base64_Digest;
begin
Set_Key (Ctx, Key);
Update (Ctx, Data);
Finish_Base64 (Ctx, Result, URL);
return Result;
end Sign_Base64;
-- ------------------------------
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
-- ------------------------------
procedure Set_Key (E : in out Context;
Key : in String) is
Buf : Ada.Streams.Stream_Element_Array (1 .. Key'Length);
for Buf'Address use Key'Address;
pragma Import (Ada, Buf);
begin
Set_Key (E, Buf);
end Set_Key;
IPAD : constant Ada.Streams.Stream_Element := 16#36#;
OPAD : constant Ada.Streams.Stream_Element := 16#5c#;
-- ------------------------------
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
-- ------------------------------
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array) is
use type Ada.Streams.Stream_Element_Offset;
use type Ada.Streams.Stream_Element;
begin
-- Reduce the key
if Key'Length > 64 then
Util.Encoders.SHA1.Update (E.SHA, Key);
Util.Encoders.SHA1.Finish (E.SHA, E.Key (0 .. 19));
E.Key_Len := 19;
else
E.Key_Len := Key'Length - 1;
E.Key (0 .. E.Key_Len) := Key;
end if;
-- Hash the key in the SHA1 context.
declare
Block : Ada.Streams.Stream_Element_Array (0 .. 63);
begin
for I in 0 .. E.Key_Len loop
Block (I) := IPAD xor E.Key (I);
end loop;
for I in E.Key_Len + 1 .. 63 loop
Block (I) := IPAD;
end loop;
Util.Encoders.SHA1.Update (E.SHA, Block);
end;
end Set_Key;
-- ------------------------------
-- Update the hash with the string.
-- ------------------------------
procedure Update (E : in out Context;
S : in String) is
begin
Util.Encoders.SHA1.Update (E.SHA, S);
end Update;
-- ------------------------------
-- Update the hash with the string.
-- ------------------------------
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array) is
begin
Util.Encoders.SHA1.Update (E.SHA, S);
end Update;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Hash_Array) is
use type Ada.Streams.Stream_Element;
use type Ada.Streams.Stream_Element_Offset;
begin
Util.Encoders.SHA1.Finish (E.SHA, Hash);
-- Hash the key in the SHA1 context.
declare
Block : Ada.Streams.Stream_Element_Array (0 .. 63);
begin
for I in 0 .. E.Key_Len loop
Block (I) := OPAD xor E.Key (I);
end loop;
if E.Key_Len < 63 then
for I in E.Key_Len + 1 .. 63 loop
Block (I) := OPAD;
end loop;
end if;
Util.Encoders.SHA1.Update (E.SHA, Block);
end;
Util.Encoders.SHA1.Update (E.SHA, Hash);
Util.Encoders.SHA1.Finish (E.SHA, Hash);
end Finish;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA1.Digest) is
H : Util.Encoders.SHA1.Hash_Array;
B : Util.Encoders.Base16.Encoder;
begin
Finish (E, H);
B.Convert (H, Hash);
end Finish;
-- ------------------------------
-- Computes the HMAC-SHA1 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
-- ------------------------------
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA1.Base64_Digest;
URL : in Boolean := False) is
H : Util.Encoders.SHA1.Hash_Array;
B : Util.Encoders.Base64.Encoder;
begin
Finish (E, H);
B.Set_URL_Mode (URL);
B.Convert (H, Hash);
end Finish_Base64;
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
begin
null;
end Transform;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context) is
begin
null;
end Initialize;
end Util.Encoders.HMAC.SHA1;
|
Refactor the encoders to use the Convert procedure to simplify the final HMAC-SHA1 conversion
|
Refactor the encoders to use the Convert procedure to simplify the final HMAC-SHA1 conversion
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c55528f31a5fac56697753d11c8faa632e04f8ec
|
src/asf-validators-texts.adb
|
src/asf-validators-texts.adb
|
-----------------------------------------------------------------------
-- asf-validators-texts -- ASF Texts Validators
-- 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.
-----------------------------------------------------------------------
-- The <b>ASF.Validators.Texts</b> defines various text oriented validators.
package body ASF.Validators.Texts is
-- ------------------------------
-- Length_Validator
-- ------------------------------
-- ------------------------------
-- Create a length validator.
-- ------------------------------
function Create_Length_Validator (Minimum : in Natural;
Maximum : in Natural) return Validator_Access is
Result : constant Length_Validator_Access := new Length_Validator;
begin
Result.Minimum := Minimum;
Result.Maximum := Maximum;
return Result.all'Access;
end Create_Length_Validator;
-- ------------------------------
-- Verify that the value's length is between the validator minimum and maximum
-- boundaries.
-- If some error are found, the procedure should create a <b>FacesMessage</b>
-- describing the problem and add that message to the current faces context.
-- The procedure can examine the state and modify the component tree.
-- It must raise the <b>Invalid_Value</b> exception if the value is not valid.
-- ------------------------------
procedure Validate (Valid : in Length_Validator;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Component : in out ASF.Components.Base.UIComponent'Class;
Value : in EL.Objects.Object) is
begin
if EL.Objects.Is_Null (Value) then
return;
end if;
declare
S : constant String := EL.Objects.To_String (Value);
begin
if S'Length > Valid.Maximum then
Component.Add_Message (Name => "validatorMessage",
Default => MAXIMUM_MESSAGE_ID,
Context => Context);
raise Invalid_Value;
end if;
if S'Length < Valid.Minimum then
Component.Add_Message (Name => "validatorMessage",
Default => MINIMUM_MESSAGE_ID,
Context => Context);
raise Invalid_Value;
end if;
end;
end Validate;
end ASF.Validators.Texts;
|
-----------------------------------------------------------------------
-- asf-validators-texts -- ASF Texts Validators
-- 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.Beans.Objects;
-- The <b>ASF.Validators.Texts</b> defines various text oriented validators.
package body ASF.Validators.Texts is
-- ------------------------------
-- Length_Validator
-- ------------------------------
-- ------------------------------
-- Create a length validator.
-- ------------------------------
function Create_Length_Validator (Minimum : in Natural;
Maximum : in Natural) return Validator_Access is
Result : constant Length_Validator_Access := new Length_Validator;
begin
Result.Minimum := Minimum;
Result.Maximum := Maximum;
return Result.all'Access;
end Create_Length_Validator;
-- ------------------------------
-- Verify that the value's length is between the validator minimum and maximum
-- boundaries.
-- If some error are found, the procedure should create a <b>FacesMessage</b>
-- describing the problem and add that message to the current faces context.
-- The procedure can examine the state and modify the component tree.
-- It must raise the <b>Invalid_Value</b> exception if the value is not valid.
-- ------------------------------
procedure Validate (Valid : in Length_Validator;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Component : in out ASF.Components.Base.UIComponent'Class;
Value : in EL.Objects.Object) is
begin
if EL.Objects.Is_Null (Value) then
return;
end if;
declare
S : constant String := EL.Objects.To_String (Value);
begin
if S'Length > Valid.Maximum then
Component.Add_Message (Name => ASF.Components.VALIDATOR_MESSAGE_NAME,
Default => MAXIMUM_MESSAGE_ID,
Arg1 => Util.Beans.Objects.To_Object (Valid.Maximum),
Arg2 => Component.Get_Label (Context),
Context => Context);
raise Invalid_Value;
end if;
if S'Length < Valid.Minimum then
Component.Add_Message (Name => ASF.Components.VALIDATOR_MESSAGE_NAME,
Default => MINIMUM_MESSAGE_ID,
Arg1 => Util.Beans.Objects.To_Object (Valid.Minimum),
Arg2 => Component.Get_Label (Context),
Context => Context);
raise Invalid_Value;
end if;
end;
end Validate;
end ASF.Validators.Texts;
|
Add a message when the validation fails
|
Add a message when the validation fails
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
15592ccd524fe7003ddea8f74285b424cc1f8f66
|
src/gen-commands-plugins.ads
|
src/gen-commands-plugins.ads
|
-----------------------------------------------------------------------
-- gen-commands-plugins -- Plugin creation and management commands for dynamo
-- Copyright (C) 2012, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Plugins is
-- ------------------------------
-- Generator Command
-- ------------------------------
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Plugins;
|
-----------------------------------------------------------------------
-- gen-commands-plugins -- Plugin creation and management commands for dynamo
-- Copyright (C) 2012, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Plugins is
-- ------------------------------
-- Generator Command
-- ------------------------------
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
overriding
procedure Help (Cmd : in out Command;
Name : in String;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Plugins;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
1d468239bf675942848915a72f90520e699e1c3f
|
src/util-concurrent-fifos.adb
|
src/util-concurrent-fifos.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : constant Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
Fix compilation warning reported by gcc 4.7
|
Fix compilation warning reported by gcc 4.7
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b3b5b607d9c3553857d5499221e1d55f9b5ca730
|
src/el-expressions-nodes.ads
|
src/el-expressions-nodes.ads
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Nodes
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The 'ELNode' describes an expression that can later be evaluated
-- on an expression context. Expressions are parsed and translated
-- to a read-only tree.
with EL.Functions;
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Strings.Unbounded;
with Util.Concurrent.Counters;
private package EL.Expressions.Nodes is
use EL.Functions;
use Ada.Strings.Wide_Wide_Unbounded;
use Ada.Strings.Unbounded;
type Reduction;
type ELNode is abstract tagged record
Ref_Counter : Util.Concurrent.Counters.Counter;
end record;
type ELNode_Access is access all ELNode'Class;
type Reduction is record
Node : ELNode_Access;
Value : EL.Objects.Object;
end record;
-- Evaluate a node on a given context.
function Get_Value (Expr : ELNode;
Context : ELContext'Class) return Object is abstract;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
function Reduce (Expr : ELNode;
Context : ELContext'Class) return Reduction is abstract;
-- Delete the expression tree (calls Delete (ELNode_Access) recursively).
procedure Delete (Node : in out ELNode) is abstract;
-- Delete the expression tree. Free the memory allocated by nodes
-- of the expression tree. Clears the node pointer.
procedure Delete (Node : in out ELNode_Access);
-- ------------------------------
-- Unary expression node
-- ------------------------------
type ELUnary is new ELNode with private;
type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS);
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELUnary;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELUnary;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELUnary);
-- ------------------------------
-- Binary expression node
-- ------------------------------
type ELBinary is new ELNode with private;
type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT,
EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD,
EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT);
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELBinary;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELBinary;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELBinary);
-- ------------------------------
-- Ternary expression node
-- ------------------------------
type ELTernary is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELTernary;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELTernary;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELTernary);
-- ------------------------------
-- Variable to be looked at in the expression context
-- ------------------------------
type ELVariable is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELVariable;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELVariable;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELVariable);
-- ------------------------------
-- Value property referring to a variable
-- ------------------------------
type ELValue is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELValue;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELValue;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELValue);
-- ------------------------------
-- Literal object (integer, boolean, float, string)
-- ------------------------------
type ELObject is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELObject;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELObject;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELObject);
-- ------------------------------
-- Function call with up to 4 arguments
-- ------------------------------
type ELFunction is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELFunction;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELFunction;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELFunction);
-- Create constant nodes
function Create_Node (Value : Boolean) return ELNode_Access;
function Create_Node (Value : Long_Long_Integer) return ELNode_Access;
function Create_Node (Value : String) return ELNode_Access;
function Create_Node (Value : Wide_Wide_String) return ELNode_Access;
function Create_Node (Value : Long_Float) return ELNode_Access;
function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access;
function Create_Variable (Name : Unbounded_String) return ELNode_Access;
function Create_Value (Variable : ELNode_Access;
Name : Unbounded_String) return ELNode_Access;
-- Create unary expressions
function Create_Node (Of_Type : Unary_Node;
Expr : ELNode_Access) return ELNode_Access;
-- Create binary expressions
function Create_Node (Of_Type : Binary_Node;
Left : ELNode_Access;
Right : ELNode_Access) return ELNode_Access;
-- Create a ternary expression.
function Create_Node (Cond : ELNode_Access;
Left : ELNode_Access;
Right : ELNode_Access) return ELNode_Access;
-- Create a function call
function Create_Node (Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access) return ELNode_Access;
-- Create a function call
function Create_Node (Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access;
Arg2 : ELNode_Access) return ELNode_Access;
-- Create a function call
function Create_Node (Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access;
Arg2 : ELNode_Access;
Arg3 : ELNode_Access) return ELNode_Access;
-- Create a function call
function Create_Node (Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access;
Arg2 : ELNode_Access;
Arg3 : ELNode_Access;
Arg4 : ELNode_Access) return ELNode_Access;
private
type ELUnary is new ELNode with record
Kind : Unary_Node;
Node : ELNode_Access;
end record;
-- ------------------------------
-- Binary nodes
-- ------------------------------
type ELBinary is new ELNode with record
Kind : Binary_Node;
Left : ELNode_Access;
Right : ELNode_Access;
end record;
-- ------------------------------
-- Ternary expression
-- ------------------------------
type ELTernary is new ELNode with record
Cond : ELNode_Access;
Left : ELNode_Access;
Right : ELNode_Access;
end record;
-- #{bean.name} - Bean name, Bean property
-- #{bean[12]} - Bean name,
-- Variable to be looked at in the expression context
type ELVariable is new ELNode with record
Name : Unbounded_String;
end record;
type ELValue is new ELNode with record
Name : Unbounded_String;
Variable : ELNode_Access;
end record;
-- A literal object (integer, boolean, float, String)
type ELObject is new ELNode with record
Value : Object;
end record;
-- A function call with up to 4 arguments.
type ELFunction is new ELNode with record
Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access;
Arg2 : ELNode_Access;
Arg3 : ELNode_Access;
Arg4 : ELNode_Access;
end record;
end EL.Expressions.Nodes;
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Nodes
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The 'ELNode' describes an expression that can later be evaluated
-- on an expression context. Expressions are parsed and translated
-- to a read-only tree.
with EL.Functions;
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Strings.Unbounded;
with Util.Concurrent.Counters;
private package EL.Expressions.Nodes is
use EL.Functions;
use Ada.Strings.Wide_Wide_Unbounded;
use Ada.Strings.Unbounded;
type Reduction;
type ELNode is abstract tagged limited record
Ref_Counter : Util.Concurrent.Counters.Counter;
end record;
type ELNode_Access is access all ELNode'Class;
type Reduction is record
Node : ELNode_Access;
Value : EL.Objects.Object;
end record;
-- Evaluate a node on a given context.
function Get_Value (Expr : ELNode;
Context : ELContext'Class) return Object is abstract;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
function Reduce (Expr : ELNode;
Context : ELContext'Class) return Reduction is abstract;
-- Delete the expression tree (calls Delete (ELNode_Access) recursively).
procedure Delete (Node : in out ELNode) is abstract;
-- Delete the expression tree. Free the memory allocated by nodes
-- of the expression tree. Clears the node pointer.
procedure Delete (Node : in out ELNode_Access);
-- ------------------------------
-- Unary expression node
-- ------------------------------
type ELUnary is new ELNode with private;
type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS);
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELUnary;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELUnary;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELUnary);
-- ------------------------------
-- Binary expression node
-- ------------------------------
type ELBinary is new ELNode with private;
type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT,
EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD,
EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT);
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELBinary;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELBinary;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELBinary);
-- ------------------------------
-- Ternary expression node
-- ------------------------------
type ELTernary is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELTernary;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELTernary;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELTernary);
-- ------------------------------
-- Variable to be looked at in the expression context
-- ------------------------------
type ELVariable is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELVariable;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELVariable;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELVariable);
-- ------------------------------
-- Value property referring to a variable
-- ------------------------------
type ELValue is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELValue;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELValue;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELValue);
-- ------------------------------
-- Literal object (integer, boolean, float, string)
-- ------------------------------
type ELObject is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELObject;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELObject;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELObject);
-- ------------------------------
-- Function call with up to 4 arguments
-- ------------------------------
type ELFunction is new ELNode with private;
-- Evaluate a node on a given context.
overriding
function Get_Value (Expr : ELFunction;
Context : ELContext'Class) return Object;
-- Reduce the expression by eliminating variables which are known
-- and computing constant expressions. Returns either a new expression
-- tree or a constant value.
overriding
function Reduce (Expr : ELFunction;
Context : ELContext'Class) return Reduction;
overriding
procedure Delete (Node : in out ELFunction);
-- Create constant nodes
function Create_Node (Value : Boolean) return ELNode_Access;
function Create_Node (Value : Long_Long_Integer) return ELNode_Access;
function Create_Node (Value : String) return ELNode_Access;
function Create_Node (Value : Wide_Wide_String) return ELNode_Access;
function Create_Node (Value : Long_Float) return ELNode_Access;
function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access;
function Create_Variable (Name : Unbounded_String) return ELNode_Access;
function Create_Value (Variable : ELNode_Access;
Name : Unbounded_String) return ELNode_Access;
-- Create unary expressions
function Create_Node (Of_Type : Unary_Node;
Expr : ELNode_Access) return ELNode_Access;
-- Create binary expressions
function Create_Node (Of_Type : Binary_Node;
Left : ELNode_Access;
Right : ELNode_Access) return ELNode_Access;
-- Create a ternary expression.
function Create_Node (Cond : ELNode_Access;
Left : ELNode_Access;
Right : ELNode_Access) return ELNode_Access;
-- Create a function call
function Create_Node (Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access) return ELNode_Access;
-- Create a function call
function Create_Node (Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access;
Arg2 : ELNode_Access) return ELNode_Access;
-- Create a function call
function Create_Node (Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access;
Arg2 : ELNode_Access;
Arg3 : ELNode_Access) return ELNode_Access;
-- Create a function call
function Create_Node (Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access;
Arg2 : ELNode_Access;
Arg3 : ELNode_Access;
Arg4 : ELNode_Access) return ELNode_Access;
private
type ELUnary is new ELNode with record
Kind : Unary_Node;
Node : ELNode_Access;
end record;
-- ------------------------------
-- Binary nodes
-- ------------------------------
type ELBinary is new ELNode with record
Kind : Binary_Node;
Left : ELNode_Access;
Right : ELNode_Access;
end record;
-- ------------------------------
-- Ternary expression
-- ------------------------------
type ELTernary is new ELNode with record
Cond : ELNode_Access;
Left : ELNode_Access;
Right : ELNode_Access;
end record;
-- #{bean.name} - Bean name, Bean property
-- #{bean[12]} - Bean name,
-- Variable to be looked at in the expression context
type ELVariable is new ELNode with record
Name : Unbounded_String;
end record;
type ELValue is new ELNode with record
Name : Unbounded_String;
Variable : ELNode_Access;
end record;
-- A literal object (integer, boolean, float, String)
type ELObject is new ELNode with record
Value : Object;
end record;
-- A function call with up to 4 arguments.
type ELFunction is new ELNode with record
Func : EL.Functions.Function_Access;
Arg1 : ELNode_Access;
Arg2 : ELNode_Access;
Arg3 : ELNode_Access;
Arg4 : ELNode_Access;
end record;
end EL.Expressions.Nodes;
|
Use a limited type for ELNode so that we can use the portable concurrent counter implementation
|
Use a limited type for ELNode so that we can use the portable concurrent counter implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
bc4f899fd89708ec4ba061f2d817bddedb9ba50b
|
src/gen-commands-propset.adb
|
src/gen-commands-propset.adb
|
-----------------------------------------------------------------------
-- gen-commands-propset -- Set a property on dynamo project
-- 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 Ada.Text_IO;
package body Gen.Commands.Propset 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;
begin
if Args.Get_Count /= 2 then
Gen.Commands.Usage;
return;
end if;
Generator.Read_Project ("dynamo.xml", True);
Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2));
Generator.Save_Project;
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 ("propset: Set the value of a property in the dynamo project file");
Put_Line ("Usage: propset NAME VALUEE");
New_Line;
end Help;
end Gen.Commands.Propset;
|
-----------------------------------------------------------------------
-- gen-commands-propset -- Set a property on dynamo project
-- 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 Ada.Text_IO;
package body Gen.Commands.Propset 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 (Name);
use Ada.Strings.Unbounded;
begin
if Args.Get_Count /= 2 then
Cmd.Usage;
return;
end if;
Generator.Read_Project ("dynamo.xml", True);
Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2));
Generator.Save_Project;
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 ("propset: Set the value of a property in the dynamo project file");
Put_Line ("Usage: propset NAME VALUEE");
New_Line;
end Help;
end Gen.Commands.Propset;
|
Use the command usage procedure to report the program usage
|
Use the command usage procedure to report the program usage
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
3ca7c7dd0f7545179b76cb2fef1897b61d0e82ce
|
src/security-policies.adb
|
src/security-policies.adb
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Security.Controllers;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Get the policy index.
-- ------------------------------
function Get_Policy_Index (From : in Policy'Class) return Policy_Index is
begin
return From.Index;
end Get_Policy_Index;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
-- ------------------------------
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
exit when Manager.Permissions (I) = null;
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with" clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug
-- but we have to use a temporary variable and do some type conversion...
declare
P : Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end loop;
Free (Manager.Permissions);
end if;
end Finalize;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Security.Controllers;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Get the policy index.
-- ------------------------------
function Get_Policy_Index (From : in Policy'Class) return Policy_Index is
begin
return From.Index;
end Get_Policy_Index;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
-- ------------------------------
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- ------------------------------
-- Create the policy contexts to be associated with the security context.
-- ------------------------------
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access is
begin
return new Policy_Context_Array (1 .. Manager.Max_Policies);
end Create_Policy_Contexts;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
exit when Manager.Permissions (I) = null;
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with" clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug
-- but we have to use a temporary variable and do some type conversion...
declare
P : Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end loop;
Free (Manager.Permissions);
end if;
end Finalize;
end Security.Policies;
|
Implement the Create_Policy_Contexts operation
|
Implement the Create_Policy_Contexts operation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
12a565620a6bdb5bd084b45684b898109693d37d
|
mat/src/mat-readers.adb
|
mat/src/mat-readers.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Events;
with MAT.Types;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
procedure Register_Servant (Adapter : in Manager;
Proxy : in Servant) is
begin
if Proxy.Owner /= null then
raise PROGRAM_ERROR;
end if;
Proxy.Owner := Adapter;
end Register_Servant;
-- ------------------------------
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Attribute_Table_Ptr) is
Handler : Message_Handler;
begin
Handler.For_Servant := Reader;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
procedure Register_Message_Analyzer (Proxy : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Attribute_Table;
Table : out MAT.Events.Attribute_Table_Ptr) is
Handler : Message_Handler := (For_Servant => Proxy, Id => Id);
Adapter : IpcManager := IpcManager_Base (Proxy.Owner.all)'Access;
N : String_Ptr := new String'(Name);
It : Event_Def_AVL.Iterator := Find (adapter.Event_Types, N);
begin
if Is_Done (It) then
return;
end if;
declare
Event_Def : Event_Description_Ptr := Current_Item (It);
Inserted : Boolean;
begin
Insert (T => Adapter.Handlers,
Element => Handler,
The_Key => Event_Def.Id,
Not_Found => Inserted);
Table := new Attribute_Table (1 .. Event_Def.Nb_Attributes);
Table (Table'Range) := Event_Def.Def (Table'Range);
for I in Table'Range loop
Table (I).Ref := 0;
for J in Model'Range loop
if Table (I).Name.all = Model (I).Name.all then
Table (I).Ref := Model (I).Ref;
exit;
end if;
end loop;
end loop;
end;
end Register_Message_Analyzer;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg);
end;
end if;
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
procedure Read_Attributes (Key : in String;
Element : in out Message_Handler) is
begin
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
begin
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
end if;
end loop;
end;
end loop;
end Read_Attributes;
begin
Log.Debug ("Read event definition {0}", Name);
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attributes'Access);
end if;
end Read_Definition;
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Client.Flags := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
end Read_Headers;
end MAT.Readers;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Events;
with MAT.Types;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Attribute_Table_Ptr) is
Handler : Message_Handler;
begin
Handler.For_Servant := Reader;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg);
end;
end if;
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
procedure Read_Attributes (Key : in String;
Element : in out Message_Handler) is
begin
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
begin
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
end if;
end loop;
end;
end loop;
end Read_Attributes;
begin
Log.Debug ("Read event definition {0}", Name);
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attributes'Access);
end if;
end Read_Definition;
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Client.Flags := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
end Read_Headers;
end MAT.Readers;
|
Remove unused operations
|
Remove unused operations
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
c189c7c966bfc208a9d85b87bb299ab334039a81
|
mat/src/mat-readers.ads
|
mat/src/mat-readers.ads
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Finalization;
with System;
with Util.Properties;
with Util.Streams.Buffered;
with MAT.Types;
with MAT.Events;
with MAT.Events.Targets;
package MAT.Readers is
type Buffer_Type is private;
type Buffer_Ptr is access all Buffer_Type;
type Message is record
Kind : MAT.Events.Event_Type;
Size : Natural;
Buffer : Buffer_Ptr;
end record;
-----------------
-- Abstract servant definition
-----------------
-- The Servant is a small proxy that binds the specific message
-- handlers to the client specific dispatcher.
type Reader_Base is abstract tagged limited private;
type Reader_Access is access all Reader_Base'Class;
procedure Dispatch (For_Servant : in out Reader_Base;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out Message) is abstract;
-----------------
-- Ipc Client Manager
-----------------
-- The Manager is a kind of object adapter. It registers a collection
-- of servants and dispatches incomming messages to those servants.
type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with private;
type Manager is access all Manager_Base'Class;
-- Initialize the manager instance.
overriding
procedure Initialize (Manager : in out Manager_Base);
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message);
-- Read a message from the stream.
procedure Read_Message (Client : in out Manager_Base;
Msg : in out Message) is abstract;
-- Read a list of event definitions from the stream and configure the reader.
procedure Read_Event_Definitions (Client : in out Manager_Base;
Msg : in out Message);
-- Get the target events.
function Get_Target_Events (Client : in Manager_Base)
return MAT.Events.Targets.Target_Events_Access;
private
type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN);
type Buffer_Type is record
Current : System.Address;
Start : System.Address;
Last : System.Address;
Buffer : Util.Streams.Buffered.Buffer_Access;
Size : Natural;
Total : Natural;
Endian : Endian_Type := LITTLE_ENDIAN;
end record;
type Reader_Base is abstract tagged limited record
Owner : Manager := null;
end record;
-- Record a servant
type Message_Handler is record
For_Servant : Reader_Access;
Id : MAT.Events.Internal_Reference;
Attributes : MAT.Events.Const_Attribute_Table_Access;
Mapping : MAT.Events.Attribute_Table_Ptr;
end record;
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type;
use type MAT.Types.Uint16;
package Reader_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Message_Handler,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Runtime handlers associated with the events.
package Handler_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16,
Element_Type => Message_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with record
Readers : Reader_Maps.Map;
Handlers : Handler_Maps.Map;
Version : MAT.Types.Uint16;
Flags : MAT.Types.Uint16;
Probe : MAT.Events.Attribute_Table_Ptr;
Frame : access MAT.Events.Frame_Info;
Events : MAT.Events.Targets.Target_Events_Access;
end record;
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message);
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message);
end MAT.Readers;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Finalization;
with System;
with Util.Properties;
with Util.Streams.Buffered;
with MAT.Types;
with MAT.Events;
with MAT.Events.Targets;
package MAT.Readers is
type Buffer_Type is private;
type Buffer_Ptr is access all Buffer_Type;
type Message is record
Kind : MAT.Events.Event_Type;
Size : Natural;
Buffer : Buffer_Ptr;
end record;
-----------------
-- Abstract servant definition
-----------------
-- The Servant is a small proxy that binds the specific message
-- handlers to the client specific dispatcher.
type Reader_Base is abstract tagged limited private;
type Reader_Access is access all Reader_Base'Class;
procedure Dispatch (For_Servant : in out Reader_Base;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out Message) is abstract;
-----------------
-- Ipc Client Manager
-----------------
-- The Manager is a kind of object adapter. It registers a collection
-- of servants and dispatches incomming messages to those servants.
type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with private;
type Manager is access all Manager_Base'Class;
-- Initialize the manager instance.
overriding
procedure Initialize (Manager : in out Manager_Base);
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message);
-- Read a message from the stream.
procedure Read_Message (Client : in out Manager_Base;
Msg : in out Message) is abstract;
-- Read a list of event definitions from the stream and configure the reader.
procedure Read_Event_Definitions (Client : in out Manager_Base;
Msg : in out Message);
-- Get the target events.
function Get_Target_Events (Client : in Manager_Base)
return MAT.Events.Targets.Target_Events_Access;
type Reader_List_Type is limited interface;
type Reader_List_Type_Access is access all Reader_List_Type'Class;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (List : in out Reader_List_Type;
Reader : in out Manager_Base'Class) is abstract;
private
type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN);
type Buffer_Type is record
Current : System.Address;
Start : System.Address;
Last : System.Address;
Buffer : Util.Streams.Buffered.Buffer_Access;
Size : Natural;
Total : Natural;
Endian : Endian_Type := LITTLE_ENDIAN;
end record;
type Reader_Base is abstract tagged limited record
Owner : Manager := null;
end record;
-- Record a servant
type Message_Handler is record
For_Servant : Reader_Access;
Id : MAT.Events.Internal_Reference;
Attributes : MAT.Events.Const_Attribute_Table_Access;
Mapping : MAT.Events.Attribute_Table_Ptr;
end record;
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type;
use type MAT.Types.Uint16;
package Reader_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Message_Handler,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Runtime handlers associated with the events.
package Handler_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16,
Element_Type => Message_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with record
Readers : Reader_Maps.Map;
Handlers : Handler_Maps.Map;
Version : MAT.Types.Uint16;
Flags : MAT.Types.Uint16;
Probe : MAT.Events.Attribute_Table_Ptr;
Frame : access MAT.Events.Frame_Info;
Events : MAT.Events.Targets.Target_Events_Access;
end record;
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message);
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message);
end MAT.Readers;
|
Define the Reader_List_Type interface with the Initialize procedure
|
Define the Reader_List_Type interface with the Initialize procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
7533773c33ff4e598ae1a5174d80228dcb88b0e3
|
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.Strings.Sets;
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;
Names : Util.Strings.Sets.Set;
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_Project_List (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := List.First;
Ref : Model.Projects.Project_Reference;
begin
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;
end Print_Project_List;
-- ------------------------------
-- 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 not Project.Modules.Is_Empty then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
Print_Project_List (Project, Indent, Project.Modules);
Print_Project_List (Project, Indent, Project.Dependencies);
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
declare
Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name);
begin
Ada.Text_IO.Set_Col (Indent);
if Names.Contains (Name) then
Ada.Text_IO.Put_Line ("!! " & Name);
else
Names.Insert (Name);
Ada.Text_IO.Put_Line ("== " & Name);
Print_Modules (Ref.Project.all, Indent + 4);
Names.Delete (Name);
end if;
end;
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;
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Strings.Sets;
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);
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector);
List : Gen.Utils.String_List.Vector;
Names : Util.Strings.Sets.Set;
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_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := List.First;
Ref : Model.Projects.Project_Reference;
begin
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;
end Print_Project_List;
-- ------------------------------
-- 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 not Project.Modules.Is_Empty then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
Print_Project_List (Indent, Project.Modules);
Print_Project_List (Indent, Project.Dependencies);
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
declare
Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name);
begin
Ada.Text_IO.Set_Col (Indent);
if Names.Contains (Name) then
Ada.Text_IO.Put_Line ("!! " & Name);
else
Names.Insert (Name);
Ada.Text_IO.Put_Line ("== " & Name);
Print_Modules (Ref.Project.all, Indent + 4);
Names.Delete (Name);
end if;
end;
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;
|
Simplify the Print_Project_List procedure, fix compilation warnings
|
Simplify the Print_Project_List procedure, fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
62556a4e98d03c7abcdbbc3c25f92dc378bdfe54
|
tests/natools-smaz-tests.adb
|
tests/natools-smaz-tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Natools.Smaz.Original;
package body Natools.Smaz.Tests is
function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Image (S : Ada.Streams.Stream_Element_Array) return String is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Image;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
begin
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Decompressed);
begin
First_OK := True;
if Buffer /= Compressed then
Test.Fail ("Bad compression of """ & Decompressed & '"');
Test.Info ("Found: " & Image (Buffer));
Test.Info ("Expected:" & Image (Compressed));
declare
Round : constant String := Decompress (Dict, Buffer);
begin
if Round /= Decompressed then
Test.Info ("Roundtrip failed, got: """ & Round & '"');
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of """ & Decompressed & '"');
end if;
Test.Report_Exception (Error, NT.Fail);
end;
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant String := Decompress (Dict, Compressed);
begin
First_OK := True;
if Buffer /= Decompressed then
Test.Fail ("Bad decompression of " & Image (Compressed));
Test.Info ("Found: """ & Buffer & '"');
Test.Info ("Expected:""" & Decompressed & '"');
declare
Round : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Buffer);
begin
if Round /= Compressed then
Test.Info ("Roundtrip failed, got: " & Image (Round));
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of " & Image (Compressed));
end if;
Test.Report_Exception (Error, NT.Fail);
end;
end Roundtrip_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Sample_Strings (Report);
end All_Tests;
----------------------
-- Individual Tests --
----------------------
procedure Sample_Strings (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 1, 48, 48, 24, 204, 254, 69, 250, 4, 45,
60, 22, 255, 2, 51, 51, 51));
Roundtrip_Test (Test, Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 1, 49, 48, 0, 255, 1, 50, 48, 0, 255, 1, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings;
end Natools.Smaz.Tests;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Natools.Smaz.Original;
package body Natools.Smaz.Tests is
function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Image (S : Ada.Streams.Stream_Element_Array) return String is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Image;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
begin
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Decompressed);
begin
First_OK := True;
if Buffer /= Compressed then
Test.Fail ("Bad compression of """ & Decompressed & '"');
Test.Info ("Found: " & Image (Buffer));
Test.Info ("Expected:" & Image (Compressed));
declare
Round : constant String := Decompress (Dict, Buffer);
begin
if Round /= Decompressed then
Test.Info ("Roundtrip failed, got: """ & Round & '"');
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of """ & Decompressed & '"');
end if;
Test.Report_Exception (Error, NT.Fail);
end;
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant String := Decompress (Dict, Compressed);
begin
First_OK := True;
if Buffer /= Decompressed then
Test.Fail ("Bad decompression of " & Image (Compressed));
Test.Info ("Found: """ & Buffer & '"');
Test.Info ("Expected:""" & Decompressed & '"');
declare
Round : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Buffer);
begin
if Round /= Compressed then
Test.Info ("Roundtrip failed, got: " & Image (Round));
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of " & Image (Compressed));
end if;
Test.Report_Exception (Error, NT.Fail);
end;
end Roundtrip_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Sample_Strings (Report);
end All_Tests;
----------------------
-- Individual Tests --
----------------------
procedure Sample_Strings (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109,
112, 108, 51, 51, 51));
Roundtrip_Test (Test, Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings;
end Natools.Smaz.Tests;
|
update the expected compressed to match improved encoder
|
smaz-tests: update the expected compressed to match improved encoder
|
Ada
|
isc
|
faelys/natools
|
b0ffed4012c9461553410e72389fa904f2cb4b29
|
regtests/ado-tests.adb
|
regtests/ado-tests.adb
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Calendar;
with ADO.Statements;
with ADO.Objects;
with ADO.Sessions;
with ADO.Utils;
with Regtests;
with Regtests.Simple.Model;
with Regtests.Images.Model;
with Util.Assertions;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Test_Caller;
package body ADO.Tests is
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests");
package Caller is new Util.Test_Caller (Test, "ADO");
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
T.Fail ("Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
T.Fail ("Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use ADO.Objects;
use type ADO.Sessions.Connection_Status;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
T.Assert (DB.Get_Status = ADO.Sessions.OPEN,
"The database connection is open");
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
-- ------------------------------
-- Test string insert.
-- ------------------------------
procedure Test_String (T : in out Test) is
use ADO.Objects;
use Ada.Strings.Unbounded;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
User : Regtests.Simple.Model.User_Ref;
Usr2 : Regtests.Simple.Model.User_Ref;
Name : Unbounded_String;
begin
for I in 1 .. 127 loop
Append (Name, Character'Val (I));
end loop;
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
DB.Begin_Transaction;
User.Set_Name (Name);
User.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Usr2.Load (DB, User.Get_Id);
Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name),
"Invalid name inserted for user");
end Test_String;
-- ------------------------------
-- Test blob insert.
-- ------------------------------
procedure Test_Blob (T : in out Test) is
use ADO.Objects;
use Ada.Streams;
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element);
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Img : Regtests.Images.Model.Image_Ref;
Size : constant Natural := 100;
Data : ADO.Blob_Ref := ADO.Create_Blob (Size);
Img2 : Regtests.Images.Model.Image_Ref;
begin
for I in 1 .. Size loop
Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255);
end loop;
DB.Begin_Transaction;
Img.Set_Image (Data);
Img.Set_Create_Date (Ada.Calendar.Clock);
Img.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
-- And verify that the blob data matches what we inserted.
Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len),
"Invalid blob length");
for I in 1 .. Data.Value.Len loop
Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I),
"Invalid blob content at " & Stream_Element_Offset'Image (I));
end loop;
-- Create a blob initialized with a file content.
Data := ADO.Create_Blob ("Makefile");
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob");
T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small");
declare
Content : Ada.Streams.Stream_Element_Array (1 .. 10);
Img3 : Regtests.Images.Model.Image_Ref;
begin
for I in Content'Range loop
Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30);
end loop;
Data := ADO.Create_Blob (Content);
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)");
T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small");
DB.Begin_Transaction;
Img3.Set_Image (Data);
Img3.Set_Create_Date (Ada.Calendar.Clock);
Img3.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img3.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
Img2.Set_Image (ADO.Null_Blob);
Img2.Save (DB);
DB.Commit;
end;
end Test_Blob;
-- ------------------------------
-- Test the To_Object and To_Identifier operations.
-- ------------------------------
procedure Test_Identifier_To_Object (T : in out Test) is
Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER);
begin
T.Assert (Util.Beans.Objects.Is_Null (Val),
"To_Object must return null for ADO.NO_IDENTIFIER");
T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER,
"To_Identifier must return ADO.NO_IDENTIFIER for null");
Val := ADO.Utils.To_Object (1);
T.Assert (not Util.Beans.Objects.Is_Null (Val),
"To_Object must not return null for a valid Identifier");
T.Assert (ADO.Utils.To_Identifier (Val) = 1,
"To_Identifier must return the correct identifier");
end Test_Identifier_To_Object;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access);
Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access);
Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access);
Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access);
Caller.Add_Test (Suite, "Test insert string",
Test_String'Access);
Caller.Add_Test (Suite, "Test insert blob",
Test_Blob'Access);
Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier",
Test_Identifier_To_Object'Access);
end Add_Tests;
end ADO.Tests;
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Calendar;
with ADO.Statements;
with ADO.Objects;
with ADO.Sessions;
with ADO.Utils;
with Regtests;
with Regtests.Simple.Model;
with Regtests.Images.Model;
with Util.Assertions;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Test_Caller;
package body ADO.Tests is
use Ada.Exceptions;
use ADO.Statements;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests");
package Caller is new Util.Test_Caller (Test, "ADO");
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
T.Fail ("Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
T.Fail ("Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use type ADO.Sessions.Connection_Status;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
T.Assert (DB.Get_Status = ADO.Sessions.OPEN,
"The database connection is open");
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
-- ------------------------------
-- Test string insert.
-- ------------------------------
procedure Test_String (T : in out Test) is
use Ada.Strings.Unbounded;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
User : Regtests.Simple.Model.User_Ref;
Usr2 : Regtests.Simple.Model.User_Ref;
Name : Unbounded_String;
begin
for I in 1 .. 127 loop
Append (Name, Character'Val (I));
end loop;
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
DB.Begin_Transaction;
User.Set_Name (Name);
User.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Usr2.Load (DB, User.Get_Id);
Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name),
"Invalid name inserted for user");
end Test_String;
-- ------------------------------
-- Test blob insert.
-- ------------------------------
procedure Test_Blob (T : in out Test) is
use Ada.Streams;
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element);
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Img : Regtests.Images.Model.Image_Ref;
Size : constant Natural := 100;
Data : ADO.Blob_Ref := ADO.Create_Blob (Size);
Img2 : Regtests.Images.Model.Image_Ref;
begin
for I in 1 .. Size loop
Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255);
end loop;
DB.Begin_Transaction;
Img.Set_Image (Data);
Img.Set_Create_Date (Ada.Calendar.Clock);
Img.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
-- And verify that the blob data matches what we inserted.
Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len),
"Invalid blob length");
for I in 1 .. Data.Value.Len loop
Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I),
"Invalid blob content at " & Stream_Element_Offset'Image (I));
end loop;
-- Create a blob initialized with a file content.
Data := ADO.Create_Blob ("Makefile");
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob");
T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small");
declare
Content : Ada.Streams.Stream_Element_Array (1 .. 10);
Img3 : Regtests.Images.Model.Image_Ref;
begin
for I in Content'Range loop
Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30);
end loop;
Data := ADO.Create_Blob (Content);
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)");
T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small");
DB.Begin_Transaction;
Img3.Set_Image (Data);
Img3.Set_Create_Date (Ada.Calendar.Clock);
Img3.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img3.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
Img2.Set_Image (ADO.Null_Blob);
Img2.Save (DB);
DB.Commit;
end;
end Test_Blob;
-- ------------------------------
-- Test the To_Object and To_Identifier operations.
-- ------------------------------
procedure Test_Identifier_To_Object (T : in out Test) is
Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER);
begin
T.Assert (Util.Beans.Objects.Is_Null (Val),
"To_Object must return null for ADO.NO_IDENTIFIER");
T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER,
"To_Identifier must return ADO.NO_IDENTIFIER for null");
Val := ADO.Utils.To_Object (1);
T.Assert (not Util.Beans.Objects.Is_Null (Val),
"To_Object must not return null for a valid Identifier");
T.Assert (ADO.Utils.To_Identifier (Val) = 1,
"To_Identifier must return the correct identifier");
end Test_Identifier_To_Object;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access);
Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access);
Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access);
Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access);
Caller.Add_Test (Suite, "Test insert string",
Test_String'Access);
Caller.Add_Test (Suite, "Test insert blob",
Test_Blob'Access);
Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier",
Test_Identifier_To_Object'Access);
end Add_Tests;
end ADO.Tests;
|
Remove unecessary use clause
|
Remove unecessary use clause
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
5ef13269e90049ecca9dd1c336495666f42d56e5
|
samples/print_user.adb
|
samples/print_user.adb
|
-----------------------------------------------------------------------
-- Print_User -- Example to find an object from the database
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with ADO.Drivers;
with ADO.Sessions;
with ADO.SQL;
with ADO.Sessions.Factory;
with Samples.User.Model;
with Util.Log.Loggers;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Print_User is
use ADO;
use Ada;
use Samples.User.Model;
Factory : ADO.Sessions.Factory.Session_Factory;
begin
Util.Log.Loggers.Initialize ("samples.properties");
-- Initialize the database drivers.
ADO.Drivers.Initialize ("samples.properties");
if Ada.Command_Line.Argument_Count < 1 then
Ada.Text_IO.Put_Line ("Usage: print_user user-name ...");
Ada.Text_IO.Put_Line ("Example: print_user joe");
Ada.Command_Line.Set_Exit_Status (2);
return;
end if;
-- Create and configure the connection pool
Factory.Create (ADO.Drivers.Get_Config ("ado.database"));
declare
Session : ADO.Sessions.Session := Factory.Get_Session;
User : User_Ref;
Found : Boolean;
begin
for I in 1 .. Ada.Command_Line.Argument_Count loop
declare
User_Name : constant String := Ada.Command_Line.Argument (I);
Query : ADO.SQL.Query;
begin
Ada.Text_IO.Put_Line ("Searching '" & User_Name & "'...");
Query.Bind_Param (1, User_Name);
Query.Set_Filter ("name = ?");
User.Find (Session => Session, Query => Query, Found => Found);
if Found then
Ada.Text_IO.Put_Line (" Id : " & Identifier'Image (User.Get_Id));
Ada.Text_IO.Put_Line (" User : " & User.Get_Name);
Ada.Text_IO.Put_Line (" Email : " & User.Get_Email);
else
Ada.Text_IO.Put_Line (" User '" & User_Name & "' does not exist");
end if;
end;
end loop;
end;
end Print_User;
|
-----------------------------------------------------------------------
-- Print_User -- Example to find an object from the database
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with ADO.Drivers.Initializer;
with ADO.Sessions;
with ADO.SQL;
with ADO.Sessions.Factory;
with Samples.User.Model;
with Util.Log.Loggers;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Print_User is
use ADO;
use Ada;
use Samples.User.Model;
Factory : ADO.Sessions.Factory.Session_Factory;
begin
Util.Log.Loggers.Initialize ("samples.properties");
-- Initialize the database drivers.
ADO.Drivers.Initialize ("samples.properties");
if Ada.Command_Line.Argument_Count < 1 then
Ada.Text_IO.Put_Line ("Usage: print_user user-name ...");
Ada.Text_IO.Put_Line ("Example: print_user joe");
Ada.Command_Line.Set_Exit_Status (2);
return;
end if;
-- Create and configure the connection pool
Factory.Create (ADO.Drivers.Get_Config ("ado.database"));
declare
Session : ADO.Sessions.Session := Factory.Get_Session;
User : User_Ref;
Found : Boolean;
begin
for I in 1 .. Ada.Command_Line.Argument_Count loop
declare
User_Name : constant String := Ada.Command_Line.Argument (I);
Query : ADO.SQL.Query;
begin
Ada.Text_IO.Put_Line ("Searching '" & User_Name & "'...");
Query.Bind_Param (1, User_Name);
Query.Set_Filter ("name = ?");
User.Find (Session => Session, Query => Query, Found => Found);
if Found then
Ada.Text_IO.Put_Line (" Id : " & Identifier'Image (User.Get_Id));
Ada.Text_IO.Put_Line (" User : " & User.Get_Name);
Ada.Text_IO.Put_Line (" Email : " & User.Get_Email);
else
Ada.Text_IO.Put_Line (" User '" & User_Name & "' does not exist");
end if;
end;
end loop;
end;
end Print_User;
|
Update driver registration and initialization
|
Update driver registration and initialization
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
0ab2ffb053d39c669f6d8d68edcc6e5179f83f63
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "50";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "51";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
end Definitions;
|
Bump version to 1.51
|
Bump version to 1.51
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
8d87e6136b9c68c5ac3e1b61ae2aa3a0ce2d0d07
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "2";
synth_version_minor : constant String := "07";
copyright_years : constant String := "2015-2018";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "2";
synth_version_minor : constant String := "08";
copyright_years : constant String := "2015-2019";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
Bump copyright years and version for upcoming release
|
Bump copyright years and version for upcoming release
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
3f750f1702534a1f591eadd9bd37cfcd3be88081
|
src/wiki-attributes.adb
|
src/wiki-attributes.adb
|
-----------------------------------------------------------------------
-- wiki-attributes -- Wiki document attributes
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Ada.Unchecked_Deallocation;
package body Wiki.Attributes is
use Ada.Characters;
-- ------------------------------
-- Get the attribute name.
-- ------------------------------
function Get_Name (Position : in Cursor) return String is
Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos);
begin
return Attr.Name;
end Get_Name;
-- ------------------------------
-- Get the attribute value.
-- ------------------------------
function Get_Value (Position : in Cursor) return String is
Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos);
begin
return Ada.Characters.Conversions.To_String (Attr.Value);
end Get_Value;
-- ------------------------------
-- Get the attribute wide value.
-- ------------------------------
function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is
Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos);
begin
return Attr.Value;
end Get_Wide_Value;
-- ------------------------------
-- Get the attribute wide value.
-- ------------------------------
function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is
Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos);
begin
return To_Unbounded_Wide_Wide_String (Attr.Value);
end Get_Unbounded_Wide_Value;
-- ------------------------------
-- Returns True if the cursor has a valid attribute.
-- ------------------------------
function Has_Element (Position : in Cursor) return Boolean is
begin
return Attribute_Vectors.Has_Element (Position.Pos);
end Has_Element;
-- ------------------------------
-- Move the cursor to the next attribute.
-- ------------------------------
procedure Next (Position : in out Cursor) is
begin
Attribute_Vectors.Next (Position.Pos);
end Next;
-- ------------------------------
-- Find the attribute with the given name.
-- ------------------------------
function Find (List : in Attribute_List_Type;
Name : in String) return Cursor is
Iter : Attribute_Vectors.Cursor := List.List.First;
begin
while Attribute_Vectors.Has_Element (Iter) loop
declare
Attr : constant Attribute_Access := Attribute_Vectors.Element (Iter);
begin
if Attr.Name = Name then
return Cursor '(Pos => Iter);
end if;
end;
Attribute_Vectors.Next (Iter);
end loop;
return Cursor '(Pos => Iter);
end Find;
-- ------------------------------
-- Find the attribute with the given name and return its value.
-- ------------------------------
function Get_Attribute (List : in Attribute_List_Type;
Name : in String) return Unbounded_Wide_Wide_String is
Attr : constant Cursor := Find (List, Name);
begin
if Has_Element (Attr) then
return Get_Unbounded_Wide_Value (Attr);
else
return Null_Unbounded_Wide_Wide_String;
end if;
end Get_Attribute;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List_Type;
Name : in Wide_Wide_String;
Value : in Wide_Wide_String) is
Attr : constant Attribute_Access
:= new Attribute '(Name_Length => Name'Length,
Value_Length => Value'Length,
Name => Conversions.To_String (Name),
Value => Value);
begin
List.List.Append (Attr);
end Append;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List_Type;
Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is
begin
Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name),
Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value));
end Append;
-- ------------------------------
-- Get the cursor to get access to the first attribute.
-- ------------------------------
function First (List : in Attribute_List_Type) return Cursor is
begin
return Cursor '(Pos => List.List.First);
end First;
-- ------------------------------
-- Get the number of attributes in the list.
-- ------------------------------
function Length (List : in Attribute_List_Type) return Natural is
begin
return Natural (List.List.Length);
end Length;
-- ------------------------------
-- Clear the list and remove all existing attributes.
-- ------------------------------
procedure Clear (List : in out Attribute_List_Type) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Attribute,
Name => Attribute_Access);
Item : Attribute_Access;
begin
while not List.List.Is_Empty loop
Item := List.List.Last_Element;
List.List.Delete_Last;
Free (Item);
end loop;
end Clear;
-- ------------------------------
-- Finalize the attribute list releasing any storage.
-- ------------------------------
overriding
procedure Finalize (List : in out Attribute_List_Type) is
begin
List.Clear;
end Finalize;
end Wiki.Attributes;
|
-----------------------------------------------------------------------
-- wiki-attributes -- Wiki document attributes
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Ada.Unchecked_Deallocation;
package body Wiki.Attributes is
use Ada.Characters;
-- ------------------------------
-- Get the attribute name.
-- ------------------------------
function Get_Name (Position : in Cursor) return String is
Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos);
begin
return Attr.Name;
end Get_Name;
-- ------------------------------
-- Get the attribute value.
-- ------------------------------
function Get_Value (Position : in Cursor) return String is
Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos);
begin
return Ada.Characters.Conversions.To_String (Attr.Value);
end Get_Value;
-- ------------------------------
-- Get the attribute wide value.
-- ------------------------------
function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is
Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos);
begin
return Attr.Value;
end Get_Wide_Value;
-- ------------------------------
-- Get the attribute wide value.
-- ------------------------------
function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is
Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos);
begin
return To_Unbounded_Wide_Wide_String (Attr.Value);
end Get_Unbounded_Wide_Value;
-- ------------------------------
-- Returns True if the cursor has a valid attribute.
-- ------------------------------
function Has_Element (Position : in Cursor) return Boolean is
begin
return Attribute_Vectors.Has_Element (Position.Pos);
end Has_Element;
-- ------------------------------
-- Move the cursor to the next attribute.
-- ------------------------------
procedure Next (Position : in out Cursor) is
begin
Attribute_Vectors.Next (Position.Pos);
end Next;
-- ------------------------------
-- Find the attribute with the given name.
-- ------------------------------
function Find (List : in Attribute_List_Type;
Name : in String) return Cursor is
Iter : Attribute_Vectors.Cursor := List.List.First;
begin
while Attribute_Vectors.Has_Element (Iter) loop
declare
Attr : constant Attribute_Access := Attribute_Vectors.Element (Iter);
begin
if Attr.Name = Name then
return Cursor '(Pos => Iter);
end if;
end;
Attribute_Vectors.Next (Iter);
end loop;
return Cursor '(Pos => Iter);
end Find;
-- ------------------------------
-- Find the attribute with the given name and return its value.
-- ------------------------------
function Get_Attribute (List : in Attribute_List_Type;
Name : in String) return Unbounded_Wide_Wide_String is
Attr : constant Cursor := Find (List, Name);
begin
if Has_Element (Attr) then
return Get_Unbounded_Wide_Value (Attr);
else
return Null_Unbounded_Wide_Wide_String;
end if;
end Get_Attribute;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List_Type;
Name : in Wide_Wide_String;
Value : in Wide_Wide_String) is
Attr : constant Attribute_Access
:= new Attribute '(Name_Length => Name'Length,
Value_Length => Value'Length,
Name => Conversions.To_String (Name),
Value => Value);
begin
List.List.Append (Attr);
end Append;
-- ------------------------------
-- Append the attribute to the attribute list.
-- ------------------------------
procedure Append (List : in out Attribute_List_Type;
Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is
begin
Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name),
Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value));
end Append;
-- ------------------------------
-- Get the cursor to get access to the first attribute.
-- ------------------------------
function First (List : in Attribute_List_Type) return Cursor is
begin
return Cursor '(Pos => List.List.First);
end First;
-- ------------------------------
-- Get the number of attributes in the list.
-- ------------------------------
function Length (List : in Attribute_List_Type) return Natural is
begin
return Natural (List.List.Length);
end Length;
-- ------------------------------
-- Clear the list and remove all existing attributes.
-- ------------------------------
procedure Clear (List : in out Attribute_List_Type) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Attribute,
Name => Attribute_Access);
Item : Attribute_Access;
begin
while not List.List.Is_Empty loop
Item := List.List.Last_Element;
List.List.Delete_Last;
Free (Item);
end loop;
end Clear;
-- ------------------------------
-- Iterate over the list attributes and call the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterate (List : in Attribute_List_Type;
Process : not null access procedure (Name : in String;
Value : in Wide_Wide_String)) is
Iter : Attribute_Vectors.Cursor := List.List.First;
Item : Attribute_Access;
begin
while Attribute_Vectors.Has_Element (Iter) loop
Item := Attribute_Vectors.Element (Iter);
Process (Item.Name, Item.Value);
Attribute_Vectors.Next (Iter);
end loop;
end Iterate;
-- ------------------------------
-- Finalize the attribute list releasing any storage.
-- ------------------------------
overriding
procedure Finalize (List : in out Attribute_List_Type) is
begin
List.Clear;
end Finalize;
end Wiki.Attributes;
|
Implement the Iterate procedure and invoke the Process procedure with each name/value pair
|
Implement the Iterate procedure and invoke the Process procedure with each name/value pair
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
28060ddd680e5bf34a8e1e2e7ba91797ae70a766
|
src/asf-routes.ads
|
src/asf-routes.ads
|
-----------------------------------------------------------------------
-- asf-routes -- Request routing
-- 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.Finalization;
with Util.Beans.Basic;
with Util.Refs;
with EL.Expressions;
with EL.Contexts;
package ASF.Routes is
type Route_Type is abstract new Util.Refs.Ref_Entity with null record;
type Route_Type_Access is access all Route_Type'Class;
-- function Duplicate (Route : in Route_Type) return Route_Type_Access is abstract;
package Route_Type_Refs is
new Util.Refs.Indefinite_References (Element_Type => Route_Type'Class,
Element_Access => Route_Type_Access);
subtype Route_Type_Ref is Route_Type_Refs.Ref;
-- subtype Route_Type_Access is Route_Type_Refs.Element_Access;
No_Parameter : exception;
type Path_Mode is (FULL, PREFIX, SUFFIX);
-- The <tt>Route_Context_Type</tt> defines the context information after a path
-- has been routed.
type Route_Context_Type is tagged limited private;
-- Get path information after the routing.
function Get_Path (Context : in Route_Context_Type;
Mode : in Path_Mode := FULL) return String;
-- Get the path parameter value for the given parameter index.
-- The <tt>No_Parameter</tt> exception is raised if the parameter does not exist.
function Get_Parameter (Context : in Route_Context_Type;
Index : in Positive) return String;
-- Get the number of path parameters that were extracted for the route.
function Get_Parameter_Count (Context : in Route_Context_Type) return Natural;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
function Get_Path_Pos (Context : in Route_Context_Type) return Natural;
-- Return the route associated with the resolved route context.
function Get_Route (Context : in Route_Context_Type) return Route_Type_Access;
-- Change the context to use a new route.
procedure Change_Route (Context : in out Route_Context_Type;
To : in Route_Type_Access);
-- Inject the parameters that have been extracted from the path according
-- to the selected route.
procedure Inject_Parameters (Context : in Route_Context_Type;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- The <tt>Router_Type</tt> registers the different routes with their rules and
-- resolves a path into a route context information.
type Router_Type is new Ada.Finalization.Limited_Controlled with private;
type Router_Type_Access is access all Router_Type'Class;
-- Add a route associated with the given path pattern. The pattern is split into components.
-- Some path components can be a fixed string (/home) and others can be variable.
-- When a path component is variable, the value can be retrieved from the route context.
procedure Add_Route (Router : in out Router_Type;
Pattern : in String;
To : in Route_Type_Access;
ELContext : in EL.Contexts.ELContext'Class);
-- Build the route context from the given path by looking at the different routes registered
-- in the router with <tt>Add_Route</tt>.
procedure Find_Route (Router : in Router_Type;
Path : in String;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Router : in Router_Type;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
private
-- use type Route_Type_Refs.Element_Access;
type String_Access is access all String;
type Route_Node_Type;
type Route_Node_Access is access all Route_Node_Type'Class;
-- Describes a variable path component whose value must be injected in an Ada bean.
type Route_Param_Type is limited record
Route : Route_Node_Access;
First : Natural := 0;
Last : Natural := 0;
end record;
type Route_Param_Array is array (Positive range <>) of Route_Param_Type;
type Route_Match_Type is (NO_MATCH, MAYBE_MATCH, WILDCARD_MATCH, EXT_MATCH, YES_MATCH);
type Route_Node_Type is abstract tagged limited record
Next_Route : Route_Node_Access;
Children : Route_Node_Access;
Route : Route_Type_Ref;
end record;
-- Inject the parameter that was extracted from the path.
procedure Inject_Parameter (Node : in Route_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is null;
-- Check if the route node accepts the given path component.
function Matches (Node : in Route_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is abstract;
-- Return the component path pattern that this route node represents.
-- Example: 'index.html', '#{user.id}', ':id'
function Get_Pattern (Node : in Route_Node_Type) return String is abstract;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
function Get_Path_Pos (Node : in Route_Node_Type;
Param : in Route_Param_Type) return Natural;
-- Find recursively a match on the given route sub-tree. The match must start at the position
-- <tt>First</tt> in the path up to the last path position. While the path components are
-- checked, the route context is populated with variable components. When the full path
-- matches, <tt>YES_MATCH</tt> is returned in the context gets the route instance.
procedure Find_Match (Node : in Route_Node_Type;
Path : in String;
First : in Natural;
Match : out Route_Match_Type;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Node : in Route_Node_Type;
Path : in String;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
-- A fixed path component identification.
type Path_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : aliased String (1 .. Len);
end record;
type Path_Node_Access is access all Path_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns YES_MATCH if the name corresponds exactly to the node's name.
overriding
function Matches (Node : in Path_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, 'Name').
overriding
function Get_Pattern (Node : in Path_Node_Type) return String;
-- A variable path component whose value is injected in an Ada bean using the EL expression.
-- The route node is created each time an EL expression is found in the route pattern.
-- Example: /home/#{user.id}/index.html
-- In this example, the EL expression refers to <tt>user.id</tt>.
type EL_Node_Type is new Route_Node_Type with record
Value : EL.Expressions.Value_Expression;
end record;
type EL_Node_Access is access all EL_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in EL_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, the EL expr).
overriding
function Get_Pattern (Node : in EL_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in EL_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- A variable path component which can be injected in an Ada bean.
-- Example: /home/:id/view.html
-- The path component represented by <tt>:id</tt> is injected in the Ada bean object
-- passed to the <tt>Inject_Parameters</tt> procedure.
type Param_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : String (1 .. Len);
end record;
type Param_Node_Access is access all Param_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Param_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, Name).
overriding
function Get_Pattern (Node : in Param_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in Param_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
type Extension_Node_Type (Len : Natural) is new Route_Node_Type with record
Ext : String (1 .. Len);
end record;
type Extension_Node_Access is access all Extension_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Extension_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *.Ext).
overriding
function Get_Pattern (Node : in Extension_Node_Type) return String;
type Wildcard_Node_Type is new Route_Node_Type with null record;
type Wildcard_Node_Access is access all Wildcard_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns WILDCARD_MATCH.
overriding
function Matches (Node : in Wildcard_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *).
overriding
function Get_Pattern (Node : in Wildcard_Node_Type) return String;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
overriding
function Get_Path_Pos (Node : in Wildcard_Node_Type;
Param : in Route_Param_Type) return Natural;
MAX_ROUTE_PARAMS : constant Positive := 10;
type Route_Context_Type is limited new Ada.Finalization.Limited_Controlled with record
Route : Route_Type_Access;
Path : String_Access;
Params : Route_Param_Array (1 .. MAX_ROUTE_PARAMS);
Count : Natural := 0;
end record;
-- Release the storage held by the route context.
overriding
procedure Finalize (Context : in out Route_Context_Type);
type Router_Type is new Ada.Finalization.Limited_Controlled with record
Route : aliased Path_Node_Type (Len => 0);
end record;
-- Release the storage held by the router.
overriding
procedure Finalize (Router : in out Router_Type);
end ASF.Routes;
|
-----------------------------------------------------------------------
-- asf-routes -- Request routing
-- 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.Finalization;
with Util.Beans.Basic;
with Util.Refs;
with EL.Expressions;
with EL.Contexts;
package ASF.Routes is
type Route_Type is abstract new Util.Refs.Ref_Entity with null record;
type Route_Type_Access is access all Route_Type'Class;
-- function Duplicate (Route : in Route_Type) return Route_Type_Access is abstract;
package Route_Type_Refs is
new Util.Refs.Indefinite_References (Element_Type => Route_Type'Class,
Element_Access => Route_Type_Access);
subtype Route_Type_Ref is Route_Type_Refs.Ref;
-- subtype Route_Type_Access is Route_Type_Refs.Element_Access;
No_Parameter : exception;
type Path_Mode is (FULL, PREFIX, SUFFIX);
-- The <tt>Route_Context_Type</tt> defines the context information after a path
-- has been routed.
type Route_Context_Type is tagged limited private;
-- Get path information after the routing.
function Get_Path (Context : in Route_Context_Type;
Mode : in Path_Mode := FULL) return String;
-- Get the path parameter value for the given parameter index.
-- The <tt>No_Parameter</tt> exception is raised if the parameter does not exist.
function Get_Parameter (Context : in Route_Context_Type;
Index : in Positive) return String;
-- Get the number of path parameters that were extracted for the route.
function Get_Parameter_Count (Context : in Route_Context_Type) return Natural;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
function Get_Path_Pos (Context : in Route_Context_Type) return Natural;
-- Return the route associated with the resolved route context.
function Get_Route (Context : in Route_Context_Type) return Route_Type_Access;
-- Change the context to use a new route.
procedure Change_Route (Context : in out Route_Context_Type;
To : in Route_Type_Access);
-- Inject the parameters that have been extracted from the path according
-- to the selected route.
procedure Inject_Parameters (Context : in Route_Context_Type;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- The <tt>Router_Type</tt> registers the different routes with their rules and
-- resolves a path into a route context information.
type Router_Type is new Ada.Finalization.Limited_Controlled with private;
type Router_Type_Access is access all Router_Type'Class;
-- Add a route associated with the given path pattern. The pattern is split into components.
-- Some path components can be a fixed string (/home) and others can be variable.
-- When a path component is variable, the value can be retrieved from the route context.
-- Once the route path is created, the <tt>Process</tt> procedure is called with the route
-- reference.
procedure Add_Route (Router : in out Router_Type;
Pattern : in String;
ELContext : in EL.Contexts.ELContext'Class;
Process : not null access procedure (Route : in out Route_Type_Ref));
-- Build the route context from the given path by looking at the different routes registered
-- in the router with <tt>Add_Route</tt>.
procedure Find_Route (Router : in Router_Type;
Path : in String;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Router : in Router_Type;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
private
-- use type Route_Type_Refs.Element_Access;
type String_Access is access all String;
type Route_Node_Type;
type Route_Node_Access is access all Route_Node_Type'Class;
-- Describes a variable path component whose value must be injected in an Ada bean.
type Route_Param_Type is limited record
Route : Route_Node_Access;
First : Natural := 0;
Last : Natural := 0;
end record;
type Route_Param_Array is array (Positive range <>) of Route_Param_Type;
type Route_Match_Type is (NO_MATCH, MAYBE_MATCH, WILDCARD_MATCH, EXT_MATCH, YES_MATCH);
type Route_Node_Type is abstract tagged limited record
Next_Route : Route_Node_Access;
Children : Route_Node_Access;
Route : Route_Type_Ref;
end record;
-- Inject the parameter that was extracted from the path.
procedure Inject_Parameter (Node : in Route_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is null;
-- Check if the route node accepts the given path component.
function Matches (Node : in Route_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is abstract;
-- Return the component path pattern that this route node represents.
-- Example: 'index.html', '#{user.id}', ':id'
function Get_Pattern (Node : in Route_Node_Type) return String is abstract;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
function Get_Path_Pos (Node : in Route_Node_Type;
Param : in Route_Param_Type) return Natural;
-- Find recursively a match on the given route sub-tree. The match must start at the position
-- <tt>First</tt> in the path up to the last path position. While the path components are
-- checked, the route context is populated with variable components. When the full path
-- matches, <tt>YES_MATCH</tt> is returned in the context gets the route instance.
procedure Find_Match (Node : in Route_Node_Type;
Path : in String;
First : in Natural;
Match : out Route_Match_Type;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Node : in Route_Node_Type;
Path : in String;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
-- A fixed path component identification.
type Path_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : aliased String (1 .. Len);
end record;
type Path_Node_Access is access all Path_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns YES_MATCH if the name corresponds exactly to the node's name.
overriding
function Matches (Node : in Path_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, 'Name').
overriding
function Get_Pattern (Node : in Path_Node_Type) return String;
-- A variable path component whose value is injected in an Ada bean using the EL expression.
-- The route node is created each time an EL expression is found in the route pattern.
-- Example: /home/#{user.id}/index.html
-- In this example, the EL expression refers to <tt>user.id</tt>.
type EL_Node_Type is new Route_Node_Type with record
Value : EL.Expressions.Value_Expression;
end record;
type EL_Node_Access is access all EL_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in EL_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, the EL expr).
overriding
function Get_Pattern (Node : in EL_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in EL_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- A variable path component which can be injected in an Ada bean.
-- Example: /home/:id/view.html
-- The path component represented by <tt>:id</tt> is injected in the Ada bean object
-- passed to the <tt>Inject_Parameters</tt> procedure.
type Param_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : String (1 .. Len);
end record;
type Param_Node_Access is access all Param_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Param_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, Name).
overriding
function Get_Pattern (Node : in Param_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in Param_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
type Extension_Node_Type (Len : Natural) is new Route_Node_Type with record
Ext : String (1 .. Len);
end record;
type Extension_Node_Access is access all Extension_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Extension_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *.Ext).
overriding
function Get_Pattern (Node : in Extension_Node_Type) return String;
type Wildcard_Node_Type is new Route_Node_Type with null record;
type Wildcard_Node_Access is access all Wildcard_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns WILDCARD_MATCH.
overriding
function Matches (Node : in Wildcard_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *).
overriding
function Get_Pattern (Node : in Wildcard_Node_Type) return String;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
overriding
function Get_Path_Pos (Node : in Wildcard_Node_Type;
Param : in Route_Param_Type) return Natural;
MAX_ROUTE_PARAMS : constant Positive := 10;
type Route_Context_Type is limited new Ada.Finalization.Limited_Controlled with record
Route : Route_Type_Access;
Path : String_Access;
Params : Route_Param_Array (1 .. MAX_ROUTE_PARAMS);
Count : Natural := 0;
end record;
-- Release the storage held by the route context.
overriding
procedure Finalize (Context : in out Route_Context_Type);
type Router_Type is new Ada.Finalization.Limited_Controlled with record
Route : aliased Path_Node_Type (Len => 0);
end record;
-- Release the storage held by the router.
overriding
procedure Finalize (Router : in out Router_Type);
end ASF.Routes;
|
Change the Add_Route procedure to invoke a Process procedure with the route reference so that we can update the existing route
|
Change the Add_Route procedure to invoke a Process procedure with the route reference
so that we can update the existing route
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
bcffe2bfc9a85fadcfd69015b3f2b56b33228c45
|
src/babel-base.ads
|
src/babel-base.ads
|
-----------------------------------------------------------------------
-- babel-base -- Database for files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO;
package Babel.Base is
type Database is abstract new Ada.Finalization.Limited_Controlled with private;
private
type Database is abstract new Ada.Finalization.Limited_Controlled with record
Name : Integer;
end record;
end Babel.Base;
|
-----------------------------------------------------------------------
-- babel-base -- Database for files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO;
with Babel.Files;
package Babel.Base is
type Database is abstract new Ada.Finalization.Limited_Controlled with private;
-- Insert the file in the database.
procedure Insert (Into : in out Database;
File : in Babel.Files.File_Type) is abstract;
private
type Database is abstract new Ada.Finalization.Limited_Controlled with record
Name : Integer;
end record;
end Babel.Base;
|
Define the Insert operation on the Database abstract type
|
Define the Insert operation on the Database abstract type
|
Ada
|
apache-2.0
|
stcarrez/babel
|
18e08b31170b3b0976a45a8a311a454029c4b136
|
src/ado-parameters.ads
|
src/ado-parameters.ads
|
-----------------------------------------------------------------------
-- ADO Parameters -- Parameters for queries
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Calendar;
with Ada.Containers.Indefinite_Vectors;
with ADO.Utils;
with ADO.Drivers.Dialects;
-- === Query Parameters ===
-- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost
-- all database types including boolean, numbers, strings, dates and blob. Parameters are
-- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types.
--
-- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt>
-- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name
-- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list
-- and uses the last position. In most cases, it is easier to bind a parameter with a name
-- as follows:
--
-- Query.Bind_Param ("name", "Joe");
--
-- and the SQL can use the following construct:
--
-- SELECT * FROM user WHERE name = :name
--
-- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it
-- as a position index. Setting a parameter is easier:
--
-- Query.Add_Param ("Joe");
--
-- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct:
--
-- SELECT * FROM user WHERE name = ?
--
-- === Parameter Expander ===
-- The parameter expander is a mechanism that allows to replace or inject values in the SQL
-- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander
-- is useful to replace parameters that are global to a session or to an application.
--
package ADO.Parameters is
use Ada.Strings.Unbounded;
type Token is new String;
type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER,
T_INTEGER, T_BOOLEAN, T_BLOB);
type Parameter (T : Parameter_Type;
Len : Natural;
Value_Len : Natural) is record
Position : Natural := 0;
Name : String (1 .. Len);
case T is
when T_NULL =>
null;
when T_LONG_INTEGER =>
Long_Num : Long_Long_Integer := 0;
when T_INTEGER =>
Num : Integer;
when T_BOOLEAN =>
Bool : Boolean;
when T_DATE =>
Time : Ada.Calendar.Time;
when T_BLOB =>
Data : ADO.Blob_Ref;
when others =>
Str : String (1 .. Value_Len);
end case;
end record;
type Expander is limited interface;
type Expander_Access is access all Expander'Class;
-- Expand the name from the given group into a target parameter value to be used in
-- the SQL query. The expander can look in a cache or in some configuration to find
-- the value associated with the name and return it. The Expander can return a
-- T_NULL when a value is not found or it may also raise some exception.
function Expand (Instance : in Expander;
Group : in String;
Name : in String) return Parameter is abstract;
type Abstract_List is abstract new Ada.Finalization.Controlled with private;
type Abstract_List_Access is access all Abstract_List'Class;
-- Set the SQL dialect description object.
procedure Set_Dialect (Params : in out Abstract_List;
D : in ADO.Drivers.Dialects.Dialect_Access);
-- Get the SQL dialect description object.
function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access;
-- Add the parameter in the list.
procedure Add_Parameter (Params : in out Abstract_List;
Param : in Parameter) is abstract;
-- Set the parameters from another parameter list.
procedure Set_Parameters (Parameters : in out Abstract_List;
From : in Abstract_List'Class) is abstract;
-- Return the number of parameters in the list.
function Length (Params : in Abstract_List) return Natural is abstract;
-- Return the parameter at the given position
function Element (Params : in Abstract_List;
Position : in Natural) return Parameter is abstract;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in Abstract_List;
Position : in Natural;
Process : not null access
procedure (Element : in Parameter)) is abstract;
-- Clear the list of parameters.
procedure Clear (Parameters : in out Abstract_List) is abstract;
-- Operations to bind a parameter
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Token);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Blob_Ref);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Utils.Identifier_Vector);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in ADO.Blob_Ref);
procedure Bind_Null_Param (Params : in out Abstract_List;
Position : in Natural);
procedure Bind_Null_Param (Params : in out Abstract_List;
Name : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Boolean);
procedure Add_Param (Params : in out Abstract_List;
Value : in Long_Long_Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in Identifier);
procedure Add_Param (Params : in out Abstract_List;
Value : in Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Unbounded_String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Ada.Calendar.Time);
-- Add a null parameter.
procedure Add_Null_Param (Params : in out Abstract_List);
-- Expand the SQL string with the query parameters. The following parameters syntax
-- are recognized and replaced:
-- <ul>
-- <li>? is replaced according to the current parameter index. The index is incremented
-- after each occurrence of ? character.
-- <li>:nnn is replaced by the parameter at index <b>nnn</b>.
-- <li>:name is replaced by the parameter with the name <b>name</b>
-- </ul>
-- Parameter strings are escaped. When a parameter is not found, an empty string is used.
-- Returns the expanded SQL string.
function Expand (Params : in Abstract_List'Class;
SQL : in String) return String;
-- ------------------------------
-- List of parameters
-- ------------------------------
-- The <b>List</b> is an implementation of the parameter list.
type List is new Abstract_List with private;
procedure Add_Parameter (Params : in out List;
Param : in Parameter);
procedure Set_Parameters (Params : in out List;
From : in Abstract_List'Class);
-- Return the number of parameters in the list.
function Length (Params : in List) return Natural;
-- Return the parameter at the given position
function Element (Params : in List;
Position : in Natural) return Parameter;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in List;
Position : in Natural;
Process : not null access procedure (Element : in Parameter));
-- Clear the list of parameters.
procedure Clear (Params : in out List);
private
function Compare_On_Name (Left, Right : in Parameter) return Boolean;
package Parameter_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Parameter,
"=" => Compare_On_Name);
type Abstract_List is abstract new Ada.Finalization.Controlled with record
Dialect : ADO.Drivers.Dialects.Dialect_Access := null;
Expander : Expander_Access;
end record;
type List is new Abstract_List with record
Params : Parameter_Vectors.Vector;
end record;
end ADO.Parameters;
|
-----------------------------------------------------------------------
-- ADO Parameters -- Parameters for queries
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Calendar;
with Ada.Containers.Indefinite_Vectors;
with ADO.Utils;
with ADO.Drivers.Dialects;
-- === Query Parameters ===
-- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost
-- all database types including boolean, numbers, strings, dates and blob. Parameters are
-- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types.
--
-- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt>
-- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name
-- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list
-- and uses the last position. In most cases, it is easier to bind a parameter with a name
-- as follows:
--
-- Query.Bind_Param ("name", "Joe");
--
-- and the SQL can use the following construct:
--
-- SELECT * FROM user WHERE name = :name
--
-- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it
-- as a position index. Setting a parameter is easier:
--
-- Query.Add_Param ("Joe");
--
-- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct:
--
-- SELECT * FROM user WHERE name = ?
--
-- === Parameter Expander ===
-- The parameter expander is a mechanism that allows to replace or inject values in the SQL
-- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander
-- is useful to replace parameters that are global to a session or to an application.
--
package ADO.Parameters is
use Ada.Strings.Unbounded;
type Token is new String;
type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER,
T_INTEGER, T_BOOLEAN, T_BLOB);
type Parameter (T : Parameter_Type;
Len : Natural;
Value_Len : Natural) is record
Position : Natural := 0;
Name : String (1 .. Len);
case T is
when T_NULL =>
null;
when T_LONG_INTEGER =>
Long_Num : Long_Long_Integer := 0;
when T_INTEGER =>
Num : Integer;
when T_BOOLEAN =>
Bool : Boolean;
when T_DATE =>
Time : Ada.Calendar.Time;
when T_BLOB =>
Data : ADO.Blob_Ref;
when others =>
Str : String (1 .. Value_Len);
end case;
end record;
type Expander is limited interface;
type Expander_Access is access all Expander'Class;
-- Expand the name from the given group into a target parameter value to be used in
-- the SQL query. The expander can look in a cache or in some configuration to find
-- the value associated with the name and return it. The Expander can return a
-- T_NULL when a value is not found or it may also raise some exception.
function Expand (Instance : in Expander;
Group : in String;
Name : in String) return Parameter is abstract;
type Abstract_List is abstract new Ada.Finalization.Controlled with private;
type Abstract_List_Access is access all Abstract_List'Class;
-- Set the SQL dialect description object.
procedure Set_Dialect (Params : in out Abstract_List;
D : in ADO.Drivers.Dialects.Dialect_Access);
-- Get the SQL dialect description object.
function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access;
-- Add the parameter in the list.
procedure Add_Parameter (Params : in out Abstract_List;
Param : in Parameter) is abstract;
-- Set the parameters from another parameter list.
procedure Set_Parameters (Parameters : in out Abstract_List;
From : in Abstract_List'Class) is abstract;
-- Return the number of parameters in the list.
function Length (Params : in Abstract_List) return Natural is abstract;
-- Return the parameter at the given position
function Element (Params : in Abstract_List;
Position : in Natural) return Parameter is abstract;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in Abstract_List;
Position : in Natural;
Process : not null access
procedure (Element : in Parameter)) is abstract;
-- Clear the list of parameters.
procedure Clear (Parameters : in out Abstract_List) is abstract;
-- Operations to bind a parameter
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Token);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Blob_Ref);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Utils.Identifier_Vector);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in ADO.Blob_Ref);
procedure Bind_Null_Param (Params : in out Abstract_List;
Position : in Natural);
procedure Bind_Null_Param (Params : in out Abstract_List;
Name : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Boolean);
procedure Add_Param (Params : in out Abstract_List;
Value : in Long_Long_Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in Identifier);
procedure Add_Param (Params : in out Abstract_List;
Value : in Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Unbounded_String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Ada.Calendar.Time);
-- Add a null parameter.
procedure Add_Null_Param (Params : in out Abstract_List);
-- Expand the SQL string with the query parameters. The following parameters syntax
-- are recognized and replaced:
-- <ul>
-- <li>? is replaced according to the current parameter index. The index is incremented
-- after each occurrence of ? character.
-- <li>:nnn is replaced by the parameter at index <b>nnn</b>.
-- <li>:name is replaced by the parameter with the name <b>name</b>
-- <li>$group[var-name] is replaced by using the expander interface.
-- </ul>
-- Parameter strings are escaped. When a parameter is not found, an empty string is used.
-- Returns the expanded SQL string.
function Expand (Params : in Abstract_List'Class;
SQL : in String) return String;
-- ------------------------------
-- List of parameters
-- ------------------------------
-- The <b>List</b> is an implementation of the parameter list.
type List is new Abstract_List with private;
procedure Add_Parameter (Params : in out List;
Param : in Parameter);
procedure Set_Parameters (Params : in out List;
From : in Abstract_List'Class);
-- Return the number of parameters in the list.
function Length (Params : in List) return Natural;
-- Return the parameter at the given position
function Element (Params : in List;
Position : in Natural) return Parameter;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in List;
Position : in Natural;
Process : not null access procedure (Element : in Parameter));
-- Clear the list of parameters.
procedure Clear (Params : in out List);
private
function Compare_On_Name (Left, Right : in Parameter) return Boolean;
package Parameter_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Parameter,
"=" => Compare_On_Name);
type Abstract_List is abstract new Ada.Finalization.Controlled with record
Dialect : ADO.Drivers.Dialects.Dialect_Access := null;
Expander : Expander_Access;
end record;
type List is new Abstract_List with record
Params : Parameter_Vectors.Vector;
end record;
end ADO.Parameters;
|
Update the documentation for the Expand function
|
Update the documentation for the Expand function
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
09a2190fde33a6a032e56d4a23ca7c7f38e7b406
|
src/el-expressions.adb
|
src/el-expressions.adb
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Language
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Expressions.Nodes;
with EL.Expressions.Parser;
package body EL.Expressions is
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : Expression;
Context : ELContext'Class) return Object is
begin
if Expr.Node = null then
return EL.Objects.Null_Object;
end if;
return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context);
end Get_Value;
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : ValueExpression;
Context : ELContext'Class) return Object is
pragma Unreferenced (Context);
begin
if Expr.Bean = null then
return EL.Objects.Null_Object;
end if;
return To_Object (Expr.Bean);
end Get_Value;
procedure Set_Value (Expr : in ValueExpression;
Context : in ELContext'Class;
Value : in Object) is
begin
null;
end Set_Value;
function Is_Readonly (Expr : in ValueExpression) return Boolean is
begin
if Expr.Bean = null then
return True;
end if;
return not (Expr.Bean.all in EL.Beans.Bean'Class);
end Is_Readonly;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
Result : Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
if Node /= null then
Result.Node := Node.all'Access;
end if;
return Result;
end Create_Expression;
function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class)
return ValueExpression is
Result : ValueExpression;
begin
Result.Bean := Bean;
return Result;
end Create_ValueExpression;
-- Parse an expression and return its representation ready for evaluation.
function Create_Expression (Expr : String;
Context : ELContext'Class)
return ValueExpression is
Result : ValueExpression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
Result.Node := Node.all'Access;
return Result;
end Create_Expression;
procedure Adjust (Object : in out Expression) is
begin
if Object.Node /= null then
Object.Node.Ref_Counter := Object.Node.Ref_Counter + 1;
end if;
end Adjust;
procedure Finalize (Object : in out Expression) is
Node : EL.Expressions.Nodes.ELNode_Access;
begin
if Object.Node /= null then
Node := Object.Node.all'Access;
Node.Ref_Counter := Node.Ref_Counter - 1;
if Node.Ref_Counter = 0 then
EL.Expressions.Nodes.Delete (Node);
Object.Node := null;
end if;
end if;
end Finalize;
end EL.Expressions;
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Language
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Expressions.Nodes;
with EL.Expressions.Parser;
package body EL.Expressions is
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : Expression;
Context : ELContext'Class) return Object is
begin
if Expr.Node = null then
return EL.Objects.Null_Object;
end if;
return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context);
end Get_Value;
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : ValueExpression;
Context : ELContext'Class) return Object is
pragma Unreferenced (Context);
begin
if Expr.Bean = null then
if Expr.Node = null then
return EL.Objects.Null_Object;
else
return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context);
end if;
end if;
return To_Object (Expr.Bean);
end Get_Value;
procedure Set_Value (Expr : in ValueExpression;
Context : in ELContext'Class;
Value : in Object) is
begin
null;
end Set_Value;
function Is_Readonly (Expr : in ValueExpression) return Boolean is
begin
if Expr.Bean = null then
return True;
end if;
return not (Expr.Bean.all in EL.Beans.Bean'Class);
end Is_Readonly;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
Result : Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
if Node /= null then
Result.Node := Node.all'Access;
end if;
return Result;
end Create_Expression;
function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class)
return ValueExpression is
Result : ValueExpression;
begin
Result.Bean := Bean;
return Result;
end Create_ValueExpression;
-- Parse an expression and return its representation ready for evaluation.
function Create_Expression (Expr : String;
Context : ELContext'Class)
return ValueExpression is
Result : ValueExpression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
Result.Node := Node.all'Access;
return Result;
end Create_Expression;
procedure Adjust (Object : in out Expression) is
begin
if Object.Node /= null then
Object.Node.Ref_Counter := Object.Node.Ref_Counter + 1;
end if;
end Adjust;
procedure Finalize (Object : in out Expression) is
Node : EL.Expressions.Nodes.ELNode_Access;
begin
if Object.Node /= null then
Node := Object.Node.all'Access;
Node.Ref_Counter := Node.Ref_Counter - 1;
if Node.Ref_Counter = 0 then
EL.Expressions.Nodes.Delete (Node);
Object.Node := null;
end if;
end if;
end Finalize;
end EL.Expressions;
|
Fix Get_Value for the Value_Expression
|
Fix Get_Value for the Value_Expression
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
9626f98db16d4f2f7085a77ec5585d6bf7ef95ad
|
src/wiki-parsers-mediawiki.adb
|
src/wiki-parsers-mediawiki.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-mediawiki -- Media Wiki parser operations
-- Copyright (C) 2011- 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Helpers;
with Wiki.Parsers.Common;
package body Wiki.Parsers.MediaWiki is
use Wiki.Helpers;
use Wiki.Buffers;
use type Wiki.Nodes.Node_Kind;
procedure Parse_Bold_Italic (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
-- ------------------------------
-- Parse an italic, bold or bold + italic sequence.
-- Example:
-- ''name'' (italic)
-- '''name''' (bold)
-- '''''name''''' (bold+italic)
-- ------------------------------
procedure Parse_Bold_Italic (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Count : Natural := Count_Occurence (Text, From, ''');
begin
case Count is
when 1 =>
Common.Parse_Text (Parser, Text, From);
return;
when 2 =>
Toggle_Format (Parser, ITALIC);
when 3 =>
Toggle_Format (Parser, BOLD);
when 4 =>
Toggle_Format (Parser, BOLD);
Common.Parse_Text (Parser, Text, From);
Count := 3;
when 5 =>
Toggle_Format (Parser, BOLD);
Toggle_Format (Parser, ITALIC);
when others =>
Common.Parse_Text (Parser, Text, From);
return;
end case;
for I in 1 .. Count loop
Next (Text, From);
end loop;
end Parse_Bold_Italic;
procedure Parse_Line (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access) is
Pos : Natural := 1;
C : Wiki.Strings.WChar;
Buffer : Wiki.Buffers.Buffer_Access := Text;
begin
-- Feed the HTML parser if there are some pending state.
if not Wiki.Html_Parser.Is_Empty (Parser.Html) then
Common.Parse_Html_Element (Parser, Buffer, Pos, Start => False);
if Buffer = null then
return;
end if;
end if;
if Parser.Pre_Tag_Counter > 0 then
Common.Parse_Html_Preformatted (Parser, Buffer, Pos);
if Buffer = null then
return;
end if;
end if;
if Parser.Current_Node = Nodes.N_PREFORMAT then
if Buffer.Content (Pos) = ' ' then
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
end if;
Pop_Block (Parser);
end if;
if Parser.Current_Node = Nodes.N_HEADER then
Pop_Block (Parser);
end if;
C := Buffer.Content (Pos);
case C is
when CR | LF =>
Common.Parse_Paragraph (Parser, Buffer, Pos);
return;
when '=' =>
Common.Parse_Header (Parser, Buffer, Pos, '=');
if Buffer = null then
return;
end if;
when '-' =>
Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-');
if Buffer = null then
return;
end if;
when '*' | '#' =>
if Common.Is_List (Buffer, Pos) then
Common.Parse_List (Parser, Buffer, Pos);
end if;
when ' ' =>
Parser.Preformat_Indent := 1;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 1;
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Push_Block (Parser, Nodes.N_PREFORMAT);
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
when ';' =>
Common.Parse_Definition (Parser, Buffer, Pos);
return;
when ':' =>
if Parser.Current_Node = Nodes.N_DEFINITION then
Next (Buffer, Pos);
Common.Skip_Spaces (Buffer, Pos);
end if;
when others =>
if Parser.Current_Node /= Nodes.N_PARAGRAPH then
Pop_List (Parser);
Push_Block (Parser, Nodes.N_PARAGRAPH);
end if;
end case;
Main :
while Buffer /= null loop
declare
Last : Natural := Buffer.Last;
begin
while Pos <= Last loop
C := Buffer.Content (Pos);
case C is
when ''' =>
Parse_Bold_Italic (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '/' =>
Parse_Format_Double (Parser, Buffer, Pos, '/', Wiki.EMPHASIS);
exit Main when Buffer = null;
when '[' =>
Common.Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '{' =>
Common.Parse_Template (Parser, Buffer, Pos, '{');
exit Main when Buffer = null;
when CR | LF =>
Append (Parser.Text, ' ');
Pos := Pos + 1;
when '<' =>
Common.Parse_Html_Element (Parser, Buffer, Pos, Start => True);
exit Main when Buffer = null;
when '&' =>
Common.Parse_Entity (Parser, Buffer, Pos);
exit Main when Buffer = null;
when others =>
Append (Parser.Text, C);
Pos := Pos + 1;
end case;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop Main;
end Parse_Line;
end Wiki.Parsers.MediaWiki;
|
-----------------------------------------------------------------------
-- wiki-parsers-mediawiki -- Media Wiki parser operations
-- Copyright (C) 2011- 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Helpers;
with Wiki.Parsers.Common;
package body Wiki.Parsers.MediaWiki is
use Wiki.Helpers;
use Wiki.Buffers;
use type Wiki.Nodes.Node_Kind;
procedure Parse_Bold_Italic (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
-- ------------------------------
-- Parse an italic, bold or bold + italic sequence.
-- Example:
-- ''name'' (italic)
-- '''name''' (bold)
-- '''''name''''' (bold+italic)
-- ------------------------------
procedure Parse_Bold_Italic (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Count : Natural := Count_Occurence (Text, From, ''');
begin
case Count is
when 1 =>
Common.Parse_Text (Parser, Text, From);
return;
when 2 =>
Toggle_Format (Parser, ITALIC);
when 3 =>
Toggle_Format (Parser, BOLD);
when 4 =>
Toggle_Format (Parser, BOLD);
Common.Parse_Text (Parser, Text, From);
Count := 3;
when 5 =>
Toggle_Format (Parser, BOLD);
Toggle_Format (Parser, ITALIC);
when others =>
Common.Parse_Text (Parser, Text, From);
return;
end case;
for I in 1 .. Count loop
Next (Text, From);
end loop;
end Parse_Bold_Italic;
procedure Parse_Line (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access) is
Pos : Natural := 1;
C : Wiki.Strings.WChar;
Buffer : Wiki.Buffers.Buffer_Access := Text;
begin
-- Feed the HTML parser if there are some pending state.
if not Wiki.Html_Parser.Is_Empty (Parser.Html) then
Common.Parse_Html_Element (Parser, Buffer, Pos, Start => False);
if Buffer = null then
return;
end if;
end if;
if Parser.Pre_Tag_Counter > 0 then
Common.Parse_Html_Preformatted (Parser, Buffer, Pos);
if Buffer = null then
return;
end if;
end if;
if Parser.Current_Node = Nodes.N_PREFORMAT then
if Buffer.Content (Pos) = ' ' then
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
end if;
Pop_Block (Parser);
end if;
if Parser.Current_Node = Nodes.N_HEADER then
Pop_Block (Parser);
end if;
C := Buffer.Content (Pos);
case C is
when CR | LF =>
Common.Parse_Paragraph (Parser, Buffer, Pos);
return;
when '=' =>
Common.Parse_Header (Parser, Buffer, Pos, '=');
if Buffer = null then
return;
end if;
when '-' =>
Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-');
if Buffer = null then
return;
end if;
when '*' | '#' =>
if Common.Is_List (Buffer, Pos) then
Common.Parse_List (Parser, Buffer, Pos);
end if;
when ' ' =>
if Common.Is_List (Buffer, Pos + 1) then
Pos := Pos + 1;
Common.Parse_List (Parser, Buffer, Pos);
end if;
-- Parser.Preformat_Indent := 1;
-- Parser.Preformat_Fence := ' ';
-- Parser.Preformat_Fcount := 1;
-- Flush_Text (Parser, Trim => Right);
-- Pop_Block (Parser);
-- Push_Block (Parser, Nodes.N_PREFORMAT);
-- Common.Append (Parser.Text, Buffer, Pos + 1);
-- return;
when ';' =>
Common.Parse_Definition (Parser, Buffer, Pos);
return;
when ':' =>
if Parser.Current_Node = Nodes.N_DEFINITION then
Next (Buffer, Pos);
Common.Skip_Spaces (Buffer, Pos);
end if;
when others =>
if Parser.Current_Node /= Nodes.N_PARAGRAPH then
Pop_List (Parser);
Push_Block (Parser, Nodes.N_PARAGRAPH);
end if;
end case;
Main :
while Buffer /= null loop
declare
Last : Natural := Buffer.Last;
begin
while Pos <= Buffer.Last loop
C := Buffer.Content (Pos);
case C is
when ''' =>
Parse_Bold_Italic (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '/' =>
Parse_Format_Double (Parser, Buffer, Pos, '/', Wiki.EMPHASIS);
exit Main when Buffer = null;
when '[' =>
Common.Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '{' =>
Common.Parse_Template (Parser, Buffer, Pos, '{');
exit Main when Buffer = null;
when CR | LF =>
Append (Parser.Text, ' ');
Pos := Pos + 1;
when '<' =>
Common.Parse_Html_Element (Parser, Buffer, Pos, Start => True);
exit Main when Buffer = null;
when '&' =>
Common.Parse_Entity (Parser, Buffer, Pos);
exit Main when Buffer = null;
when others =>
Append (Parser.Text, C);
Pos := Pos + 1;
end case;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop Main;
end Parse_Line;
end Wiki.Parsers.MediaWiki;
|
Fix pre-formatting in the new Mediawiki parser
|
Fix pre-formatting in the new Mediawiki parser
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
9fbc6f0879f7e6edc62ae3e793cf896f3333c123
|
src/wiki-render.adb
|
src/wiki-render.adb
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
package body Wiki.Render is
-- ------------------------------
-- 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 Wiki.Strings.WString;
URI : out Wiki.Strings.UString;
Width : out Natural;
Height : out Natural) is
pragma Unreferenced (Renderer);
begin
URI := Wiki.Strings.To_UString (Link);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- 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 Wiki.Strings.WString;
URI : out Wiki.Strings.UString;
Exists : out Boolean) is
pragma Unreferenced (Renderer);
begin
URI := Wiki.Strings.To_UString (Link);
Exists := True;
end Make_Page_Link;
-- ------------------------------
-- 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) is
use type Wiki.Nodes.Node_List_Access;
procedure Process (Node : in Wiki.Nodes.Node_Type);
procedure Process (Node : in Wiki.Nodes.Node_Type) is
begin
Engine.Render (Doc, Node);
end Process;
begin
if List /= null then
Wiki.Nodes.Iterate (List, Process'Access);
end if;
end Render;
-- ------------------------------
-- Render the document.
-- ------------------------------
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document) is
procedure Process (Node : in Wiki.Nodes.Node_Type);
procedure Process (Node : in Wiki.Nodes.Node_Type) is
begin
Engine.Render (Doc, Node);
end Process;
begin
Doc.Iterate (Process'Access);
Engine.Finish (Doc);
end Render;
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.
-----------------------------------------------------------------------
package body Wiki.Render is
-- ------------------------------
-- 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) is
use type Wiki.Nodes.Node_List_Access;
procedure Process (Node : in Wiki.Nodes.Node_Type);
procedure Process (Node : in Wiki.Nodes.Node_Type) is
begin
Engine.Render (Doc, Node);
end Process;
begin
if List /= null then
Wiki.Nodes.Iterate (List, Process'Access);
end if;
end Render;
-- ------------------------------
-- Render the document.
-- ------------------------------
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document) is
procedure Process (Node : in Wiki.Nodes.Node_Type);
procedure Process (Node : in Wiki.Nodes.Node_Type) is
begin
Engine.Render (Doc, Node);
end Process;
begin
Doc.Iterate (Process'Access);
Engine.Finish (Doc);
end Render;
end Wiki.Render;
|
Move the Link_Renderer and Default_Link_Renderer in the Wiki.Render.Links package
|
Move the Link_Renderer and Default_Link_Renderer in the Wiki.Render.Links package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
3887dc9bc2c18271c4a19532b02cebcfc02e70bb
|
regtests/el-objects-discrete_tests.adb
|
regtests/el-objects-discrete_tests.adb
|
-----------------------------------------------------------------------
-- el-objects-tests - Generic simple test for discrete object types
-- 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 Ada.Containers;
with Util.Test_Caller;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with Ada.Calendar;
with EL.Objects.Hash;
package body EL.Objects.Discrete_Tests is
use EL.Objects;
use Ada.Strings.Fixed;
use Ada.Containers;
procedure Test_Eq (T : Test; V : String; N : Test_Type);
procedure Test_Conversion (T : Test; V : String; N : Test_Type);
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type);
procedure Test_Sub (T : Test; V : String; N : Test_Type);
procedure Test_Add (T : Test; V : String; N : Test_Type);
-- Generic test for To_Object and To_XXX types
-- Several values are specified in the Test_Values string.
generic
with procedure Basic_Test (T : in Test; V : String; N : Test_Type);
procedure Test_Basic_Object (T : in out Test);
procedure Test_Basic_Object (T : in out Test) is
pragma Unmodified (T);
Pos, Next : Natural;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
begin
Basic_Test (T, V, N);
end;
Pos := Next + 1;
end loop;
end Test_Basic_Object;
-- ------------------------------
-- Test EL.Objects.To_Object
-- ------------------------------
procedure Test_Conversion (T : Test; V : String; N : Test_Type) is
Value : EL.Objects.Object;
begin
Value := To_Object (V);
T.Assert (Condition => To_Type (Value) = N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
T.Assert (Condition => V = To_String (Value),
Message => Test_Name & ".To_String returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Conversion;
procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion);
-- ------------------------------
-- Test EL.Objects.Hash
-- ------------------------------
procedure Test_Hash (T : in out Test) is
pragma Unmodified (T);
Pos, Next : Natural;
Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0);
Nb_Hash : Natural := 0;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
Value : constant EL.Objects.Object := To_Object_Test (N);
H : constant Hash_Type := EL.Objects.Hash (Value);
Found : Boolean := False;
begin
for J in 1 .. Nb_Hash loop
if Hash_Values (J) = H then
Found := True;
end if;
end loop;
if not Found then
Nb_Hash := Nb_Hash + 1;
Hash_Values (Nb_Hash) := H;
end if;
end;
Pos := Next + 1;
end loop;
Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values");
Assert (T, Nb_Hash > 1, "Only one hash value found");
end Test_Hash;
-- ------------------------------
-- Test EL.Objects."+"
-- ------------------------------
procedure Test_Add (T : Test; V : String; N : Test_Type) is
Value : EL.Objects.Object := To_Object_Test (N);
begin
Value := Value + To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N + N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Add;
procedure Test_Add is new Test_Basic_Object (Test_Add);
-- ------------------------------
-- Test EL.Objects."-"
-- ------------------------------
procedure Test_Sub (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (V);
Value : EL.Objects.Object;
begin
Value := To_Object_Test (N) - To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N - N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: 0");
end Test_Sub;
procedure Test_Sub is new Test_Basic_Object (Test_Sub);
-- ------------------------------
-- Test EL.Objects."<" and EL.Objects.">"
-- ------------------------------
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is
Res : Boolean;
Is_Neg : constant Boolean := Index (V, "-") = V'First;
O : EL.Objects.Object := To_Object_Test (N);
begin
Res := To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O))
& " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O)));
Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V);
if V /= "0" and V /= "false" and V /= "true" then
Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
end if;
end Test_Lt_Gt;
procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt);
-- ------------------------------
-- Test EL.Objects."="
-- ------------------------------
procedure Test_Eq (T : Test; V : String; N : Test_Type) is
Res : Boolean;
begin
Res := To_Object_Test (N) = To_Object_Test (N);
T.Assert (Condition => Res,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " when we expected: true");
Res := To_Object_Test (N) = To_Object ("Something" & V);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " where we expected: False");
end Test_Eq;
procedure Test_Eq is new Test_Basic_Object (Test_Eq);
-- ------------------------------
-- Test EL.Objects."="
-- ------------------------------
procedure Test_Perf (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (T, V);
use Ada.Calendar;
Start : Ada.Calendar.Time;
Value : constant EL.Objects.Object := To_Object_Test (N);
D : Duration;
begin
Start := Ada.Calendar.Clock;
for I in 1 .. 1_000 loop
declare
V : EL.Objects.Object := Value;
begin
V := V + V;
pragma Unreferenced (V);
end;
end loop;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0));
end Test_Perf;
procedure Test_Perf is new Test_Basic_Object (Test_Perf);
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test EL.Objects.To_Object." & Test_Name,
Test_To_Object'Access);
Caller.Add_Test (Suite, "Test EL.Objects.To_String." & Test_Name,
Test_To_Object'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'='." & Test_Name,
Test_Eq'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'+'." & Test_Name,
Test_Add'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'-'." & Test_Name,
Test_Sub'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'<'." & Test_Name,
Test_Lt_Gt'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'>'." & Test_Name,
Test_Lt_Gt'Access);
Caller.Add_Test (Suite, "Performance EL.Objects.'>'." & Test_Name,
Test_Perf'Access);
Caller.Add_Test (Suite, "Test EL.Objects.Hash." & Test_Name,
Test_Hash'Access);
end Add_Tests;
end EL.Objects.Discrete_Tests;
|
-----------------------------------------------------------------------
-- el-objects-tests - Generic simple test for discrete object types
-- 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 Ada.Containers;
with Util.Test_Caller;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with Ada.Calendar;
with EL.Objects.Hash;
package body EL.Objects.Discrete_Tests is
use EL.Objects;
use Ada.Strings.Fixed;
use Ada.Containers;
procedure Test_Eq (T : Test; V : String; N : Test_Type);
procedure Test_Conversion (T : Test; V : String; N : Test_Type);
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type);
procedure Test_Sub (T : Test; V : String; N : Test_Type);
procedure Test_Add (T : Test; V : String; N : Test_Type);
-- Generic test for To_Object and To_XXX types
-- Several values are specified in the Test_Values string.
generic
with procedure Basic_Test (T : in Test; V : String; N : Test_Type);
procedure Test_Basic_Object (T : in out Test);
procedure Test_Basic_Object (T : in out Test) is
pragma Unmodified (T);
Pos, Next : Natural;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
begin
Basic_Test (T, V, N);
end;
Pos := Next + 1;
end loop;
end Test_Basic_Object;
-- ------------------------------
-- Test EL.Objects.To_Object
-- ------------------------------
procedure Test_Conversion (T : Test; V : String; N : Test_Type) is
Value : EL.Objects.Object;
begin
Value := To_Object (V);
T.Assert (Condition => To_Type (Value) = N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
T.Assert (Condition => V = To_String (Value),
Message => Test_Name & ".To_String returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Conversion;
procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion);
-- ------------------------------
-- Test EL.Objects.Hash
-- ------------------------------
procedure Test_Hash (T : in out Test) is
pragma Unmodified (T);
Pos, Next : Natural;
Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0);
Nb_Hash : Natural := 0;
begin
Pos := Test_Values'First;
while Pos <= Test_Values'Last loop
Next := Index (Test_Values, ",", Pos);
if Next < Pos then
Next := Test_Values'Last + 1;
end if;
declare
V : constant String := Test_Values (Pos .. Next - 1);
N : constant Test_Type := Value (V);
Value : constant EL.Objects.Object := To_Object_Test (N);
H : constant Hash_Type := EL.Objects.Hash (Value);
Found : Boolean := False;
begin
for J in 1 .. Nb_Hash loop
if Hash_Values (J) = H then
Found := True;
end if;
end loop;
if not Found then
Nb_Hash := Nb_Hash + 1;
Hash_Values (Nb_Hash) := H;
end if;
end;
Pos := Next + 1;
end loop;
Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values");
Assert (T, Nb_Hash > 1, "Only one hash value found");
end Test_Hash;
-- ------------------------------
-- Test EL.Objects."+"
-- ------------------------------
procedure Test_Add (T : Test; V : String; N : Test_Type) is
Value : EL.Objects.Object := To_Object_Test (N);
begin
Value := Value + To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N + N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: " & V);
end Test_Add;
procedure Test_Add is new Test_Basic_Object (Test_Add);
-- ------------------------------
-- Test EL.Objects."-"
-- ------------------------------
procedure Test_Sub (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (V);
Value : EL.Objects.Object;
begin
Value := To_Object_Test (N) - To_Object_Test (N);
T.Assert (Condition => To_Type (Value) = N - N,
Message => Test_Name & " returned invalid value: "
& To_String (Value) & " when we expected: 0");
end Test_Sub;
procedure Test_Sub is new Test_Basic_Object (Test_Sub);
-- ------------------------------
-- Test EL.Objects."<" and EL.Objects.">"
-- ------------------------------
procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is
Res : Boolean;
Is_Neg : constant Boolean := Index (V, "-") = V'First;
O : EL.Objects.Object := To_Object_Test (N);
begin
Res := To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: false");
Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O))
& " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O)));
Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (Is_Neg)
& " with value: " & V);
if V /= "0" and V /= "false" and V /= "true" then
Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'<' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N);
T.Assert (Condition => Res = not Is_Neg,
Message => Test_Name & ".'>' returned invalid value: "
& Boolean'Image (Res) & " when we expected: "
& Boolean'Image (not Is_Neg)
& " with value: " & V);
end if;
end Test_Lt_Gt;
procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt);
-- ------------------------------
-- Test EL.Objects."="
-- ------------------------------
procedure Test_Eq (T : Test; V : String; N : Test_Type) is
Res : Boolean;
begin
Res := To_Object_Test (N) = To_Object_Test (N);
T.Assert (Condition => Res,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " when we expected: true");
Res := To_Object_Test (N) = To_Object ("Something" & V);
T.Assert (Condition => Res = False,
Message => Test_Name & ".'=' returned invalid value: "
& Boolean'Image (Res) & " where we expected: False");
end Test_Eq;
procedure Test_Eq is new Test_Basic_Object (Test_Eq);
-- ------------------------------
-- Test EL.Objects."="
-- ------------------------------
procedure Test_Perf (T : Test; V : String; N : Test_Type) is
pragma Unreferenced (T, V);
use Ada.Calendar;
Start : Ada.Calendar.Time;
Value : constant EL.Objects.Object := To_Object_Test (N);
D : Duration;
begin
Start := Ada.Calendar.Clock;
for I in 1 .. 1_000 loop
declare
V : EL.Objects.Object := Value;
begin
V := V + V;
pragma Unreferenced (V);
end;
end loop;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0));
end Test_Perf;
procedure Test_Perf is new Test_Basic_Object (Test_Perf);
package Caller is new Util.Test_Caller (Test, "EL.Objects");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test EL.Objects.To_Object." & Test_Name,
Test_To_Object'Access);
Caller.Add_Test (Suite, "Test EL.Objects.To_String." & Test_Name,
Test_To_Object'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'='." & Test_Name,
Test_Eq'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'+'." & Test_Name,
Test_Add'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'-'." & Test_Name,
Test_Sub'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'<'." & Test_Name,
Test_Lt_Gt'Access);
Caller.Add_Test (Suite, "Test EL.Objects.'>'." & Test_Name,
Test_Lt_Gt'Access);
Caller.Add_Test (Suite, "Performance EL.Objects.'>'." & Test_Name,
Test_Perf'Access);
Caller.Add_Test (Suite, "Test EL.Objects.Hash." & Test_Name,
Test_Hash'Access);
end Add_Tests;
end EL.Objects.Discrete_Tests;
|
Use the test name EL.Objects
|
Use the test name EL.Objects
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
2bd18f41318427616bf2bed57865e26fc21c5f2a
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- 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 AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Services.Tests;
with AWA.Wikis.Parsers.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 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.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with ASF.Server.Web;
with ASF.Servlets.Faces;
with ASF.Server.Tests;
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;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
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.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Blogs.Services.Tests.Add_Tests (Ret);
AWA.Storages.Services.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
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : AWA.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.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.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- 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 AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Services.Tests;
with AWA.Wikis.Parsers.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.Services.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.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with ASF.Server.Web;
with ASF.Servlets.Faces;
with ASF.Server.Tests;
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;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
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.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Blogs.Services.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.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
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : AWA.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.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
Add the images plugin unit tests
|
Add the images plugin unit tests
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
5db70522e0fdb3c0c37f1cbaebb480496f2db6c6
|
src/babel-stores-local.adb
|
src/babel-stores-local.adb
|
-----------------------------------------------------------------------
-- bkp-stores-local -- Store management for local files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Interfaces.C.Strings;
with System.OS_Constants;
with Util.Log.Loggers;
with Util.Files;
with Util.Systems.Os;
with Util.Streams.Raw;
with Interfaces;
package body Babel.Stores.Local is
function Errno return Integer;
pragma Import (C, errno, "__get_errno");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local");
function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Ada.Directories.File_Size is
Size : Ada.Directories.File_Size;
begin
Size := Ada.Directories.Size (Ent);
return Size;
exception
when Constraint_Error =>
return Ada.Directories.File_Size (Interfaces.Unsigned_32'Last);
end Get_File_Size;
-- ------------------------------
-- Get the absolute path to access the local file.
-- ------------------------------
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String is
begin
if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then
return Path;
else
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path);
end if;
end Get_Absolute_Path;
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path);
Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last);
Ada.Streams.Stream_IO.Close (File);
Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last));
end Read;
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String) is
use Util.Systems.Os;
use type Interfaces.C.int;
File : Util.Systems.Os.File_Type;
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
begin
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
end if;
end if;
if File < 0 then
raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path;
end if;
Stream.Initialize (File);
Interfaces.C.Strings.Free (Name);
end Open;
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
Stream : Util.Streams.Raw.Raw_Stream;
begin
Log.Info ("Write {0}", Abs_Path);
Store.Open (Stream, Abs_Path);
Stream.Write (Into.Data (Into.Data'First .. Into.Last));
Stream.Close;
end Write;
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is
use Ada.Directories;
Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Log.Info ("Scan directory {0}", Path);
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
File : Babel.Files.File_Type;
begin
if Kind = Ordinary_File then
if Filter.Is_Accepted (Kind, Path, Name) then
File := Into.Find (Name);
if File = null then
File := Into.Create (Name);
end if;
Babel.Files.Set_Size (Get_File_Size (Ent));
Into.Add_File (Path, New_File);
end if;
elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then
Child := Info.Find (Name);
if Child = null then
Child := Into.Create (Name);
end if;
Into.Add_Directory (Child);
-- if Into.Children = null then
-- Into.Children := new Babel.Files.Directory_Vector;
-- end if;
-- Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
-- Into.Children.Append (Child);
-- Into.Tot_Dirs := Into.Tot_Dirs + 1;
Into.Add_Directory (Path, Name);
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
-- ------------------------------
-- Set the root directory for the local store.
-- ------------------------------
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String) is
begin
Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path);
end Set_Root_Directory;
end Babel.Stores.Local;
|
-----------------------------------------------------------------------
-- bkp-stores-local -- Store management for local files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Interfaces.C.Strings;
with System.OS_Constants;
with Util.Log.Loggers;
with Util.Files;
with Util.Systems.Os;
with Util.Streams.Raw;
with Interfaces;
package body Babel.Stores.Local is
function Errno return Integer;
pragma Import (C, errno, "__get_errno");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local");
function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Babel.Files.File_Size is
Size : Ada.Directories.File_Size;
begin
Size := Ada.Directories.Size (Ent);
return Babel.Files.File_Size (Size);
exception
when Constraint_Error =>
return Babel.Files.File_Size (Interfaces.Unsigned_32'Last);
end Get_File_Size;
-- ------------------------------
-- Get the absolute path to access the local file.
-- ------------------------------
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String is
begin
if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then
return Path;
else
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path);
end if;
end Get_Absolute_Path;
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
File : Ada.Streams.Stream_IO.File_Type;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
begin
Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path);
Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last);
Ada.Streams.Stream_IO.Close (File);
Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last));
end Read;
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String) is
use Util.Systems.Os;
use type Interfaces.C.int;
File : Util.Systems.Os.File_Type;
Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path);
begin
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#);
end if;
end if;
if File < 0 then
raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path;
end if;
Stream.Initialize (File);
Interfaces.C.Strings.Free (Name);
end Open;
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer) is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
Abs_Path : constant String := Store.Get_Absolute_Path (Path);
Stream : Util.Streams.Raw.Raw_Stream;
begin
Log.Info ("Write {0}", Abs_Path);
Store.Open (Stream, Abs_Path);
Stream.Write (Into.Data (Into.Data'First .. Into.Last));
Stream.Close;
end Write;
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class) is
use Ada.Directories;
use type Babel.Files.File_Type;
use type Babel.Files.Directory_Type;
Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True,
Ada.Directories.Directory => True,
Special_File => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Log.Info ("Scan directory {0}", Path);
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Kind : constant File_Kind := Ada.Directories.Kind (Ent);
File : Babel.Files.File_Type;
Dir : Babel.Files.Directory_Type;
begin
if Kind = Ordinary_File then
if Filter.Is_Accepted (Kind, Path, Name) then
File := Into.Find (Name);
if File = Babel.Files.NO_FILE then
File := Into.Create (Name);
end if;
Babel.Files.Set_Size (File, Get_File_Size (Ent));
Into.Add_File (File);
end if;
elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then
Dir := Into.Find (Name);
if Dir = Babel.Files.NO_DIRECTORY then
Dir := Into.Create (Name);
end if;
Into.Add_Directory (Dir);
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception ", E);
end Scan;
-- ------------------------------
-- Set the root directory for the local store.
-- ------------------------------
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String) is
begin
Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path);
end Set_Root_Directory;
end Babel.Stores.Local;
|
Update the Scan procedure implementation to use the new File_Container interface
|
Update the Scan procedure implementation to use the new File_Container interface
|
Ada
|
apache-2.0
|
stcarrez/babel
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.