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
|
---|---|---|---|---|---|---|---|---|---|
1106da608bcc2fe762c15626ebbc98c921899d49
|
src/security-auth.adb
|
src/security-auth.adb
|
-----------------------------------------------------------------------
-- security-openid -- OpenID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.Auth.OpenID;
with Security.Auth.OAuth.Facebook;
package body Security.Auth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth");
-- ------------------------------
-- Get the provider.
-- ------------------------------
function Get_Provider (Assoc : in Association) return String is
begin
return To_String (Assoc.Provider);
end Get_Provider;
-- ------------------------------
-- Get the email address
-- ------------------------------
function Get_Email (Auth : in Authentication) return String is
begin
return To_String (Auth.Email);
end Get_Email;
-- ------------------------------
-- Get the user first name.
-- ------------------------------
function Get_First_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.First_Name);
end Get_First_Name;
-- ------------------------------
-- Get the user last name.
-- ------------------------------
function Get_Last_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Last_Name);
end Get_Last_Name;
-- ------------------------------
-- Get the user full name.
-- ------------------------------
function Get_Full_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Full_Name);
end Get_Full_Name;
-- ------------------------------
-- Get the user identity.
-- ------------------------------
function Get_Identity (Auth : in Authentication) return String is
begin
return To_String (Auth.Identity);
end Get_Identity;
-- ------------------------------
-- Get the user claimed identity.
-- ------------------------------
function Get_Claimed_Id (Auth : in Authentication) return String is
begin
return To_String (Auth.Claimed_Id);
end Get_Claimed_Id;
-- ------------------------------
-- Get the user language.
-- ------------------------------
function Get_Language (Auth : in Authentication) return String is
begin
return To_String (Auth.Language);
end Get_Language;
-- ------------------------------
-- Get the user country.
-- ------------------------------
function Get_Country (Auth : in Authentication) return String is
begin
return To_String (Auth.Country);
end Get_Country;
-- ------------------------------
-- Get the result of the authentication.
-- ------------------------------
function Get_Status (Auth : in Authentication) return Auth_Result is
begin
return Auth.Status;
end Get_Status;
-- ------------------------------
-- Default principal
-- ------------------------------
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Principal) return String is
begin
return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth);
end Get_Name;
-- ------------------------------
-- Get the user email address.
-- ------------------------------
function Get_Email (From : in Principal) return String is
begin
return Get_Email (From.Auth);
end Get_Email;
-- ------------------------------
-- Get the authentication data.
-- ------------------------------
function Get_Authentication (From : in Principal) return Authentication is
begin
return From.Auth;
end Get_Authentication;
-- ------------------------------
-- Create a principal with the given authentication results.
-- ------------------------------
function Create_Principal (Auth : in Authentication) return Principal_Access is
P : constant Principal_Access := new Principal;
begin
P.Auth := Auth;
return P;
end Create_Principal;
-- ------------------------------
-- Initialize the OpenID realm.
-- ------------------------------
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID) is
Provider : constant String := Params.Get_Parameter ("auth.provider." & Name);
Impl : Manager_Access;
begin
if Provider = PROVIDER_OPENID then
Impl := new Security.Auth.OpenID.Manager;
elsif Provider = PROVIDER_FACEBOOK then
Impl := new Security.Auth.OAuth.Facebook.Manager;
else
Log.Error ("Authentication provider {0} not recognized", Provider);
raise Service_Error with "Authentication provider not supported";
end if;
Realm.Delegate := Impl;
Impl.Initialize (Params, Name);
Realm.Provider := To_Unbounded_String (Name);
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Discover (Name, Result);
else
-- Result.URL := Realm.Realm;
Result.Alias := To_Unbounded_String ("");
end if;
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Provider := Realm.Provider;
if Realm.Delegate /= null then
Realm.Delegate.Associate (OP, Result);
end if;
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
begin
if Realm.Delegate /= null then
return Realm.Delegate.Get_Authentication_URL (OP, Assoc);
else
return To_String (OP.URL);
end if;
end Get_Authentication_URL;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String) is
begin
if Status /= AUTHENTICATED then
Log.Error ("OpenID verification failed: {0}", Message);
else
Log.Info ("OpenID verification: {0}", Message);
end if;
Result.Status := Status;
end Set_Result;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Verify (Assoc, Request, Result);
else
Set_Result (Result, SETUP_NEEDED, "Setup is needed");
end if;
end Verify;
function To_String (OP : End_Point) return String is
begin
return "openid://" & To_String (OP.URL);
end To_String;
function To_String (Assoc : Association) return String is
begin
return "session_type=" & To_String (Assoc.Session_Type)
& "&assoc_type=" & To_String (Assoc.Assoc_Type)
& "&assoc_handle=" & To_String (Assoc.Assoc_Handle)
& "&mac_key=" & To_String (Assoc.Mac_Key);
end To_String;
end Security.Auth;
|
-----------------------------------------------------------------------
-- security-openid -- OpenID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.Auth.OpenID;
with Security.Auth.OAuth.Facebook;
with Security.Auth.OAuth.Googleplus;
package body Security.Auth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth");
-- ------------------------------
-- Get the provider.
-- ------------------------------
function Get_Provider (Assoc : in Association) return String is
begin
return To_String (Assoc.Provider);
end Get_Provider;
-- ------------------------------
-- Get the email address
-- ------------------------------
function Get_Email (Auth : in Authentication) return String is
begin
return To_String (Auth.Email);
end Get_Email;
-- ------------------------------
-- Get the user first name.
-- ------------------------------
function Get_First_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.First_Name);
end Get_First_Name;
-- ------------------------------
-- Get the user last name.
-- ------------------------------
function Get_Last_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Last_Name);
end Get_Last_Name;
-- ------------------------------
-- Get the user full name.
-- ------------------------------
function Get_Full_Name (Auth : in Authentication) return String is
begin
return To_String (Auth.Full_Name);
end Get_Full_Name;
-- ------------------------------
-- Get the user identity.
-- ------------------------------
function Get_Identity (Auth : in Authentication) return String is
begin
return To_String (Auth.Identity);
end Get_Identity;
-- ------------------------------
-- Get the user claimed identity.
-- ------------------------------
function Get_Claimed_Id (Auth : in Authentication) return String is
begin
return To_String (Auth.Claimed_Id);
end Get_Claimed_Id;
-- ------------------------------
-- Get the user language.
-- ------------------------------
function Get_Language (Auth : in Authentication) return String is
begin
return To_String (Auth.Language);
end Get_Language;
-- ------------------------------
-- Get the user country.
-- ------------------------------
function Get_Country (Auth : in Authentication) return String is
begin
return To_String (Auth.Country);
end Get_Country;
-- ------------------------------
-- Get the result of the authentication.
-- ------------------------------
function Get_Status (Auth : in Authentication) return Auth_Result is
begin
return Auth.Status;
end Get_Status;
-- ------------------------------
-- Default principal
-- ------------------------------
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Principal) return String is
begin
return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth);
end Get_Name;
-- ------------------------------
-- Get the user email address.
-- ------------------------------
function Get_Email (From : in Principal) return String is
begin
return Get_Email (From.Auth);
end Get_Email;
-- ------------------------------
-- Get the authentication data.
-- ------------------------------
function Get_Authentication (From : in Principal) return Authentication is
begin
return From.Auth;
end Get_Authentication;
-- ------------------------------
-- Create a principal with the given authentication results.
-- ------------------------------
function Create_Principal (Auth : in Authentication) return Principal_Access is
P : constant Principal_Access := new Principal;
begin
P.Auth := Auth;
return P;
end Create_Principal;
-- ------------------------------
-- Initialize the OpenID realm.
-- ------------------------------
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID) is
Provider : constant String := Params.Get_Parameter ("auth.provider." & Name);
Impl : Manager_Access;
begin
if Provider = PROVIDER_OPENID then
Impl := new Security.Auth.OpenID.Manager;
elsif Provider = PROVIDER_FACEBOOK then
Impl := new Security.Auth.OAuth.Facebook.Manager;
elsif Provider = PROVIDER_GOOGLE_PLUS then
Impl := new Security.Auth.OAuth.Googleplus.Manager;
else
Log.Error ("Authentication provider {0} not recognized", Provider);
raise Service_Error with "Authentication provider not supported";
end if;
Realm.Delegate := Impl;
Impl.Initialize (Params, Name);
Realm.Provider := To_Unbounded_String (Name);
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Discover (Name, Result);
else
-- Result.URL := Realm.Realm;
Result.Alias := To_Unbounded_String ("");
end if;
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Provider := Realm.Provider;
if Realm.Delegate /= null then
Realm.Delegate.Associate (OP, Result);
end if;
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
begin
if Realm.Delegate /= null then
return Realm.Delegate.Get_Authentication_URL (OP, Assoc);
else
return To_String (OP.URL);
end if;
end Get_Authentication_URL;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String) is
begin
if Status /= AUTHENTICATED then
Log.Error ("OpenID verification failed: {0}", Message);
else
Log.Info ("OpenID verification: {0}", Message);
end if;
Result.Status := Status;
end Set_Result;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
begin
if Realm.Delegate /= null then
Realm.Delegate.Verify (Assoc, Request, Result);
else
Set_Result (Result, SETUP_NEEDED, "Setup is needed");
end if;
end Verify;
function To_String (OP : End_Point) return String is
begin
return "openid://" & To_String (OP.URL);
end To_String;
function To_String (Assoc : Association) return String is
begin
return "session_type=" & To_String (Assoc.Session_Type)
& "&assoc_type=" & To_String (Assoc.Assoc_Type)
& "&assoc_handle=" & To_String (Assoc.Assoc_Handle)
& "&mac_key=" & To_String (Assoc.Mac_Key);
end To_String;
end Security.Auth;
|
Use the Google+ implementation
|
Use the Google+ implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
d841e60e573c2f3aa5304f43386d3f522330433c
|
src/asf-requests-tools.adb
|
src/asf-requests-tools.adb
|
-----------------------------------------------------------------------
-- asf.requests.tools -- ASF Requests Tools
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Transforms;
package body ASF.Requests.Tools is
-- ------------------------------
-- Builds a printable representation of the request for debugging purposes.
-- When <b>Html</b> is true, the returned content contains an HTML presentation.
-- ------------------------------
function To_String (Req : in Request'Class;
Html : in Boolean := False;
Print_Headers : in Boolean := True;
Print_Attributes : in Boolean := False) return String is
procedure Put (Title : in String; Value : in String);
procedure Put (Name : in String; Value : in EL.Objects.Object);
procedure Append_Html (Content : in String);
pragma Inline (Append_Html);
Info : Unbounded_String;
procedure Append_Html (Content : in String) is
begin
if Html then
Append (Info, Content);
end if;
end Append_Html;
procedure Put (Title : in String;
Value : in String) is
begin
if Html then
Append (Info, "<tr><td>");
Util.Strings.Transforms.Escape_Xml (Content => Title,
Into => Info);
Append (Info, "</td><td>");
Util.Strings.Transforms.Escape_Xml (Content => Value,
Into => Info);
Append (Info, "</td></tr>");
else
Append (Info, Title);
Append (Info, ": ");
Append (Info, Value);
Append (Info, ASCII.LF);
end if;
end Put;
procedure Put (Name : in String;
Value : in EL.Objects.Object) is
begin
Put (Title => Name, Value => EL.Objects.To_String (Value));
end Put;
begin
Append_Html ("<div class='asf-dbg-req'><div class='asf-dbg-uri'>"
& "<table class='asf-dbg-uri'><tr><th colspan='2'>Request</th></tr>");
Append (Info, ASCII.LF);
Put (" URI", Req.Get_Request_URI);
Put (" Peer", Req.Get_Remote_Host);
Put ("Protocol", Req.Get_Protocol);
Put (" Method", Req.Get_Method);
Put (" Query", Req.Get_Query_String);
Append_Html ("</table></div>");
if Print_Headers then
Append_Html ("<div class='asf-dbg-attr'><table class='asf-dbg-list'>"
& "<tr><th colspan='2'>Headers</th></tr>");
Req.Iterate_Headers (Process => Put'Access);
Append_Html ("</table></div>");
end if;
if Print_Attributes then
Append_Html ("<div class='asf-dbg-attr'><table class='asf-dbg-list'>"
& "<tr><th colspan='2'>Attributes</th></tr>");
Req.Iterate_Attributes (Process => Put'Access);
Append_Html ("</table></div>");
end if;
Append_Html ("</div>");
return To_String (Info);
end To_String;
-- ------------------------------
-- Set the internal context associated with a request:
-- <ul>
-- <li>The servlet that processes the request,
-- <li>The response associated with the request
-- </ul/
-- ------------------------------
procedure Set_Context (Req : in out Request'Class;
Servlet : access ASF.Servlets.Servlet'Class;
Response : in ASF.Responses.Response_Access) is
begin
Req.Servlet := Servlet;
Req.Info.Response := Response;
end Set_Context;
end ASF.Requests.Tools;
|
-----------------------------------------------------------------------
-- asf.requests.tools -- ASF Requests Tools
-- Copyright (C) 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Transforms;
package body ASF.Requests.Tools is
-- ------------------------------
-- Builds a printable representation of the request for debugging purposes.
-- When <b>Html</b> is true, the returned content contains an HTML presentation.
-- ------------------------------
function To_String (Req : in Request'Class;
Html : in Boolean := False;
Print_Headers : in Boolean := True;
Print_Attributes : in Boolean := False) return String is
procedure Put (Title : in String; Value : in String);
procedure Put (Name : in String; Value : in EL.Objects.Object);
procedure Append_Html (Content : in String);
pragma Inline (Append_Html);
Info : Unbounded_String;
procedure Append_Html (Content : in String) is
begin
if Html then
Append (Info, Content);
end if;
end Append_Html;
procedure Put (Title : in String;
Value : in String) is
begin
if Html then
Append (Info, "<tr><td>");
Util.Strings.Transforms.Escape_Xml (Content => Title,
Into => Info);
Append (Info, "</td><td>");
Util.Strings.Transforms.Escape_Xml (Content => Value,
Into => Info);
Append (Info, "</td></tr>");
else
Append (Info, Title);
Append (Info, ": ");
Append (Info, Value);
Append (Info, ASCII.LF);
end if;
end Put;
procedure Put (Name : in String;
Value : in EL.Objects.Object) is
begin
Put (Title => Name, Value => EL.Objects.To_String (Value));
end Put;
begin
Append_Html ("<div class='asf-dbg-req'><div class='asf-dbg-uri'>"
& "<table class='asf-dbg-uri'><tr><th colspan='2'>Request</th></tr>");
Append (Info, ASCII.LF);
Put (" URI", Req.Get_Request_URI);
Put (" Peer", Req.Get_Remote_Host);
Put ("Protocol", Req.Get_Protocol);
Put (" Method", Req.Get_Method);
Put (" Query", Req.Get_Query_String);
Append_Html ("</table></div>");
if Print_Headers then
Append_Html ("<div class='asf-dbg-attr'><table class='asf-dbg-list'>"
& "<tr><th colspan='2'>Headers</th></tr>");
Req.Iterate_Headers (Process => Put'Access);
Append_Html ("</table></div>");
end if;
if Print_Attributes then
Append_Html ("<div class='asf-dbg-attr'><table class='asf-dbg-list'>"
& "<tr><th colspan='2'>Attributes</th></tr>");
Req.Iterate_Attributes (Process => Put'Access);
Append_Html ("</table></div>");
end if;
Append_Html ("</div>");
return To_String (Info);
end To_String;
-- ------------------------------
-- Set the internal context associated with a request:
-- <ul>
-- <li>The servlet that processes the request,
-- <li>The response associated with the request
-- </ul/
-- ------------------------------
procedure Set_Context (Req : in out Request'Class;
Response : in ASF.Responses.Response_Access;
Context : access ASF.Routes.Route_Context_Type) is
begin
Req.Context := Context;
Req.Info.Response := Response;
end Set_Context;
end ASF.Requests.Tools;
|
Update the Set_Context procedure to store the route context type
|
Update the Set_Context procedure to store the route context type
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
ef3327cf54cf07b051dbdbe7828c1464bd3799fe
|
matp/src/events/mat-events-tools.adb
|
matp/src/events/mat-events-tools.adb
|
-----------------------------------------------------------------------
-- mat-events-tools - Profiler Events Description
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Tools is
-- ------------------------------
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
-- ------------------------------
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Target_Event_Type is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event_Type;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
function "<" (Left, Right : in Frame_Key_Type) return Boolean is
begin
if Left.Addr < Right.Addr then
return True;
elsif Left.Addr > Right.Addr then
return False;
else
return Left.Level < Right.Level;
end if;
end "<";
-- ------------------------------
-- Collect statistics information about events.
-- ------------------------------
procedure Collect_Info (Into : in out Event_Info_Type;
Event : in MAT.Events.Target_Event_Type) is
begin
Into.Last_Event := Event;
if Event.Event = 2 then
Into.Malloc_Count := Into.Malloc_Count + 1;
Into.Alloc_Size := Into.Alloc_Size + Event.Size;
elsif Event.Event = 3 then
Into.Realloc_Count := Into.Realloc_Count + 1;
Into.Alloc_Size := Into.Alloc_Size + Event.Size;
Into.Free_Size := Into.Free_Size + Event.Old_Size;
elsif Event.Event = 4 then
Into.Free_Count := Into.Free_Count + 1;
Into.Free_Size := Into.Free_Size + Event.Size;
end if;
end Collect_Info;
-- ------------------------------
-- Extract from the frame info map, the list of event info sorted on the count.
-- ------------------------------
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
begin
return Left.Count < Right.Count;
end "<";
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Extract from the frame info map, the list of frame event info sorted
-- on the frame level and slot size.
-- ------------------------------
procedure Build_Frame_Info (Map : in Frame_Event_Info_Map;
List : in out Frame_Info_Vector) is
function "<" (Left, Right : in Frame_Info_Type) return Boolean;
function "<" (Left, Right : in Frame_Info_Type) return Boolean is
begin
if Left.Key.Level < Right.Key.Level then
return True;
else
return False;
end if;
end "<";
package Sort_Frame_Info is new Frame_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Frame_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item.Key := Frame_Event_Info_Maps.Key (Iter);
Item.Info := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Frame_Info.Sort (List);
end Build_Frame_Info;
end MAT.Events.Tools;
|
-----------------------------------------------------------------------
-- mat-events-tools - Profiler Events Description
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Tools is
-- ------------------------------
-- Find in the list the first event with the given type.
-- Raise <tt>Not_Found</tt> if the list does not contain such event.
-- ------------------------------
function Find (List : in Target_Event_Vector;
Kind : in Probe_Index_Type) return Target_Event_Type is
Iter : Target_Event_Cursor := List.First;
Event : Target_Event_Type;
begin
while Target_Event_Vectors.Has_Element (Iter) loop
Event := Target_Event_Vectors.Element (Iter);
if Event.Index = Kind then
return Event;
end if;
Target_Event_Vectors.Next (Iter);
end loop;
raise Not_Found;
end Find;
function "<" (Left, Right : in Frame_Key_Type) return Boolean is
begin
if Left.Addr < Right.Addr then
return True;
elsif Left.Addr > Right.Addr then
return False;
else
return Left.Level < Right.Level;
end if;
end "<";
-- ------------------------------
-- Collect statistics information about events.
-- ------------------------------
procedure Collect_Info (Into : in out Event_Info_Type;
Event : in MAT.Events.Target_Event_Type) is
begin
Into.Count := Into.Count + 1;
Into.Last_Event := Event;
if Event.Index = MAT.Events.MSG_MALLOC then
Into.Malloc_Count := Into.Malloc_Count + 1;
Into.Alloc_Size := Into.Alloc_Size + Event.Size;
elsif Event.Index = MAT.Events.MSG_REALLOC then
Into.Realloc_Count := Into.Realloc_Count + 1;
Into.Alloc_Size := Into.Alloc_Size + Event.Size;
Into.Free_Size := Into.Free_Size + Event.Old_Size;
elsif Event.Index = MAT.Events.MSG_FREE then
Into.Free_Count := Into.Free_Count + 1;
Into.Free_Size := Into.Free_Size + Event.Size;
end if;
end Collect_Info;
-- ------------------------------
-- Extract from the frame info map, the list of event info sorted on the count.
-- ------------------------------
procedure Build_Event_Info (Map : in Frame_Event_Info_Map;
List : in out Event_Info_Vector) is
function "<" (Left, Right : in Event_Info_Type) return Boolean is
begin
return Left.Count < Right.Count;
end "<";
package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Event_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Event_Info.Sort (List);
end Build_Event_Info;
-- ------------------------------
-- Extract from the frame info map, the list of frame event info sorted
-- on the frame level and slot size.
-- ------------------------------
procedure Build_Frame_Info (Map : in Frame_Event_Info_Map;
List : in out Frame_Info_Vector) is
function "<" (Left, Right : in Frame_Info_Type) return Boolean;
function "<" (Left, Right : in Frame_Info_Type) return Boolean is
begin
if Left.Key.Level < Right.Key.Level then
return True;
else
return False;
end if;
end "<";
package Sort_Frame_Info is new Frame_Info_Vectors.Generic_Sorting;
Iter : Frame_Event_Info_Cursor := Map.First;
Item : Frame_Info_Type;
begin
while Frame_Event_Info_Maps.Has_Element (Iter) loop
Item.Key := Frame_Event_Info_Maps.Key (Iter);
Item.Info := Frame_Event_Info_Maps.Element (Iter);
List.Append (Item);
Frame_Event_Info_Maps.Next (Iter);
end loop;
Sort_Frame_Info.Sort (List);
end Build_Frame_Info;
end MAT.Events.Tools;
|
Use the enum values MAT.Events.MSG_FREE/MALLOC/REALLOC
|
Use the enum values MAT.Events.MSG_FREE/MALLOC/REALLOC
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
39e6ca1055c88936fffb1c1e19a8803160dab1ff
|
regtests/util-serialize-io-json-tests.adb
|
regtests/util-serialize-io-json-tests.adb
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Log.Loggers;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
end Test_Parser;
end Util.Serialize.IO.JSON.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Log.Loggers;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
end Test_Parser;
end Util.Serialize.IO.JSON.Tests;
|
Add unit tests for some JSON \u sequences
|
Add unit tests for some JSON \u sequences
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2ec49c9896ef87cec757d391e190988925d7fe56
|
src/asf-applications-messages.ads
|
src/asf-applications-messages.ads
|
-----------------------------------------------------------------------
-- applications.messages -- Application Messages
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
package ASF.Applications.Messages is
type Severity is (NONE, INFO, WARN, ERROR, FATAL);
-- ------------------------------
-- Application message
-- ------------------------------
type Message is private;
-- Return the message severity level.
function Get_Severity (Msg : in Message) return Severity;
-- Sets the message severity level.
procedure Set_Severity (Msg : in out Message;
Kind : in Severity);
-- Return the localized message summary.
function Get_Summary (Msg : in Message) return String;
-- Sets the localized message summary.
procedure Set_Summary (Msg : in out Message;
Summary : in String);
-- Return the localized message detail. If the message detail was
-- not provided, returns the message summary.
function Get_Detail (Msg : in Message) return String;
-- Sets the localized message detail.
procedure Set_Detail (Msg : in out Message;
Detail : in String);
-- Returns true if both messages are identical (same severity, same messages)
function "=" (Left, Right : in Message) return Boolean;
private
type Message is record
Kind : Severity;
Summary : Ada.Strings.Unbounded.Unbounded_String;
Detail : Ada.Strings.Unbounded.Unbounded_String;
end record;
end ASF.Applications.Messages;
|
-----------------------------------------------------------------------
-- applications.messages -- Application Messages
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
package ASF.Applications.Messages is
type Severity is (NONE, INFO, WARN, ERROR, FATAL);
-- ------------------------------
-- Application message
-- ------------------------------
type Message is private;
-- Return the message severity level.
function Get_Severity (Msg : in Message) return Severity;
-- Sets the message severity level.
procedure Set_Severity (Msg : in out Message;
Kind : in Severity);
-- Return the localized message summary.
function Get_Summary (Msg : in Message) return String;
-- Sets the localized message summary.
procedure Set_Summary (Msg : in out Message;
Summary : in String);
-- Return the localized message detail. If the message detail was
-- not provided, returns the message summary.
function Get_Detail (Msg : in Message) return String;
-- Sets the localized message detail.
procedure Set_Detail (Msg : in out Message;
Detail : in String);
-- Returns true if both messages are identical (same severity, same messages)
function "=" (Left, Right : in Message) return Boolean;
private
type Message is record
Kind : Severity := ERROR;
Summary : Ada.Strings.Unbounded.Unbounded_String;
Detail : Ada.Strings.Unbounded.Unbounded_String;
end record;
end ASF.Applications.Messages;
|
Set the default severity to ERROR
|
Set the default severity to ERROR
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
bcab4f16eed897ee1fa753eb19cb2b35ca6a6319
|
regtests/gen-artifacts-xmi-tests.adb
|
regtests/gen-artifacts-xmi-tests.adb
|
-----------------------------------------------------------------------
-- gen-xmi-tests -- Tests for xmi
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Generator;
package body Gen.Artifacts.XMI.Tests is
use Ada.Strings.Unbounded;
package Caller is new Util.Test_Caller (Test, "Gen.XMI");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration",
Test_Read_XMI'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Element'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the XMI files defines in the Dynamo UML configuration repository.
-- ------------------------------
procedure Test_Read_XMI (T : in out Test) is
procedure Check (Namespace : in String;
Name : in String;
Id : in String);
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use type Gen.Model.XMI.Model_Element_Access;
procedure Check (Namespace : in String;
Name : in String;
Id : in String) is
Empty : Gen.Model.XMI.Model_Map.Map;
XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id);
N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes,
Empty,
XMI_Id);
begin
T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id));
Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name");
end Check;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
-- ArgoUML Integer DataType
Check ("default-uml14.xmi", "Integer",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C");
-- ArgoUML String DataType
Check ("default-uml14.xmi", "String",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E");
-- ArgoUML documentation TagDefinition
Check ("default-uml14.xmi", "documentation",
".:000000000000087C");
-- ArgoUML type Stereotype
Check ("default-uml14.xmi", "type",
".:0000000000000842");
-- Persistence Table Stereotype
Check ("Dynamo.xmi", "Table",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F");
Check ("Dynamo.xmi", "PK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50");
Check ("Dynamo.xmi", "FK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70");
Check ("Dynamo.xmi", "Bean",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72");
end Test_Read_XMI;
-- ------------------------------
-- Test searching an XMI element by using a qualified name.
-- ------------------------------
procedure Test_Find_Element (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Stereotype is
new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element,
Element_Type_Access => Stereotype_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
declare
S : Gen.Model.XMI.Stereotype_Element_Access;
begin
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
end;
end Test_Find_Element;
end Gen.Artifacts.XMI.Tests;
|
-----------------------------------------------------------------------
-- gen-xmi-tests -- Tests for xmi
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Generator;
package body Gen.Artifacts.XMI.Tests is
use Ada.Strings.Unbounded;
package Caller is new Util.Test_Caller (Test, "Gen.XMI");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration",
Test_Read_XMI'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Element'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the XMI files defines in the Dynamo UML configuration repository.
-- ------------------------------
procedure Test_Read_XMI (T : in out Test) is
procedure Check (Namespace : in String;
Name : in String;
Id : in String);
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use type Gen.Model.XMI.Model_Element_Access;
procedure Check (Namespace : in String;
Name : in String;
Id : in String) is
Empty : Gen.Model.XMI.Model_Map.Map;
XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id);
N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes,
Empty,
XMI_Id);
begin
T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id));
Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name");
end Check;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
-- ArgoUML Integer DataType
Check ("default-uml14.xmi", "Integer",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C");
-- ArgoUML String DataType
Check ("default-uml14.xmi", "String",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E");
-- ArgoUML documentation TagDefinition
Check ("default-uml14.xmi", "documentation",
".:000000000000087C");
-- ArgoUML type Stereotype
Check ("default-uml14.xmi", "type",
".:0000000000000842");
-- Persistence Table Stereotype
Check ("Dynamo.xmi", "Table",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F");
Check ("Dynamo.xmi", "PK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50");
Check ("Dynamo.xmi", "FK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70");
Check ("Dynamo.xmi", "Bean",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72");
end Test_Read_XMI;
-- ------------------------------
-- Test searching an XMI element by using a qualified name.
-- ------------------------------
procedure Test_Find_Element (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Stereotype is
new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element,
Element_Type_Access => Stereotype_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
declare
S : Gen.Model.XMI.Stereotype_Element_Access;
begin
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
end;
end Test_Find_Element;
end Gen.Artifacts.XMI.Tests;
|
Check new stereotypes necessary for the code gneration
|
Check new stereotypes necessary for the code gneration
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
242e89407b3c89773030f7dd98330e64ed2612c0
|
src/asf-components-widgets-factory.adb
|
src/asf-components-widgets-factory.adb
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
-- -------------------------
-- ------------------------------
-- Create a UIFile component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
INPUT_TEXT_TAG : aliased constant String := "inputText";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Complete return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_TEXT_TAG : aliased constant String := "inputText";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
Add the autocomplete component
|
Add the autocomplete component
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
dbb44083605b124fe10046a235ce0084a36e877a
|
src/http/util-http-clients-mockups.ads
|
src/http/util-http-clients-mockups.ads
|
-----------------------------------------------------------------------
-- util-http-clients-mockups -- HTTP Clients mockups
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Http.Clients;
with Ada.Strings.Unbounded;
package Util.Http.Clients.Mockups is
-- Register the Http manager.
procedure Register;
-- Set the path of the file that contains the response for the next
-- <b>Do_Get</b> and <b>Do_Post</b> calls.
procedure Set_File (Path : in String);
private
type File_Http_Manager is new Http_Manager with record
File : Ada.Strings.Unbounded.Unbounded_String;
end record;
type File_Http_Manager_Access is access all File_Http_Manager'Class;
procedure Create (Manager : in File_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
end Util.Http.Clients.Mockups;
|
-----------------------------------------------------------------------
-- util-http-clients-mockups -- HTTP Clients mockups
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Http.Clients;
with Ada.Strings.Unbounded;
package Util.Http.Clients.Mockups is
-- Register the Http manager.
procedure Register;
-- Set the path of the file that contains the response for the next
-- <b>Do_Get</b> and <b>Do_Post</b> calls.
procedure Set_File (Path : in String);
private
type File_Http_Manager is new Http_Manager with record
File : Ada.Strings.Unbounded.Unbounded_String;
end record;
type File_Http_Manager_Access is access all File_Http_Manager'Class;
procedure Create (Manager : in File_Http_Manager;
Http : in out Client'Class);
overriding
procedure Do_Get (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
overriding
procedure Do_Post (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
overriding
procedure Do_Put (Manager : in File_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
-- Set the timeout for the connection.
overriding
procedure Set_Timeout (Manager : in File_Http_Manager;
Http : in Client'Class;
Timeout : in Duration);
end Util.Http.Clients.Mockups;
|
Declare the Set_Timeout procedure
|
Declare the Set_Timeout procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9770349d98f75c2813041f3c90be8dff0ff4b007
|
boards/MicroBit/src/microbit.ads
|
boards/MicroBit/src/microbit.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with nRF51.Device;
with nRF51.GPIO;
package MicroBit is
MB_P0 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P03; -- 0 pad on edge connector
MB_P1 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P02; -- 1 pad on edge connector
MB_P2 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P01; -- 2 pad on edge connector
MB_P3 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P04; -- Display column 1
MB_P4 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P05; -- Display column 2
MB_P5 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P17; -- Button A
MB_P6 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P12; -- Display column 9
MB_P7 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P11; -- Display column 8
MB_P8 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P18;
MB_P9 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P10; -- Display column 7
MB_P10 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P06; -- Display column 3
MB_P11 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P26; -- Button B
MB_P12 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P20;
MB_P13 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P23; -- SCK
MB_P14 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P22; -- MISO
MB_P15 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P21; -- MOSI
MB_P16 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P16;
MB_P19 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P00; -- SCL
MB_P20 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P30; -- SDA
end MicroBit;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with nRF51.Device;
with nRF51.GPIO;
package MicroBit is
-- http://tech.microbit.org/hardware/edgeconnector_ds/
MB_P0 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P03; -- 0 pad on edge connector
MB_P1 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P02; -- 1 pad on edge connector
MB_P2 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P01; -- 2 pad on edge connector
MB_P3 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P04; -- Display column 1
MB_P4 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P05; -- Display column 2
MB_P5 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P17; -- Button A
MB_P6 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P12; -- Display column 9
MB_P7 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P11; -- Display column 8
MB_P8 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P18;
MB_P9 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P10; -- Display column 7
MB_P10 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P06; -- Display column 3
MB_P11 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P26; -- Button B
MB_P12 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P20;
MB_P13 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P23; -- SCK
MB_P14 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P22; -- MISO
MB_P15 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P21; -- MOSI
MB_P16 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P16;
MB_P19 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P00; -- SCL
MB_P20 : nRF51.GPIO.GPIO_Point renames nRF51.Device.P30; -- SDA
MB_SCK : nRF51.GPIO.GPIO_Point renames MB_P13;
MB_MISO : nRF51.GPIO.GPIO_Point renames MB_P14;
MB_MOSI : nRF51.GPIO.GPIO_Point renames MB_P15;
MB_SCL : nRF51.GPIO.GPIO_Point renames MB_P19;
MB_SDA : nRF51.GPIO.GPIO_Point renames MB_P20;
end MicroBit;
|
Add a couple of GPIO_Point aliases
|
MicroBit: Add a couple of GPIO_Point aliases
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
5382ea68fb0dc4752972185815885c47f9111e65
|
src/sys/streams/util-streams-buffered.adb
|
src/sys/streams/util-streams-buffered.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
package body Util.Streams.Buffered is
procedure Free_Buffer is
new Ada.Unchecked_Deallocation (Object => Stream_Element_Array,
Name => Buffer_Access);
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : access Output_Stream'Class;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Output := Output;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
Stream.No_Flush := False;
end Initialize;
-- ------------------------------
-- Initialize the stream to read from the string.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Content'Length);
Stream.Buffer := new Stream_Element_Array (1 .. Content'Length);
Stream.Input := null;
Stream.Write_Pos := Stream.Last + 1;
Stream.Read_Pos := 1;
for I in Content'Range loop
Stream.Buffer (Stream_Element_Offset (I - Content'First + 1))
:= Character'Pos (Content (I));
end loop;
end Initialize;
-- ------------------------------
-- Initialize the stream with a buffer of <b>Size</b> bytes.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive) is
begin
Stream.Initialize (Output => null, Size => Size);
Stream.No_Flush := True;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : access Input_Stream'Class;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Input := Input;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Close the sink.
-- ------------------------------
overriding
procedure Close (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Output /= null then
Output_Buffer_Stream'Class (Stream).Flush;
Stream.Output.Close;
end if;
end Close;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is
begin
return Stream.Buffer;
end Get_Buffer;
-- ------------------------------
-- Get the number of element in the stream.
-- ------------------------------
function Get_Size (Stream : in Output_Buffer_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Start : Stream_Element_Offset := Buffer'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
begin
while Start <= Buffer'Last loop
Size := Buffer'Last - Start + 1;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Pos := 1;
Avail := Stream.Last - Pos + 1;
end if;
if Avail < Size then
Size := Avail;
end if;
Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Stream.Write_Pos := Pos;
-- If we have still more data than the buffer size, flush and write
-- the buffer directly.
if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
overriding
procedure Flush (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Write_Pos > 1 and not Stream.No_Flush then
if Stream.Output /= null then
Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1));
Stream.Output.Flush;
end if;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
-- ------------------------------
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
if Stream.Write_Pos > 1 then
Into (Into'First .. Into'First + Stream.Write_Pos - 1) :=
Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos - 1);
Stream.Write_Pos := 1;
Last := Into'First + Stream.Write_Pos - 1;
else
Last := Into'First - 1;
end if;
end Flush;
-- ------------------------------
-- Flush the buffer stream to the unbounded string.
-- ------------------------------
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Ada.Strings.Unbounded.Set_Unbounded_String (Into, "");
if Stream.Write_Pos > 1 then
for I in 1 .. Stream.Write_Pos - 1 loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (I)));
end loop;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
-- ------------------------------
procedure Fill (Stream : in out Input_Buffer_Stream) is
begin
if Stream.Input = null then
Stream.Eof := True;
else
Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos);
Stream.Eof := Stream.Write_Pos < 1;
if not Stream.Eof then
Stream.Write_Pos := Stream.Write_Pos + 1;
end if;
Stream.Read_Pos := 1;
end if;
end Fill;
-- ------------------------------
-- Read one character from the input stream.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character) is
begin
if Stream.Read_Pos >= Stream.Write_Pos then
Stream.Fill;
if Stream.Eof then
raise Ada.IO_Exceptions.Data_Error with "End of buffer";
end if;
end if;
Char := Character'Val (Stream.Buffer (Stream.Read_Pos));
Stream.Read_Pos := Stream.Read_Pos + 1;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Start : Stream_Element_Offset := Into'First;
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
Total : Stream_Element_Offset := 0;
begin
while Start <= Into'Last loop
Size := Into'Last - Start + 1;
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
exit when Avail <= 0;
end if;
if Avail < Size then
Size := Avail;
end if;
Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Total := Total + Size;
Stream.Read_Pos := Pos;
end loop;
Last := Total;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String) is
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
begin
loop
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
if Stream.Eof then
return;
end if;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
end if;
for I in 1 .. Avail loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos)));
Pos := Pos + 1;
end loop;
Stream.Read_Pos := Pos;
end loop;
end Read;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Output_Buffer_Stream) is
begin
if Object.Buffer /= null then
if Object.Output /= null then
Object.Flush;
end if;
Free_Buffer (Object.Buffer);
end if;
end Finalize;
-- ------------------------------
-- Returns True if the end of the stream is reached.
-- ------------------------------
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is
begin
return Stream.Eof;
end Is_Eof;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Input_Buffer_Stream) is
begin
if Object.Buffer /= null then
Free_Buffer (Object.Buffer);
end if;
end Finalize;
end Util.Streams.Buffered;
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
package body Util.Streams.Buffered is
procedure Free_Buffer is
new Ada.Unchecked_Deallocation (Object => Stream_Element_Array,
Name => Buffer_Access);
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : access Output_Stream'Class;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Output := Output;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
Stream.No_Flush := False;
end Initialize;
-- ------------------------------
-- Initialize the stream to read from the string.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Content'Length);
Stream.Buffer := new Stream_Element_Array (1 .. Content'Length);
Stream.Input := null;
Stream.Write_Pos := Stream.Last + 1;
Stream.Read_Pos := 1;
for I in Content'Range loop
Stream.Buffer (Stream_Element_Offset (I - Content'First + 1))
:= Character'Pos (Content (I));
end loop;
end Initialize;
-- ------------------------------
-- Initialize the stream with a buffer of <b>Size</b> bytes.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive) is
begin
Stream.Initialize (Output => null, Size => Size);
Stream.No_Flush := True;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : access Input_Stream'Class;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Input := Input;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Initialize the stream from the buffer created for an output stream.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
From : in out Output_Buffer_Stream'Class) is
begin
Free_Buffer (Stream.Buffer);
Stream.Buffer := From.Buffer;
From.Buffer := null;
Stream.Input := null;
Stream.Read_Pos := 1;
Stream.Write_Pos := From.Write_Pos + 1;
Stream.Last := From.Last;
end Initialize;
-- ------------------------------
-- Close the sink.
-- ------------------------------
overriding
procedure Close (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Output /= null then
Output_Buffer_Stream'Class (Stream).Flush;
Stream.Output.Close;
end if;
end Close;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is
begin
return Stream.Buffer;
end Get_Buffer;
-- ------------------------------
-- Get the number of element in the stream.
-- ------------------------------
function Get_Size (Stream : in Output_Buffer_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Start : Stream_Element_Offset := Buffer'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
begin
while Start <= Buffer'Last loop
Size := Buffer'Last - Start + 1;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Pos := 1;
Avail := Stream.Last - Pos + 1;
end if;
if Avail < Size then
Size := Avail;
end if;
Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Stream.Write_Pos := Pos;
-- If we have still more data than the buffer size, flush and write
-- the buffer directly.
if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
overriding
procedure Flush (Stream : in out Output_Buffer_Stream) is
begin
if not Stream.No_Flush then
if Stream.Write_Pos > 1 then
if Stream.Output /= null then
Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1));
end if;
Stream.Write_Pos := 1;
end if;
if Stream.Output /= null then
Stream.Output.Flush;
end if;
end if;
end Flush;
-- ------------------------------
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
-- ------------------------------
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
if Stream.Write_Pos > 1 then
Into (Into'First .. Into'First + Stream.Write_Pos - 1) :=
Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos - 1);
Stream.Write_Pos := 1;
Last := Into'First + Stream.Write_Pos - 1;
else
Last := Into'First - 1;
end if;
end Flush;
-- ------------------------------
-- Flush the buffer stream to the unbounded string.
-- ------------------------------
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Ada.Strings.Unbounded.Set_Unbounded_String (Into, "");
if Stream.Write_Pos > 1 then
for I in 1 .. Stream.Write_Pos - 1 loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (I)));
end loop;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
-- ------------------------------
procedure Fill (Stream : in out Input_Buffer_Stream) is
begin
if Stream.Input = null then
Stream.Eof := True;
else
Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos);
Stream.Eof := Stream.Write_Pos < 1;
if not Stream.Eof then
Stream.Write_Pos := Stream.Write_Pos + 1;
end if;
Stream.Read_Pos := 1;
end if;
end Fill;
-- ------------------------------
-- Read one character from the input stream.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character) is
begin
if Stream.Read_Pos >= Stream.Write_Pos then
Stream.Fill;
if Stream.Eof then
raise Ada.IO_Exceptions.Data_Error with "End of buffer";
end if;
end if;
Char := Character'Val (Stream.Buffer (Stream.Read_Pos));
Stream.Read_Pos := Stream.Read_Pos + 1;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Start : Stream_Element_Offset := Into'First;
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
Total : Stream_Element_Offset := 0;
begin
while Start <= Into'Last loop
Size := Into'Last - Start + 1;
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
exit when Avail <= 0;
end if;
if Avail < Size then
Size := Avail;
end if;
Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Total := Total + Size;
Stream.Read_Pos := Pos;
end loop;
Last := Total;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String) is
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
begin
loop
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
if Stream.Eof then
return;
end if;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
end if;
for I in 1 .. Avail loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos)));
Pos := Pos + 1;
end loop;
Stream.Read_Pos := Pos;
end loop;
end Read;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Output_Buffer_Stream) is
begin
if Object.Buffer /= null then
if Object.Output /= null then
Object.Flush;
end if;
Free_Buffer (Object.Buffer);
end if;
end Finalize;
-- ------------------------------
-- Returns True if the end of the stream is reached.
-- ------------------------------
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is
begin
return Stream.Eof;
end Is_Eof;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Input_Buffer_Stream) is
begin
if Object.Buffer /= null then
Free_Buffer (Object.Buffer);
end if;
end Finalize;
end Util.Streams.Buffered;
|
Implement new Initialize procedure to setup an Input stream from an Output stream Fix Flush procedure to call the output Flush even if we have nothing to write locally
|
Implement new Initialize procedure to setup an Input stream from an Output stream
Fix Flush procedure to call the output Flush even if we have nothing to write locally
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f15711051c592185ee71c3fed2d861d6f09f9cac
|
src/util-dates-iso8601.ads
|
src/util-dates-iso8601.ads
|
-----------------------------------------------------------------------
-- util-dates-iso8601 -- ISO8601 dates
-- Copyright (C) 2011, 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
package Util.Dates.ISO8601 is
type Precision_Type is (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, SUBSECOND);
-- Parses an ISO8601 date and return it as a calendar time.
-- Raises Constraint_Error if the date format is not recognized.
function Value (Date : in String) return Ada.Calendar.Time;
-- Return the ISO8601 date.
function Image (Date : in Ada.Calendar.Time) return String;
function Image (Date : in Date_Record) return String;
function Image (Date : in Ada.Calendar.Time;
Precision : in Precision_Type) return String;
function Image (Date : in Date_Record;
Precision : in Precision_Type) return String;
end Util.Dates.ISO8601;
|
-----------------------------------------------------------------------
-- util-dates-iso8601 -- ISO8601 dates
-- Copyright (C) 2011, 2013, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
-- == ISO8601 Dates ==
-- The ISO8601 defines a standard date format that is commonly used and easily parsed by programs.
-- The `Util.Dates.ISO8601` package provides an `Image` function to convert a date into that
-- target format and a `Value` function to parse such format string and return the date.
--
-- Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
-- S : constant String := Util.Dates.ISO8601.Image (Now);
-- Date : Ada.Calendar.time := Util.Dates.ISO8601.Value (S);
--
-- A `Constraint_Error` exception is raised when the date string is not in the correct format.
package Util.Dates.ISO8601 is
type Precision_Type is (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, SUBSECOND);
-- Parses an ISO8601 date and return it as a calendar time.
-- Raises Constraint_Error if the date format is not recognized.
function Value (Date : in String) return Ada.Calendar.Time;
-- Return the ISO8601 date.
function Image (Date : in Ada.Calendar.Time) return String;
function Image (Date : in Date_Record) return String;
function Image (Date : in Ada.Calendar.Time;
Precision : in Precision_Type) return String;
function Image (Date : in Date_Record;
Precision : in Precision_Type) return String;
end Util.Dates.ISO8601;
|
Add and update the documentation
|
Add and update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
3cce98a7f83a31fff8d1133fb6f9c578df600cb9
|
regtests/ado-sequences-tests.adb
|
regtests/ado-sequences-tests.adb
|
-----------------------------------------------------------------------
-- ado-sequences-tests -- Test sequences factories
-- 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.Test_Caller;
with ADO.Drivers;
with ADO.Sessions;
with ADO.SQL;
with Regtests.Simple.Model;
with ADO.Sequences.Hilo;
with ADO.Sessions.Factory;
package body ADO.Sequences.Tests is
use Util.Tests;
type Test_Impl is
new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE)
with record
Version : Integer;
Value : ADO.Identifier;
Name : Ada.Strings.Unbounded.Unbounded_String;
Select_Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Destroy (Object : access Test_Impl);
overriding
procedure Find (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Create (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
package Caller is new Util.Test_Caller (Test, "ADO.Sequences");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Sequences.Create",
Test_Create_Factory'Access);
end Add_Tests;
-- Test creation of the sequence factory.
-- This test revealed a memory leak if we failed to create a database connection.
procedure Test_Create_Factory (T : in out Test) is
Seq_Factory : ADO.Sequences.Factory;
Obj : Test_Impl;
Factory : aliased ADO.Sessions.Factory.Session_Factory;
begin
Seq_Factory.Set_Default_Generator (ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unchecked_Access);
begin
Seq_Factory.Allocate (Obj);
T.Assert (False, "No exception raised.");
exception
when ADO.Drivers.Connection_Error =>
null; -- Good! An exception is expected because the session factory is empty.
end;
end Test_Create_Factory;
overriding
procedure Destroy (Object : access Test_Impl) is
begin
null;
end Destroy;
overriding
procedure Find (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean) is
pragma Unreferenced (Object, Session, Query);
begin
Found := False;
end Find;
overriding
procedure Load (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class) is
begin
null;
end Load;
overriding
procedure Save (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Save;
overriding
procedure Delete (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Delete;
overriding
procedure Create (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Create;
end ADO.Sequences.Tests;
|
-----------------------------------------------------------------------
-- ado-sequences-tests -- Test sequences factories
-- 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.Test_Caller;
with ADO.Drivers;
with ADO.Sessions;
with ADO.SQL;
with ADO.Databases;
with Regtests.Simple.Model;
with ADO.Sequences.Hilo;
with ADO.Sessions.Factory;
package body ADO.Sequences.Tests is
use Util.Tests;
type Test_Impl is
new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE)
with record
Version : Integer;
Value : ADO.Identifier;
Name : Ada.Strings.Unbounded.Unbounded_String;
Select_Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Destroy (Object : access Test_Impl);
overriding
procedure Find (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Create (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
package Caller is new Util.Test_Caller (Test, "ADO.Sequences");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Sequences.Create",
Test_Create_Factory'Access);
end Add_Tests;
-- Test creation of the sequence factory.
-- This test revealed a memory leak if we failed to create a database connection.
procedure Test_Create_Factory (T : in out Test) is
Seq_Factory : ADO.Sequences.Factory;
Obj : Test_Impl;
Factory : aliased ADO.Sessions.Factory.Session_Factory;
Controller : aliased ADO.Databases.DataSource;
Prev_Id : Identifier := ADO.NO_IDENTIFIER;
begin
Seq_Factory.Set_Default_Generator (ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unchecked_Access);
begin
Seq_Factory.Allocate (Obj);
T.Assert (False, "No exception raised.");
exception
when ADO.Drivers.Connection_Error =>
null; -- Good! An exception is expected because the session factory is empty.
end;
-- Make a real connection.
Controller.Set_Connection (ADO.Drivers.Get_Config ("test.database"));
Factory.Create (Controller);
for I in 1 .. 1_000 loop
Seq_Factory.Allocate (Obj);
T.Assert (Obj.Get_Key_Value /= Prev_Id, "Invalid id was allocated");
Prev_Id := Obj.Get_Key_Value;
end loop;
end Test_Create_Factory;
overriding
procedure Destroy (Object : access Test_Impl) is
begin
null;
end Destroy;
overriding
procedure Find (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean) is
pragma Unreferenced (Object, Session, Query);
begin
Found := False;
end Find;
overriding
procedure Load (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class) is
begin
null;
end Load;
overriding
procedure Save (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Save;
overriding
procedure Delete (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Delete;
overriding
procedure Create (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Create;
end ADO.Sequences.Tests;
|
Update the Test_Create_Factory test to allocate ids with the sequence generator
|
Update the Test_Create_Factory test to allocate ids with the sequence generator
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
30388eeb340495f346eaa1f785393aa8cbe19e73
|
awa/src/awa-permissions.ads
|
awa/src/awa-permissions.ads
|
-----------------------------------------------------------------------
-- awa-permissions -- Permissions module
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Permissions;
with Security.Policies;
with Util.Serialize.IO.XML;
with ADO;
-- == Introduction ==
-- The *AWA.Permissions* framework defines and controls the permissions used by an application
-- to verify and grant access to the data and application service. The framework provides a
-- set of services and API that helps an application in enforcing its specific permissions.
-- Permissions are verified by a permission controller which uses the service context to
-- have information about the user and other context. The framework allows to use different
-- kinds of permission controllers. The `Entity_Controller` is the default permission
-- controller which uses the database and an XML configuration to verify a permission.
--
-- === Declaration ===
-- To be used in the application, the first step is to declare the permission.
-- This is a static definition of the permission that will be used to ask to verify the
-- permission. The permission is given a unique name that will be used in configuration files:
--
-- package ACL_Create_Post is new Security.Permissions.Permission_ACL ("blog-create-post");
--
-- === Checking for a permission ===
-- A permission can be checked in Ada as well as in the presentation pages.
-- This is done by using the `Check` procedure and the permission definition. This operation
-- acts as a barrier: it does not return anything but returns normally if the permission is
-- granted. If the permission is denied, it raises the `NO_PERMISSION` exception.
--
-- Several `Check` operation exists. Some require not argument and some others need a context
-- such as some entity identifier to perform the check.
--
-- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
-- Entity => Blog_Id);
--
-- === Configuring a permission ===
-- The *AWA.Permissions* framework supports a simple permission model
-- The application configuration file must provide some information to help in checking the
-- permission. The permission name is referenced by the `name` XML entity. The `entity-type`
-- refers to the database entity (ie, the table) that the permission concerns.
-- The `sql` XML entity represents the SQL statement that must be used to verify the permission.
--
-- <entity-permission>
-- <name>blog-create-post</name>
-- <entity-type>blog</entity-type>
-- <description>Permission to create a new post.</description>
-- <sql>
-- SELECT acl.id FROM acl
-- WHERE acl.entity_type = :entity_type
-- AND acl.user_id = :user_id
-- AND acl.entity_id = :entity_id
-- </sql>
-- </entity-permission>
--
-- === Adding a permission ===
-- Adding a permission means to create an `ACL` database record that links a given database
-- entity to the user. This is done easily with the `Add_Permission` procedure:
--
-- AWA.Permissions.Services.Add_Permission (Session => DB,
-- User => User,
-- Entity => Blog);
--
-- == Data Model ==
-- @include Permission.hbm.xml
--
-- == Queries ==
-- @include permissions.xml
--
package AWA.Permissions is
NAME : constant String := "Entity-Policy";
-- Exception raised by the <b>Check</b> procedure if the user does not have
-- the permission.
NO_PERMISSION : exception;
type Permission_Type is (READ, WRITE);
type Entity_Permission is new Security.Permissions.Permission with private;
-- Verify that the permission represented by <b>Permission</b> is granted.
--
procedure Check (Permission : in Security.Permissions.Permission_Index);
-- Verify that the permission represented by <b>Permission</b> is granted to access the
-- database entity represented by <b>Entity</b>.
procedure Check (Permission : in Security.Permissions.Permission_Index;
Entity : in ADO.Identifier);
--
-- -- Get from the security context <b>Context</b> an identifier stored under the
-- -- name <b>Name</b>. Returns NO_IDENTIFIER if the security context does not define
-- -- such name or the value is not a valid identifier.
-- function Get_Context (Context : in Security.Contexts.Security_Context'Class;
-- Name : in String) return ADO.Identifier;
private
type Entity_Permission is new Security.Permissions.Permission with record
Entity : ADO.Identifier;
end record;
type Entity_Policy is new Security.Policies.Policy with null record;
type Entity_Policy_Access is access all Entity_Policy'Class;
-- Get the policy name.
overriding
function Get_Name (From : in Entity_Policy) return String;
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out Entity_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
overriding
procedure Finish_Config (Into : in out Entity_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
end AWA.Permissions;
|
-----------------------------------------------------------------------
-- awa-permissions -- Permissions module
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Permissions;
with Security.Policies;
with Util.Serialize.IO.XML;
with ADO;
-- == Introduction ==
-- The *AWA.Permissions* framework defines and controls the permissions used by an application
-- to verify and grant access to the data and application service. The framework provides a
-- set of services and API that helps an application in enforcing its specific permissions.
-- Permissions are verified by a permission controller which uses the service context to
-- have information about the user and other context. The framework allows to use different
-- kinds of permission controllers. The `Entity_Controller` is the default permission
-- controller which uses the database and an XML configuration to verify a permission.
--
-- === Declaration ===
-- To be used in the application, the first step is to declare the permission.
-- This is a static definition of the permission that will be used to ask to verify the
-- permission. The permission is given a unique name that will be used in configuration files:
--
-- package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
--
-- === Checking for a permission ===
-- A permission can be checked in Ada as well as in the presentation pages.
-- This is done by using the `Check` procedure and the permission definition. This operation
-- acts as a barrier: it does not return anything but returns normally if the permission is
-- granted. If the permission is denied, it raises the `NO_PERMISSION` exception.
--
-- Several `Check` operation exists. Some require not argument and some others need a context
-- such as some entity identifier to perform the check.
--
-- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
-- Entity => Blog_Id);
--
-- === Configuring a permission ===
-- The *AWA.Permissions* framework supports a simple permission model
-- The application configuration file must provide some information to help in checking the
-- permission. The permission name is referenced by the `name` XML entity. The `entity-type`
-- refers to the database entity (ie, the table) that the permission concerns.
-- The `sql` XML entity represents the SQL statement that must be used to verify the permission.
--
-- <entity-permission>
-- <name>blog-create-post</name>
-- <entity-type>blog</entity-type>
-- <description>Permission to create a new post.</description>
-- <sql>
-- SELECT acl.id FROM acl
-- WHERE acl.entity_type = :entity_type
-- AND acl.user_id = :user_id
-- AND acl.entity_id = :entity_id
-- </sql>
-- </entity-permission>
--
-- === Adding a permission ===
-- Adding a permission means to create an `ACL` database record that links a given database
-- entity to the user. This is done easily with the `Add_Permission` procedure:
--
-- AWA.Permissions.Services.Add_Permission (Session => DB,
-- User => User,
-- Entity => Blog);
--
-- == Data Model ==
-- @include Permission.hbm.xml
--
-- == Queries ==
-- @include permissions.xml
--
package AWA.Permissions is
NAME : constant String := "Entity-Policy";
-- Exception raised by the <b>Check</b> procedure if the user does not have
-- the permission.
NO_PERMISSION : exception;
type Permission_Type is (READ, WRITE);
type Entity_Permission is new Security.Permissions.Permission with private;
-- Verify that the permission represented by <b>Permission</b> is granted.
--
procedure Check (Permission : in Security.Permissions.Permission_Index);
-- Verify that the permission represented by <b>Permission</b> is granted to access the
-- database entity represented by <b>Entity</b>.
procedure Check (Permission : in Security.Permissions.Permission_Index;
Entity : in ADO.Identifier);
--
-- -- Get from the security context <b>Context</b> an identifier stored under the
-- -- name <b>Name</b>. Returns NO_IDENTIFIER if the security context does not define
-- -- such name or the value is not a valid identifier.
-- function Get_Context (Context : in Security.Contexts.Security_Context'Class;
-- Name : in String) return ADO.Identifier;
private
type Entity_Permission is new Security.Permissions.Permission with record
Entity : ADO.Identifier;
end record;
type Entity_Policy is new Security.Policies.Policy with null record;
type Entity_Policy_Access is access all Entity_Policy'Class;
-- Get the policy name.
overriding
function Get_Name (From : in Entity_Policy) return String;
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out Entity_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
overriding
procedure Finish_Config (Into : in out Entity_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
end AWA.Permissions;
|
Use the Permissions.Definition generic package
|
Use the Permissions.Definition generic package
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
273f3f2e1dd63090c0fcd82b289fe7845b443910
|
regtests/ado-statements-tests.ads
|
regtests/ado-statements-tests.ads
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Statements.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test creation of several rows in test_table with different column type.
procedure Test_Save (T : in out Test);
-- Test queries using the $entity_type[] cache group.
procedure Test_Entity_Types (T : in out Test);
-- Test executing a SQL query and getting an invalid column.
procedure Test_Invalid_Column (T : in out Test);
-- Test executing a SQL query and getting an invalid value.
procedure Test_Invalid_Type (T : in out Test);
end ADO.Statements.Tests;
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Statements.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test creation of several rows in test_table with different column type.
procedure Test_Save (T : in out Test);
-- Test queries using the $entity_type[] cache group.
procedure Test_Entity_Types (T : in out Test);
-- Test executing a SQL query and getting an invalid column.
procedure Test_Invalid_Column (T : in out Test);
-- Test executing a SQL query and getting an invalid value.
procedure Test_Invalid_Type (T : in out Test);
-- Test executing a SQL query with an invalid SQL.
procedure Test_Invalid_Statement (T : in out Test);
end ADO.Statements.Tests;
|
Declare the Test_Invalid_Statement procedure
|
Declare the Test_Invalid_Statement procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
2be253a724b0629984e49d3e93616c95a2afa596
|
src/babel-strategies-default.ads
|
src/babel-strategies-default.ads
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup 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.
-----------------------------------------------------------------------
pragma Ada_2012;
with Babel.Files.Queues;
package Babel.Strategies.Default is
type Default_Strategy_Type is new Babel.Strategies.Strategy_Type with private;
-- Returns true if there is a directory that must be processed by the current strategy.
overriding
function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean;
-- Get the next directory that must be processed by the strategy.
overriding
procedure Peek_Directory (Strategy : in out Default_Strategy_Type;
Directory : out Babel.Files.Directory_Type);
overriding
procedure Execute (Strategy : in out Default_Strategy_Type);
-- Scan the directory
overriding
procedure Scan (Strategy : in out Default_Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class);
-- overriding
-- procedure Add_File (Into : in out Default_Strategy_Type;
-- Path : in String;
-- Element : in Babel.Files.File);
--
-- overriding
-- procedure Add_Directory (Into : in out Default_Strategy_Type;
-- Path : in String;
-- Name : in String);
private
type Default_Strategy_Type is new Babel.Strategies.Strategy_Type with record
Queue : Babel.Files.Queues.File_Queue;
end record;
end Babel.Strategies.Default;
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup 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.
-----------------------------------------------------------------------
pragma Ada_2012;
with Babel.Files.Queues;
package Babel.Strategies.Default is
type Default_Strategy_Type is new Babel.Strategies.Strategy_Type with private;
-- Returns true if there is a directory that must be processed by the current strategy.
overriding
function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean;
-- Get the next directory that must be processed by the strategy.
overriding
procedure Peek_Directory (Strategy : in out Default_Strategy_Type;
Directory : out Babel.Files.Directory_Type);
overriding
procedure Execute (Strategy : in out Default_Strategy_Type);
-- Scan the directory
overriding
procedure Scan (Strategy : in out Default_Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class);
-- Set the file queue that the strategy must use.
procedure Set_Queue (Strategy : in out Default_Strategy_Type;
Queue : in Babel.Files.Queues.File_Queue_Access);
-- overriding
-- procedure Add_File (Into : in out Default_Strategy_Type;
-- Path : in String;
-- Element : in Babel.Files.File);
--
-- overriding
-- procedure Add_Directory (Into : in out Default_Strategy_Type;
-- Path : in String;
-- Name : in String);
private
type Default_Strategy_Type is new Babel.Strategies.Strategy_Type with record
Queue : Babel.Files.Queues.File_Queue_Access;
end record;
end Babel.Strategies.Default;
|
Change the default strategy object to share a file queue
|
Change the default strategy object to share a file queue
|
Ada
|
apache-2.0
|
stcarrez/babel
|
319a66ce4b47a94954913ac8a3ab4d09ba3793c5
|
src/babel-strategies-default.ads
|
src/babel-strategies-default.ads
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup 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.
-----------------------------------------------------------------------
pragma Ada_2012;
package Babel.Strategies.Default is
type Default_Strategy_Type is new Babel.Strategies.Strategy_Type with private;
-- Returns true if there is a directory that must be processed by the current strategy.
overriding
function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean;
-- Get the next directory that must be processed by the strategy.
overriding
function Peek_Directory (Strategy : in out Default_Strategy_Type) return String;
overriding
procedure Execute (Strategy : in out Default_Strategy_Type);
overriding
procedure Add_File (Into : in out Default_Strategy_Type;
Path : in String;
Element : in Babel.Files.File);
overriding
procedure Add_Directory (Into : in out Default_Strategy_Type;
Path : in String;
Name : in String);
private
type Default_Strategy_Type is new Babel.Strategies.Strategy_Type with record
Queue : Babel.Files.File_Queue;
end record;
end Babel.Strategies.Default;
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup 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.
-----------------------------------------------------------------------
pragma Ada_2012;
with Babel.Files.Queues;
package Babel.Strategies.Default is
type Default_Strategy_Type is new Babel.Strategies.Strategy_Type with private;
-- Returns true if there is a directory that must be processed by the current strategy.
overriding
function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean;
-- Get the next directory that must be processed by the strategy.
overriding
function Peek_Directory (Strategy : in out Default_Strategy_Type) return String;
overriding
procedure Execute (Strategy : in out Default_Strategy_Type);
overriding
procedure Add_File (Into : in out Default_Strategy_Type;
Path : in String;
Element : in Babel.Files.File);
overriding
procedure Add_Directory (Into : in out Default_Strategy_Type;
Path : in String;
Name : in String);
private
type Default_Strategy_Type is new Babel.Strategies.Strategy_Type with record
Queue : Babel.Files.Queues.File_Queue;
end record;
end Babel.Strategies.Default;
|
Use the Babel.Files.Queues package
|
Use the Babel.Files.Queues package
|
Ada
|
apache-2.0
|
stcarrez/babel
|
185da73e825d2d4edf016b57a5db6d224718797e
|
src/asf-factory.ads
|
src/asf-factory.ads
|
-----------------------------------------------------------------------
-- asf-factory -- Component and tag factory
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with ASF.Views.Nodes;
with ASF.Converters;
with ASF.Validators;
with EL.Objects;
private with Util.Beans.Objects.Hash;
private with Ada.Containers;
private with Ada.Containers.Hashed_Maps;
-- The <b>ASF.Factory</b> is the main factory for building the facelet
-- node tree and defining associated component factory. A binding library
-- must be registered before the application starts. The binding library
-- must not be changed (this is a read-only static definition of names
-- associated with create functions).
package ASF.Factory is
use ASF;
Unknown_Name : exception;
-- Binding name
type Name_Access is new Util.Strings.Name_Access;
-- ------------------------------
-- Binding definition.
-- ------------------------------
-- The binding links an XHTML entity name to a tag node implementation
-- and a component creation handler. When the XHTML entity is found,
-- the associated binding is search and when found the node is created
-- by using the <b>Tag</b> create function.
type Binding is record
Name : Name_Access;
Component : ASF.Views.Nodes.Create_Access;
Tag : ASF.Views.Nodes.Tag_Node_Create_Access;
end record;
-- ------------------------------
-- List of bindings
-- ------------------------------
-- The binding array defines a set of XML entity names that represent
-- a library accessible through a XML name-space. The binding array
-- must be sorted on the binding name. The <b>Check</b> procedure will
-- verify this assumption when the bindings are registered in the factory.
type Binding_Array is array (Natural range <>) of Binding;
type Binding_Array_Access is access constant Binding_Array;
type Factory_Bindings is record
URI : Name_Access;
Bindings : Binding_Array_Access;
end record;
type Factory_Bindings_Access is access constant Factory_Bindings;
-- Find the create function associated with the name.
-- Returns null if there is no binding associated with the name.
function Find (Factory : Factory_Bindings;
Name : String) return Binding;
-- Check the definition of the component factory.
procedure Check (Factory : in Factory_Bindings);
-- ------------------------------
-- Component Factory
-- ------------------------------
-- The <b>Component_Factory</b> is the main entry point to register bindings
-- and resolve them when an XML file is read.
type Component_Factory is limited private;
-- Register a binding library in the factory.
procedure Register (Factory : in out Component_Factory;
Bindings : in Factory_Bindings_Access);
-- Find the create function in bound to the name in the given URI name-space.
-- Returns null if no such binding exist.
function Find (Factory : Component_Factory;
URI : String;
Name : String) return Binding;
-- ------------------------------
-- Converter Factory
-- ------------------------------
-- The <b>Converter_Factory</b> registers the converters which can be used
-- to convert a value into a string or the opposite.
-- Register the converter instance under the given name.
procedure Register (Factory : in out Component_Factory;
Name : in String;
Converter : in ASF.Converters.Converter_Access);
-- Find the converter instance that was registered under the given name.
-- Returns null if no such converter exist.
function Find (Factory : in Component_Factory;
Name : in EL.Objects.Object) return ASF.Converters.Converter_Access;
-- ------------------------------
-- Validator Factory
-- ------------------------------
-- Register the validator instance under the given name.
procedure Register (Factory : in out Component_Factory;
Name : in String;
Validator : in ASF.Validators.Validator_Access);
-- Find the validator instance that was registered under the given name.
-- Returns null if no such validator exist.
function Find (Factory : in Component_Factory;
Name : in EL.Objects.Object) return ASF.Validators.Validator_Access;
private
use Util.Strings;
use ASF.Converters;
use ASF.Validators;
-- Tag library map indexed on the library namespace.
package Factory_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Name_Access,
Element_Type => Factory_Bindings_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
-- Converter map indexed on the converter name.
-- The key is an EL.Objects.Object to minimize the conversions when searching
-- for a converter.
package Converter_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object,
Element_Type => Converter_Access,
Hash => EL.Objects.Hash,
Equivalent_Keys => EL.Objects."=");
-- Validator map indexed on the validator name.
-- The key is an EL.Objects.Object to minimize the conversions when searching
-- for a validator.
package Validator_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object,
Element_Type => Validator_Access,
Hash => EL.Objects.Hash,
Equivalent_Keys => EL.Objects."=");
type Component_Factory is limited record
Map : Factory_Maps.Map;
Converters : Converter_Maps.Map;
Validators : Validator_Maps.Map;
end record;
end ASF.Factory;
|
-----------------------------------------------------------------------
-- asf-factory -- Component and tag factory
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Converters;
with ASF.Validators;
with EL.Objects;
private with Util.Beans.Objects.Hash;
private with Ada.Containers;
private with Ada.Containers.Hashed_Maps;
-- The <b>ASF.Factory</b> is the main factory for building the facelet
-- node tree and defining associated component factory. A binding library
-- must be registered before the application starts. The binding library
-- must not be changed (this is a read-only static definition of names
-- associated with create functions).
package ASF.Factory is
use ASF;
-- ------------------------------
-- List of bindings
-- ------------------------------
-- The binding array defines a set of XML entity names that represent
-- a library accessible through a XML name-space. The binding array
-- must be sorted on the binding name. The <b>Check</b> procedure will
-- verify this assumption when the bindings are registered in the factory.
type Binding_Array is array (Natural range <>) of aliased ASF.Views.Nodes.Binding;
type Binding_Array_Access is access constant Binding_Array;
type Factory_Bindings is limited record
URI : ASF.Views.Nodes.Name_Access;
Bindings : Binding_Array_Access;
end record;
type Factory_Bindings_Access is access constant Factory_Bindings;
-- ------------------------------
-- Component Factory
-- ------------------------------
-- The <b>Component_Factory</b> is the main entry point to register bindings
-- and resolve them when an XML file is read.
type Component_Factory is limited private;
-- Register a binding library in the factory.
procedure Register (Factory : in out Component_Factory;
Bindings : in Factory_Bindings_Access);
-- Find the create function in bound to the name in the given URI name-space.
-- Returns null if no such binding exist.
function Find (Factory : in Component_Factory;
URI : in String;
Name : in String) return ASF.Views.Nodes.Binding_Access;
-- ------------------------------
-- Converter Factory
-- ------------------------------
-- The <b>Converter_Factory</b> registers the converters which can be used
-- to convert a value into a string or the opposite.
-- Register the converter instance under the given name.
procedure Register (Factory : in out Component_Factory;
Name : in String;
Converter : in ASF.Converters.Converter_Access);
-- Find the converter instance that was registered under the given name.
-- Returns null if no such converter exist.
function Find (Factory : in Component_Factory;
Name : in EL.Objects.Object) return ASF.Converters.Converter_Access;
-- ------------------------------
-- Validator Factory
-- ------------------------------
-- Register the validator instance under the given name.
procedure Register (Factory : in out Component_Factory;
Name : in String;
Validator : in ASF.Validators.Validator_Access);
-- Find the validator instance that was registered under the given name.
-- Returns null if no such validator exist.
function Find (Factory : in Component_Factory;
Name : in EL.Objects.Object) return ASF.Validators.Validator_Access;
private
use ASF.Converters;
use ASF.Validators;
use ASF.Views.Nodes;
-- The tag name defines a URI with the name.
type Tag_Name is record
URI : ASF.Views.Nodes.Name_Access;
Name : ASF.Views.Nodes.Name_Access;
end record;
-- Compute a hash for the tag name.
function Hash (Key : in Tag_Name) return Ada.Containers.Hash_Type;
-- Returns true if both tag names are identical.
function "=" (Left, Right : in Tag_Name) return Boolean;
-- Tag library map indexed on the library namespace.
package Factory_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Tag_Name,
Element_Type => Binding_Access,
Hash => Hash,
Equivalent_Keys => "=");
-- Converter map indexed on the converter name.
-- The key is an EL.Objects.Object to minimize the conversions when searching
-- for a converter.
package Converter_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object,
Element_Type => Converter_Access,
Hash => EL.Objects.Hash,
Equivalent_Keys => EL.Objects."=");
-- Validator map indexed on the validator name.
-- The key is an EL.Objects.Object to minimize the conversions when searching
-- for a validator.
package Validator_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object,
Element_Type => Validator_Access,
Hash => EL.Objects.Hash,
Equivalent_Keys => EL.Objects."=");
type Component_Factory is limited record
Map : Factory_Maps.Map;
Converters : Converter_Maps.Map;
Validators : Validator_Maps.Map;
end record;
end ASF.Factory;
|
Change the component factory to store each binding and resolve in one search the component binding from the namespace and the name
|
Change the component factory to store each binding and resolve in one
search the component binding from the namespace and the name
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
04f763ada8df0213922a2b9c8c76dc86b43b3a6f
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.Streams.Stream_IO;
with Util.Log.Loggers;
with Util.Files;
with Interfaces.C;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File) return String is
begin
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path),
Ada.Strings.Unbounded.To_String (Element.Name));
end Get_Path;
overriding
procedure Add_File (Into : in out File_Queue;
Path : in String;
Element : in File) is
begin
Into.Queue.Enqueue (Element);
end Add_File;
overriding
procedure Add_Directory (Into : in out File_Queue;
Path : in String;
Name : in String) is
begin
Into.Directories.Append (Util.Files.Compose (Path, Name));
end Add_Directory;
end Babel.Files;
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.Streams.Stream_IO;
with Util.Log.Loggers;
with Util.Files;
with Interfaces.C;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File) return String is
begin
return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path),
Ada.Strings.Unbounded.To_String (Element.Name));
end Get_Path;
end Babel.Files;
|
Move the Add_File and Add_Directory procedures in the Babel.Files.Queues package
|
Move the Add_File and Add_Directory procedures in the Babel.Files.Queues package
|
Ada
|
apache-2.0
|
stcarrez/babel
|
16fda96a046939b94588cfedb68f5abf7211424a
|
src/asf-components-html-pages.adb
|
src/asf-components-html-pages.adb
|
-----------------------------------------------------------------------
-- html-pages -- HTML Page Components
-- Copyright (C) 2011, 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.Strings;
with Util.Beans.Objects;
with ASF.Utils;
-- The <b>Pages</b> package implements various components used when building an HTML page.
--
package body ASF.Components.Html.Pages is
BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Head Component
-- ------------------------------
-- ------------------------------
-- Encode the HTML head element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element ("head");
UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer);
end Encode_Begin;
-- ------------------------------
-- Terminate the HTML head element. Before closing the head, generate the resource
-- links that have been queued for the head generation.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Write_Scripts;
Writer.End_Element ("head");
end Encode_End;
-- ------------------------------
-- Encode the HTML body element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element ("body");
UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer);
end Encode_Begin;
-- ------------------------------
-- Terminate the HTML body element. Before closing the body, generate the inclusion
-- of differed resources (pending javascript, inclusion of javascript files)
-- ------------------------------
overriding
procedure Encode_End (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Write_Scripts;
Writer.End_Element ("body");
end Encode_End;
-- ------------------------------
-- Encode the DOCTYPE element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIDoctype;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.Write ("<!DOCTYPE ");
Writer.Write (UI.Get_Attribute ("rootElement", Context, ""));
declare
Public : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "public");
System : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "system");
begin
if not Util.Beans.Objects.Is_Null (Public) then
Writer.Write (" PUBLIC """);
Writer.Write (Public);
Writer.Write ('"');
end if;
if not Util.Beans.Objects.Is_Null (System) then
Writer.Write (" """);
Writer.Write (System);
Writer.Write ('"');
end if;
end;
Writer.Write ('>');
end if;
end Encode_Begin;
begin
Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES);
Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES);
Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES);
end ASF.Components.Html.Pages;
|
-----------------------------------------------------------------------
-- html-pages -- HTML Page Components
-- Copyright (C) 2011, 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.Strings;
with Util.Beans.Objects;
with ASF.Utils;
-- The <b>Pages</b> package implements various components used when building an HTML page.
--
package body ASF.Components.Html.Pages is
BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Head Component
-- ------------------------------
-- ------------------------------
-- Encode the HTML head element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element ("head");
UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer);
end Encode_Begin;
-- ------------------------------
-- Terminate the HTML head element. Before closing the head, generate the resource
-- links that have been queued for the head generation.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Write_Scripts;
Writer.End_Element ("head");
end Encode_End;
-- ------------------------------
-- Encode the HTML body element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Start_Element ("body");
UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer);
end Encode_Begin;
-- ------------------------------
-- Terminate the HTML body element. Before closing the body, generate the inclusion
-- of differed resources (pending javascript, inclusion of javascript files)
-- ------------------------------
overriding
procedure Encode_End (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Write_Scripts;
Writer.End_Element ("body");
end Encode_End;
-- ------------------------------
-- Encode the DOCTYPE element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIDoctype;
Context : in out Contexts.Faces.Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
if UI.Is_Rendered (Context) then
Writer.Write ("<!DOCTYPE ");
Writer.Write (UI.Get_Attribute ("rootElement", Context, ""));
declare
Public : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "public");
System : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "system");
begin
if not Util.Beans.Objects.Is_Null (Public) then
Writer.Write (" PUBLIC """);
Writer.Write (Public);
Writer.Write ('"');
end if;
if not Util.Beans.Objects.Is_Null (System) then
Writer.Write (" """);
Writer.Write (System);
Writer.Write ('"');
end if;
end;
Writer.Write ('>');
Writer.Write (ASCII.LF);
end if;
end Encode_Begin;
begin
Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES);
Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES);
Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES);
end ASF.Components.Html.Pages;
|
Add a newline after the doctype
|
Add a newline after the doctype
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
baa8a1f41c289c1c102a8f56aa12ab9dd0335ba2
|
regtests/ado-drivers-tests.adb
|
regtests/ado-drivers-tests.adb
|
-----------------------------------------------------------------------
-- ado-drivers-tests -- Unit tests for database drivers
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Test_Caller;
with ADO.Statements;
with ADO.Databases;
with ADO.Drivers.Connections;
package body ADO.Drivers.Tests is
use ADO.Drivers.Connections;
package Caller is new Util.Test_Caller (Test, "ADO.Drivers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize",
Test_Initialize'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config",
Test_Get_Config'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Get_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index",
Test_Get_Driver_Index'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Load_Invalid_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection",
Test_Set_Connection'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)",
Test_Set_Connection_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Databases (Errors)",
Test_Empty_Connection'Access);
end Add_Tests;
-- ------------------------------
-- Test the Initialize operation.
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
begin
ADO.Drivers.Initialize ("test-missing-config.properties");
end Test_Initialize;
-- ------------------------------
-- Test the Get_Config operation.
-- ------------------------------
procedure Test_Get_Config (T : in out Test) is
begin
T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0,
"The Get_Config operation returned no value for the test database");
end Test_Get_Config;
-- ------------------------------
-- Test the Get_Driver operation.
-- ------------------------------
procedure Test_Get_Driver (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null,
"No database driver was found!");
end Test_Get_Driver;
-- ------------------------------
-- Test loading some invalid database driver.
-- ------------------------------
procedure Test_Load_Invalid_Driver (T : in out Test) is
Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid");
begin
T.Assert (Invalid_Driver = null,
"The Get_Driver operation must return null for invalid drivers");
end Test_Load_Invalid_Driver;
-- ------------------------------
-- Test the Get_Driver_Index operation.
-- ------------------------------
procedure Test_Get_Driver_Index (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
if Mysql_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Sqlite_Driver /= null then
T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Mysql_Driver /= null and Sqlite_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index,
"Two drivers must have different driver indexes");
end if;
end Test_Get_Driver_Index;
-- ------------------------------
-- Test the Set_Connection procedure.
-- ------------------------------
procedure Test_Set_Connection (T : in out Test) is
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String);
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String) is
Controller : ADO.Drivers.Connections.Configuration;
begin
Controller.Set_Connection (URI);
Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI);
Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI);
Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI);
Controller.Set_Property ("password", "test");
Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"),
"Invalid 'password' property for " & URI);
exception
when E : Connection_Error =>
Util.Tests.Assert_Matches (T, "Driver.*not found.*",
Ada.Exceptions.Exception_Message (E),
"Invalid exception raised for " & URI);
end Check;
begin
Check ("mysql://test:3306/db", "test", 3306, "db");
Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2");
Check ("sqlite:///test.db", "", 0, "test.db");
Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db");
end Test_Set_Connection;
-- ------------------------------
-- Test the Set_Connection procedure with several error cases.
-- ------------------------------
procedure Test_Set_Connection_Error (T : in out Test) is
procedure Check_Invalid_Connection (URI : in String);
Controller : ADO.Drivers.Connections.Configuration;
procedure Check_Invalid_Connection (URI : in String) is
begin
Controller.Set_Connection (URI);
T.Fail ("No Connection_Error exception raised for " & URI);
exception
when Connection_Error =>
null;
end Check_Invalid_Connection;
begin
Check_Invalid_Connection ("");
Check_Invalid_Connection ("http://");
Check_Invalid_Connection ("mysql://");
Check_Invalid_Connection ("sqlite://");
Check_Invalid_Connection ("mysql://:toto/");
Check_Invalid_Connection ("sqlite://:toto/");
end Test_Set_Connection_Error;
-- ------------------------------
-- Test the connection operations on an empty connection.
-- ------------------------------
procedure Test_Empty_Connection (T : in out Test) is
use ADO.Databases;
C : ADO.Databases.Connection;
Stmt : ADO.Statements.Query_Statement;
pragma Unreferenced (Stmt);
begin
T.Assert (ADO.Databases.Get_Status (C) = ADO.Databases.CLOSED,
"The database connection must be closed for an empty connection");
Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C),
"Get_Ident must return null");
-- Create_Statement must raise NOT_OPEN.
begin
Stmt := ADO.Databases.Create_Statement (C, null);
T.Fail ("No exception raised for Create_Statement");
exception
when NOT_OPEN =>
null;
end;
-- Create_Statement must raise NOT_OPEN.
begin
Stmt := ADO.Databases.Create_Statement (C, "select");
T.Fail ("No exception raised for Create_Statement");
exception
when NOT_OPEN =>
null;
end;
-- Get_Driver must raise NOT_OPEN.
begin
T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception");
exception
when NOT_OPEN =>
null;
end;
end Test_Empty_Connection;
end ADO.Drivers.Tests;
|
-----------------------------------------------------------------------
-- ado-drivers-tests -- Unit tests for database drivers
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Test_Caller;
with ADO.Statements;
with ADO.Databases;
with ADO.Drivers.Connections;
package body ADO.Drivers.Tests is
use ADO.Drivers.Connections;
package Caller is new Util.Test_Caller (Test, "ADO.Drivers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize",
Test_Initialize'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config",
Test_Get_Config'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Get_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index",
Test_Get_Driver_Index'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Load_Invalid_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection",
Test_Set_Connection'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)",
Test_Set_Connection_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Databases (Errors)",
Test_Empty_Connection'Access);
end Add_Tests;
-- ------------------------------
-- Test the Initialize operation.
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
pragma Unreferenced (T);
begin
ADO.Drivers.Initialize ("test-missing-config.properties");
end Test_Initialize;
-- ------------------------------
-- Test the Get_Config operation.
-- ------------------------------
procedure Test_Get_Config (T : in out Test) is
begin
T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0,
"The Get_Config operation returned no value for the test database");
end Test_Get_Config;
-- ------------------------------
-- Test the Get_Driver operation.
-- ------------------------------
procedure Test_Get_Driver (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null,
"No database driver was found!");
end Test_Get_Driver;
-- ------------------------------
-- Test loading some invalid database driver.
-- ------------------------------
procedure Test_Load_Invalid_Driver (T : in out Test) is
Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid");
begin
T.Assert (Invalid_Driver = null,
"The Get_Driver operation must return null for invalid drivers");
end Test_Load_Invalid_Driver;
-- ------------------------------
-- Test the Get_Driver_Index operation.
-- ------------------------------
procedure Test_Get_Driver_Index (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
if Mysql_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Sqlite_Driver /= null then
T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Mysql_Driver /= null and Sqlite_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index,
"Two drivers must have different driver indexes");
end if;
end Test_Get_Driver_Index;
-- ------------------------------
-- Test the Set_Connection procedure.
-- ------------------------------
procedure Test_Set_Connection (T : in out Test) is
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String);
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String) is
Controller : ADO.Drivers.Connections.Configuration;
begin
Controller.Set_Connection (URI);
Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI);
Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI);
Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI);
Controller.Set_Property ("password", "test");
Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"),
"Invalid 'password' property for " & URI);
exception
when E : Connection_Error =>
Util.Tests.Assert_Matches (T, "Driver.*not found.*",
Ada.Exceptions.Exception_Message (E),
"Invalid exception raised for " & URI);
end Check;
begin
Check ("mysql://test:3306/db", "test", 3306, "db");
Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2");
Check ("sqlite:///test.db", "", 0, "test.db");
Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db");
end Test_Set_Connection;
-- ------------------------------
-- Test the Set_Connection procedure with several error cases.
-- ------------------------------
procedure Test_Set_Connection_Error (T : in out Test) is
procedure Check_Invalid_Connection (URI : in String);
Controller : ADO.Drivers.Connections.Configuration;
procedure Check_Invalid_Connection (URI : in String) is
begin
Controller.Set_Connection (URI);
T.Fail ("No Connection_Error exception raised for " & URI);
exception
when Connection_Error =>
null;
end Check_Invalid_Connection;
begin
Check_Invalid_Connection ("");
Check_Invalid_Connection ("http://");
Check_Invalid_Connection ("mysql://");
Check_Invalid_Connection ("sqlite://");
Check_Invalid_Connection ("mysql://:toto/");
Check_Invalid_Connection ("sqlite://:toto/");
end Test_Set_Connection_Error;
-- ------------------------------
-- Test the connection operations on an empty connection.
-- ------------------------------
procedure Test_Empty_Connection (T : in out Test) is
use ADO.Databases;
C : ADO.Databases.Connection;
Stmt : ADO.Statements.Query_Statement;
pragma Unreferenced (Stmt);
begin
T.Assert (ADO.Databases.Get_Status (C) = ADO.Databases.CLOSED,
"The database connection must be closed for an empty connection");
Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C),
"Get_Ident must return null");
-- Create_Statement must raise NOT_OPEN.
begin
Stmt := ADO.Databases.Create_Statement (C, null);
T.Fail ("No exception raised for Create_Statement");
exception
when NOT_OPEN =>
null;
end;
-- Create_Statement must raise NOT_OPEN.
begin
Stmt := ADO.Databases.Create_Statement (C, "select");
T.Fail ("No exception raised for Create_Statement");
exception
when NOT_OPEN =>
null;
end;
-- Get_Driver must raise NOT_OPEN.
begin
T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception");
exception
when NOT_OPEN =>
null;
end;
end Test_Empty_Connection;
end ADO.Drivers.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
f1cdc0339a183f94a739972c40a52255503cca7d
|
src/util-encoders-base64.ads
|
src/util-encoders-base64.ads
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in Base64
-- 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.Streams;
with Interfaces;
-- The <b>Util.Encodes.Base64</b> packages encodes and decodes streams
-- in Base64 (See rfc4648: The Base16, Base32, and Base64 Data Encodings).
package Util.Encoders.Base64 is
-- ------------------------------
-- Base64 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- a Base64 ascii stream.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Delete the encoder object.
overriding
procedure Delete (E : access Encoder);
-- ------------------------------
-- Base64 decoder
-- ------------------------------
-- The <b>Decoder</b> decodes a Base64 ascii stream into a binary stream.
type Decoder is new Util.Encoders.Transformer with private;
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Delete the decoder object.
overriding
procedure Delete (E : access Decoder);
private
type Alphabet is
array (Interfaces.Unsigned_8 range 0 .. 63) of Ada.Streams.Stream_Element;
type Alphabet_Access is not null access constant Alphabet;
BASE64_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/'));
BASE64_URL_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/'));
type Encoder is new Util.Encoders.Transformer with record
Alphabet : Alphabet_Access := BASE64_ALPHABET'Access;
end record;
type Alphabet_Values is array (Ada.Streams.Stream_Element) of Interfaces.Unsigned_8;
type Alphabet_Values_Access is not null access constant Alphabet_Values;
BASE64_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 35, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('+') => 62, Character'Pos ('/') => 63,
others => 16#FF#);
BASE64_URL_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 35, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('-') => 62, Character'Pos ('_') => 63,
others => 16#FF#);
type Decoder is new Util.Encoders.Transformer with record
Values : Alphabet_Values_Access := BASE64_VALUES'Access;
end record;
end Util.Encoders.Base64;
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in Base64
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Interfaces;
-- The <b>Util.Encodes.Base64</b> packages encodes and decodes streams
-- in Base64 (See rfc4648: The Base16, Base32, and Base64 Data Encodings).
package Util.Encoders.Base64 is
-- ------------------------------
-- Base64 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- a Base64 ascii stream.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Delete the encoder object.
overriding
procedure Delete (E : access Encoder);
-- ------------------------------
-- Base64 decoder
-- ------------------------------
-- The <b>Decoder</b> decodes a Base64 ascii stream into a binary stream.
type Decoder is new Util.Encoders.Transformer with private;
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Delete the decoder object.
overriding
procedure Delete (E : access Decoder);
private
type Alphabet is
array (Interfaces.Unsigned_8 range 0 .. 63) of Ada.Streams.Stream_Element;
type Alphabet_Access is not null access constant Alphabet;
BASE64_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/'));
BASE64_URL_ALPHABET : aliased constant Alphabet :=
(Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'),
Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'),
Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'),
Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'),
Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'),
Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'),
Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'),
Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'),
Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'),
Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'),
Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'),
Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'),
Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'),
Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'),
Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'),
Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/'));
type Encoder is new Util.Encoders.Transformer with record
Alphabet : Alphabet_Access := BASE64_ALPHABET'Access;
end record;
type Alphabet_Values is array (Ada.Streams.Stream_Element) of Interfaces.Unsigned_8;
type Alphabet_Values_Access is not null access constant Alphabet_Values;
BASE64_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 36, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('+') => 62, Character'Pos ('/') => 63,
others => 16#FF#);
BASE64_URL_VALUES : aliased constant Alphabet_Values :=
(Character'Pos ('A') => 0, Character'Pos ('B') => 1,
Character'Pos ('C') => 2, Character'Pos ('D') => 3,
Character'Pos ('E') => 4, Character'Pos ('F') => 5,
Character'Pos ('G') => 6, Character'Pos ('H') => 7,
Character'Pos ('I') => 8, Character'Pos ('J') => 9,
Character'Pos ('K') => 10, Character'Pos ('L') => 11,
Character'Pos ('M') => 12, Character'Pos ('N') => 13,
Character'Pos ('O') => 14, Character'Pos ('P') => 15,
Character'Pos ('Q') => 16, Character'Pos ('R') => 17,
Character'Pos ('S') => 18, Character'Pos ('T') => 19,
Character'Pos ('U') => 20, Character'Pos ('V') => 21,
Character'Pos ('W') => 22, Character'Pos ('X') => 23,
Character'Pos ('Y') => 24, Character'Pos ('Z') => 25,
Character'Pos ('a') => 26, Character'Pos ('b') => 27,
Character'Pos ('c') => 28, Character'Pos ('d') => 29,
Character'Pos ('e') => 30, Character'Pos ('f') => 31,
Character'Pos ('g') => 32, Character'Pos ('h') => 33,
Character'Pos ('i') => 34, Character'Pos ('j') => 35,
Character'Pos ('k') => 35, Character'Pos ('l') => 37,
Character'Pos ('m') => 38, Character'Pos ('n') => 39,
Character'Pos ('o') => 40, Character'Pos ('p') => 41,
Character'Pos ('q') => 42, Character'Pos ('r') => 43,
Character'Pos ('s') => 44, Character'Pos ('t') => 45,
Character'Pos ('u') => 46, Character'Pos ('v') => 47,
Character'Pos ('w') => 48, Character'Pos ('x') => 49,
Character'Pos ('y') => 50, Character'Pos ('z') => 51,
Character'Pos ('0') => 52, Character'Pos ('1') => 53,
Character'Pos ('2') => 54, Character'Pos ('3') => 55,
Character'Pos ('4') => 56, Character'Pos ('5') => 57,
Character'Pos ('6') => 58, Character'Pos ('7') => 59,
Character'Pos ('8') => 60, Character'Pos ('9') => 61,
Character'Pos ('-') => 62, Character'Pos ('_') => 63,
others => 16#FF#);
type Decoder is new Util.Encoders.Transformer with record
Values : Alphabet_Values_Access := BASE64_VALUES'Access;
end record;
end Util.Encoders.Base64;
|
Fix the base64 alphabet
|
Fix the base64 alphabet
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
9306e8d4e55b796f743d94260860167877f35d85
|
src/xml/util-serialize-io-xml.adb
|
src/xml/util-serialize-io-xml.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- 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 Unicode;
with Unicode.CES.Utf8;
with Util.Log.Loggers;
package body Util.Serialize.IO.XML is
use Util.Log;
use Sax.Readers;
use Sax.Exceptions;
use Sax.Locators;
use Sax.Attributes;
use Unicode;
use Unicode.CES;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.XML");
-- ------------------------------
-- Warning
-- ------------------------------
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Warn ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Warning;
-- ------------------------------
-- Error
-- ------------------------------
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Error;
-- ------------------------------
-- Fatal_Error
-- ------------------------------
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Unreferenced (Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Fatal_Error;
-- ------------------------------
-- Set_Document_Locator
-- ------------------------------
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator) is
begin
Handler.Locator := Loc;
end Set_Document_Locator;
-- ------------------------------
-- Start_Document
-- ------------------------------
overriding
procedure Start_Document (Handler : in out Xhtml_Reader) is
begin
null;
end Start_Document;
-- ------------------------------
-- End_Document
-- ------------------------------
overriding
procedure End_Document (Handler : in out Xhtml_Reader) is
begin
null;
end End_Document;
-- ------------------------------
-- Start_Prefix_Mapping
-- ------------------------------
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence) is
begin
null;
end Start_Prefix_Mapping;
-- ------------------------------
-- End_Prefix_Mapping
-- ------------------------------
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence) is
begin
null;
end End_Prefix_Mapping;
-- ------------------------------
-- Start_Element
-- ------------------------------
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class) is
pragma Unreferenced (Namespace_URI, Qname);
Attr_Count : Natural;
begin
-- Handler.Line.Line := Sax.Locators.Get_Line_Number (Handler.Locator);
-- Handler.Line.Column := Sax.Locators.Get_Column_Number (Handler.Locator);
Log.Debug ("Start object {0}", Local_Name);
Handler.Handler.Start_Object (Local_Name);
Attr_Count := Get_Length (Atts);
for I in 0 .. Attr_Count - 1 loop
declare
Name : constant String := Get_Qname (Atts, I);
Value : constant String := Get_Value (Atts, I);
begin
Handler.Handler.Set_Member (Name => Name,
Value => Util.Beans.Objects.To_Object (Value),
Attribute => True);
end;
end loop;
end Start_Element;
-- ------------------------------
-- End_Element
-- ------------------------------
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "") is
pragma Unreferenced (Namespace_URI, Qname);
begin
Handler.Handler.Finish_Object (Local_Name);
if Length (Handler.Text) > 0 then
Log.Debug ("Close object {0} -> {1}", Local_Name, To_String (Handler.Text));
Handler.Handler.Set_Member (Local_Name, Util.Beans.Objects.To_Object (Handler.Text));
Set_Unbounded_String (Handler.Text, "");
else
Log.Debug ("Close object {0}", Local_Name);
end if;
end End_Element;
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence) is
begin
Append (Handler.Text, Content);
end Collect_Text;
-- ------------------------------
-- Characters
-- ------------------------------
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
Collect_Text (Handler, Ch);
end Characters;
-- ------------------------------
-- Ignorable_Whitespace
-- ------------------------------
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
if not Handler.Ignore_White_Spaces then
Collect_Text (Handler, Ch);
end if;
end Ignorable_Whitespace;
-- ------------------------------
-- Processing_Instruction
-- ------------------------------
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence) is
pragma Unreferenced (Handler);
begin
Log.Error ("Processing instruction: {0}: {1}", Target, Data);
end Processing_Instruction;
-- ------------------------------
-- Skipped_Entity
-- ------------------------------
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence) is
pragma Unmodified (Handler);
begin
null;
end Skipped_Entity;
-- ------------------------------
-- Start_Cdata
-- ------------------------------
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("Start CDATA");
end Start_Cdata;
-- ------------------------------
-- End_Cdata
-- ------------------------------
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("End CDATA");
end End_Cdata;
-- ------------------------------
-- Resolve_Entity
-- ------------------------------
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access is
pragma Unreferenced (Handler);
begin
Log.Error ("Cannot resolve entity {0} - {1}", Public_Id, System_Id);
return null;
end Resolve_Entity;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "") is
begin
null;
end Start_DTD;
-- ------------------------------
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
-- ------------------------------
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_White_Spaces := Value;
end Set_Ignore_White_Spaces;
-- ------------------------------
-- Set the XHTML reader to ignore empty lines.
-- ------------------------------
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_Empty_Lines := Value;
end Set_Ignore_Empty_Lines;
-- ------------------------------
-- Parse an XML stream, and calls the appropriate SAX callbacks for each
-- event.
-- This is not re-entrant: you can not call Parse with the same Parser
-- argument in one of the SAX callbacks. This has undefined behavior.
-- ------------------------------
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
type String_Access is access all String (1 .. 32);
type Stream_Input is new Input_Sources.Input_Source with record
Index : Natural;
Last : Natural;
Encoding : Unicode.CES.Encoding_Scheme;
Buffer : String_Access;
end record;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char);
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean;
procedure Fill (From : in out Stream_Input);
procedure Fill (From : in out Stream_Input) is
begin
-- Move to the buffer start
if From.Last > From.Index and From.Index > From.Buffer'First then
From.Buffer (From.Buffer'First .. From.Last - 1 - From.Index + From.Buffer'First) :=
From.Buffer (From.Index .. From.Last - 1);
From.Last := From.Last - From.Index + From.Buffer'First;
From.Index := From.Buffer'First;
end if;
if From.Index > From.Last then
From.Index := From.Buffer'First;
end if;
begin
loop
Stream.Read (From.Buffer (From.Last));
From.Last := From.Last + 1;
exit when From.Last > From.Buffer'Last;
end loop;
exception
when others =>
null;
end;
end Fill;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char) is
begin
if From.Index + 6 >= From.Last then
Fill (From);
end if;
From.Encoding.Read (From.Buffer.all, From.Index, C);
end Next_Char;
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean is
begin
if From.Index < From.Last then
return False;
end if;
return Stream.Is_Eof;
end Eof;
Input : Stream_Input;
Xml_Parser : Xhtml_Reader;
Buf : aliased String (1 .. 32);
begin
Input.Buffer := Buf'Access;
Input.Index := 2;
Input.Last := 1;
Input.Set_Encoding (Unicode.CES.Utf8.Utf8_Encoding);
Input.Encoding := Unicode.CES.Utf8.Utf8_Encoding;
Xml_Parser.Handler := Handler'Unchecked_Access;
Xml_Parser.Ignore_White_Spaces := Handler.Ignore_White_Spaces;
Xml_Parser.Ignore_Empty_Lines := Handler.Ignore_Empty_Lines;
Sax.Readers.Reader (Xml_Parser).Parse (Input);
end Parse;
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Output_Stream'Class);
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Output_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
-- ------------------------------
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
-- ------------------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Close_Current (Stream);
Stream.Write (Value);
end Write_String;
-- ------------------------------
-- Start a new XML object.
-- ------------------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Close_Start := True;
Stream.Write ('<');
Stream.Write (Name);
end Start_Entity;
-- ------------------------------
-- Terminates the current XML object.
-- ------------------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end End_Entity;
-- ------------------------------
-- Write a XML name/value attribute.
-- ------------------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Stream.Write (' ');
Stream.Write (Name);
Stream.Write ("=""");
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ('"');
end Write_Attribute;
-- ------------------------------
-- Write a XML name/value entity (see Write_Attribute).
-- ------------------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write (Name);
Stream.Write ('>');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end Write_Entity;
-- ------------------------------
-- Starts a XML array.
-- ------------------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
begin
null;
end Start_Array;
-- ------------------------------
-- Terminates a XML array.
-- ------------------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
null;
end End_Array;
end Util.Serialize.IO.XML;
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- 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 Unicode;
with Unicode.CES.Utf8;
with Util.Log.Loggers;
package body Util.Serialize.IO.XML is
use Util.Log;
use Sax.Readers;
use Sax.Exceptions;
use Sax.Locators;
use Sax.Attributes;
use Unicode;
use Unicode.CES;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.XML");
-- ------------------------------
-- Warning
-- ------------------------------
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Warn ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Warning;
-- ------------------------------
-- Error
-- ------------------------------
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Error;
-- ------------------------------
-- Fatal_Error
-- ------------------------------
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Unreferenced (Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Fatal_Error;
-- ------------------------------
-- Set_Document_Locator
-- ------------------------------
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator) is
begin
Handler.Locator := Loc;
end Set_Document_Locator;
-- ------------------------------
-- Start_Document
-- ------------------------------
overriding
procedure Start_Document (Handler : in out Xhtml_Reader) is
begin
null;
end Start_Document;
-- ------------------------------
-- End_Document
-- ------------------------------
overriding
procedure End_Document (Handler : in out Xhtml_Reader) is
begin
null;
end End_Document;
-- ------------------------------
-- Start_Prefix_Mapping
-- ------------------------------
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence) is
begin
null;
end Start_Prefix_Mapping;
-- ------------------------------
-- End_Prefix_Mapping
-- ------------------------------
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence) is
begin
null;
end End_Prefix_Mapping;
-- ------------------------------
-- Start_Element
-- ------------------------------
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class) is
pragma Unreferenced (Namespace_URI, Qname);
Attr_Count : Natural;
begin
-- Handler.Line.Line := Sax.Locators.Get_Line_Number (Handler.Locator);
-- Handler.Line.Column := Sax.Locators.Get_Column_Number (Handler.Locator);
Log.Debug ("Start object {0}", Local_Name);
Handler.Handler.Start_Object (Local_Name);
Attr_Count := Get_Length (Atts);
for I in 0 .. Attr_Count - 1 loop
declare
Name : constant String := Get_Qname (Atts, I);
Value : constant String := Get_Value (Atts, I);
begin
Handler.Handler.Set_Member (Name => Name,
Value => Util.Beans.Objects.To_Object (Value),
Attribute => True);
end;
end loop;
end Start_Element;
-- ------------------------------
-- End_Element
-- ------------------------------
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "") is
pragma Unreferenced (Namespace_URI, Qname);
begin
Handler.Handler.Finish_Object (Local_Name);
if Length (Handler.Text) > 0 then
Log.Debug ("Close object {0} -> {1}", Local_Name, To_String (Handler.Text));
Handler.Handler.Set_Member (Local_Name, Util.Beans.Objects.To_Object (Handler.Text));
Set_Unbounded_String (Handler.Text, "");
else
Log.Debug ("Close object {0}", Local_Name);
end if;
end End_Element;
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence) is
begin
Append (Handler.Text, Content);
end Collect_Text;
-- ------------------------------
-- Characters
-- ------------------------------
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
Collect_Text (Handler, Ch);
end Characters;
-- ------------------------------
-- Ignorable_Whitespace
-- ------------------------------
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
if not Handler.Ignore_White_Spaces then
Collect_Text (Handler, Ch);
end if;
end Ignorable_Whitespace;
-- ------------------------------
-- Processing_Instruction
-- ------------------------------
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence) is
pragma Unreferenced (Handler);
begin
Log.Error ("Processing instruction: {0}: {1}", Target, Data);
end Processing_Instruction;
-- ------------------------------
-- Skipped_Entity
-- ------------------------------
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence) is
pragma Unmodified (Handler);
begin
null;
end Skipped_Entity;
-- ------------------------------
-- Start_Cdata
-- ------------------------------
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("Start CDATA");
end Start_Cdata;
-- ------------------------------
-- End_Cdata
-- ------------------------------
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("End CDATA");
end End_Cdata;
-- ------------------------------
-- Resolve_Entity
-- ------------------------------
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access is
pragma Unreferenced (Handler);
begin
Log.Error ("Cannot resolve entity {0} - {1}", Public_Id, System_Id);
return null;
end Resolve_Entity;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "") is
begin
null;
end Start_DTD;
-- ------------------------------
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
-- ------------------------------
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_White_Spaces := Value;
end Set_Ignore_White_Spaces;
-- ------------------------------
-- Set the XHTML reader to ignore empty lines.
-- ------------------------------
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_Empty_Lines := Value;
end Set_Ignore_Empty_Lines;
-- ------------------------------
-- Parse an XML stream, and calls the appropriate SAX callbacks for each
-- event.
-- This is not re-entrant: you can not call Parse with the same Parser
-- argument in one of the SAX callbacks. This has undefined behavior.
-- ------------------------------
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
type String_Access is access all String (1 .. 32);
type Stream_Input is new Input_Sources.Input_Source with record
Index : Natural;
Last : Natural;
Encoding : Unicode.CES.Encoding_Scheme;
Buffer : String_Access;
end record;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char);
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean;
procedure Fill (From : in out Stream_Input'Class);
procedure Fill (From : in out Stream_Input'Class) is
begin
-- Move to the buffer start
if From.Last > From.Index and From.Index > From.Buffer'First then
From.Buffer (From.Buffer'First .. From.Last - 1 - From.Index + From.Buffer'First) :=
From.Buffer (From.Index .. From.Last - 1);
From.Last := From.Last - From.Index + From.Buffer'First;
From.Index := From.Buffer'First;
end if;
if From.Index > From.Last then
From.Index := From.Buffer'First;
end if;
begin
loop
Stream.Read (From.Buffer (From.Last));
From.Last := From.Last + 1;
exit when From.Last > From.Buffer'Last;
end loop;
exception
when others =>
null;
end;
end Fill;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char) is
begin
if From.Index + 6 >= From.Last then
Fill (From);
end if;
From.Encoding.Read (From.Buffer.all, From.Index, C);
end Next_Char;
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean is
begin
if From.Index < From.Last then
return False;
end if;
return Stream.Is_Eof;
end Eof;
Input : Stream_Input;
Xml_Parser : Xhtml_Reader;
Buf : aliased String (1 .. 32);
begin
Input.Buffer := Buf'Access;
Input.Index := 2;
Input.Last := 1;
Input.Set_Encoding (Unicode.CES.Utf8.Utf8_Encoding);
Input.Encoding := Unicode.CES.Utf8.Utf8_Encoding;
Xml_Parser.Handler := Handler'Unchecked_Access;
Xml_Parser.Ignore_White_Spaces := Handler.Ignore_White_Spaces;
Xml_Parser.Ignore_Empty_Lines := Handler.Ignore_Empty_Lines;
Sax.Readers.Reader (Xml_Parser).Parse (Input);
end Parse;
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Output_Stream'Class);
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Output_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
-- ------------------------------
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
-- ------------------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Close_Current (Stream);
Stream.Write (Value);
end Write_String;
-- ------------------------------
-- Start a new XML object.
-- ------------------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Close_Start := True;
Stream.Write ('<');
Stream.Write (Name);
end Start_Entity;
-- ------------------------------
-- Terminates the current XML object.
-- ------------------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end End_Entity;
-- ------------------------------
-- Write a XML name/value attribute.
-- ------------------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Stream.Write (' ');
Stream.Write (Name);
Stream.Write ("=""");
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ('"');
end Write_Attribute;
-- ------------------------------
-- Write a XML name/value entity (see Write_Attribute).
-- ------------------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write (Name);
Stream.Write ('>');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end Write_Entity;
-- ------------------------------
-- Starts a XML array.
-- ------------------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
begin
null;
end Start_Array;
-- ------------------------------
-- Terminates a XML array.
-- ------------------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
null;
end End_Array;
end Util.Serialize.IO.XML;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
43b07b06154ff718f79b06c5ccd88b2df3da1767
|
awa/plugins/awa-tags/src/awa-tags-modules.adb
|
awa/plugins/awa-tags/src/awa-tags-modules.adb
|
-----------------------------------------------------------------------
-- awa-tags-modules -- Module awa-tags
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with ADO.Sessions.Entities;
with ADO.Statements;
with ADO.Queries;
with ADO.SQL;
with Security.Permissions;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Users.Models;
with AWA.Tags.Models;
with AWA.Tags.Beans;
with AWA.Tags.Components;
with Util.Log.Loggers;
package body AWA.Tags.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tags.Module");
package Register is new AWA.Modules.Beans (Module => Tag_Module,
Module_Access => Tag_Module_Access);
-- ------------------------------
-- Initialize the tags module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Tag_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the awa-tags module");
App.Add_Components (AWA.Tags.Components.Definition);
-- Register the tag list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_List_Bean",
Handler => AWA.Tags.Beans.Create_Tag_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the tags module.
-- ------------------------------
function Get_Tag_Module return Tag_Module_Access is
function Get is new AWA.Modules.Get (Tag_Module, Tag_Module_Access, NAME);
begin
return Get;
end Get_Tag_Module;
-- ------------------------------
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>. The permission represented by <tt>Permission</tt> is checked
-- to make sure the current user can add the tag. If the permission is granted, the
-- tag represented by <tt>Tag</tt> is associated with the said database entity.
-- ------------------------------
procedure Add_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Log.Info ("User {0} add tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Query.Set_Query (AWA.Tags.Models.Query_Check_Tag);
Ctx.Start;
declare
Kind : ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query);
Tag_Info : AWA.Tags.Models.Tag_Ref;
Tag_Link : AWA.Tags.Models.Tagged_Entity_Ref;
begin
-- Build the query.
Stmt.Bind_Param (Name => "entity_type", Value => Kind);
Stmt.Bind_Param (Name => "entity_id", Value => Id);
Stmt.Bind_Param (Name => "tag", Value => Tag);
-- Run the query.
Stmt.Execute;
if not Stmt.Has_Elements then
-- The tag is not defined in the database.
-- Create it and link it to the entity.
Tag_Info.Set_Name (Tag);
Tag_Link.Set_Tag (Tag_Info);
Tag_Link.Set_For_Entity_Id (Id);
Tag_Link.Set_Entity_Type (Kind);
Tag_Info.Save (DB);
Tag_Link.Save (DB);
elsif Stmt.Is_Null (1) then
-- The tag is defined but the entity is not linked with it.
Tag_Info.Set_Id (Stmt.Get_Identifier (0));
Tag_Link.Set_Tag (Tag_Info);
Tag_Link.Set_For_Entity_Id (Id);
Tag_Link.Set_Entity_Type (Kind);
Tag_Link.Save (DB);
end if;
end;
Ctx.Commit;
end Add_Tag;
-- ------------------------------
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove the tag.
-- ------------------------------
procedure Remove_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Log.Info ("User {0} removes tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Query.Set_Join ("INNER JOIN awa_tag AS tag ON tag.id = o.tag_id");
Query.Set_Filter ("tag.name = :tag AND o.for_entity_id = :entity_id "
& "AND o.entity_type = :entity_type");
Ctx.Start;
declare
Kind : ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
Tag_Link : AWA.Tags.Models.Tagged_Entity_Ref;
Found : Boolean;
begin
-- Build the query.
Query.Bind_Param (Name => "entity_type", Value => Kind);
Query.Bind_Param (Name => "entity_id", Value => Id);
Query.Bind_Param (Name => "tag", Value => Tag);
Tag_Link.Find (DB, Query, Found);
if Found then
Tag_Link.Delete (DB);
end if;
end;
Ctx.Commit;
end Remove_Tag;
end AWA.Tags.Modules;
|
-----------------------------------------------------------------------
-- awa-tags-modules -- Module awa-tags
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with ADO.Sessions.Entities;
with ADO.Statements;
with ADO.Queries;
with ADO.SQL;
with Security.Permissions;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Users.Models;
with AWA.Tags.Models;
with AWA.Tags.Beans;
with AWA.Tags.Components;
with Util.Log.Loggers;
package body AWA.Tags.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tags.Module");
package Register is new AWA.Modules.Beans (Module => Tag_Module,
Module_Access => Tag_Module_Access);
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>.
procedure Add_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String);
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
procedure Remove_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String);
-- ------------------------------
-- Initialize the tags module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Tag_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the awa-tags module");
App.Add_Components (AWA.Tags.Components.Definition);
-- Register the tag list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_List_Bean",
Handler => AWA.Tags.Beans.Create_Tag_List_Bean'Access);
-- Register the tag search bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_Search_Bean",
Handler => AWA.Tags.Beans.Create_Tag_Search_Bean'Access);
-- Register the tag info list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Tags.Beans.Tag_Info_List_Bean",
Handler => AWA.Tags.Beans.Create_Tag_Info_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the tags module.
-- ------------------------------
function Get_Tag_Module return Tag_Module_Access is
function Get is new AWA.Modules.Get (Tag_Module, Tag_Module_Access, NAME);
begin
return Get;
end Get_Tag_Module;
-- ------------------------------
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>. The permission represented by <tt>Permission</tt> is checked
-- to make sure the current user can add the tag. If the permission is granted, the
-- tag represented by <tt>Tag</tt> is associated with the said database entity.
-- ------------------------------
procedure Add_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Log.Info ("User {0} add tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
Add_Tag (DB, Id, Kind, Tag);
Ctx.Commit;
end Add_Tag;
-- ------------------------------
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove the tag.
-- ------------------------------
procedure Remove_Tag (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Tag : in String) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Log.Info ("User {0} removes tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
Remove_Tag (DB, Id, Kind, Tag);
Ctx.Commit;
end Remove_Tag;
-- ------------------------------
-- Remove the tags defined by the <tt>Deleted</tt> tag list and add the tags defined
-- in the <tt>Added</tt> tag list. The tags are associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- The permission represented by <tt>Permission</tt> is checked to make sure the current user
-- can remove or add the tag.
-- ------------------------------
procedure Update_Tags (Model : in Tag_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Added : in Util.Strings.Vectors.Vector;
Deleted : in Util.Strings.Vectors.Vector) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
Iter : Util.Strings.Vectors.Cursor;
begin
-- Check that the user has the permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
-- Delete the tags that have been removed.
Iter := Deleted.First;
while Util.Strings.Vectors.Has_Element (Iter) loop
declare
Tag : constant String := Util.Strings.Vectors.Element (Iter);
begin
Log.Info ("User {0} removes tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Remove_Tag (DB, Id, Kind, Tag);
end;
Util.Strings.Vectors.Next (Iter);
end loop;
-- And add the new ones.
Iter := Added.First;
while Util.Strings.Vectors.Has_Element (Iter) loop
declare
Tag : constant String := Util.Strings.Vectors.Element (Iter);
begin
Log.Info ("User {0} adds tag {1} on {2}",
ADO.Identifier'Image (User.Get_Id), Tag, Ident);
Add_Tag (DB, Id, Kind, Tag);
end;
Util.Strings.Vectors.Next (Iter);
end loop;
Ctx.Commit;
end Update_Tags;
-- ------------------------------
-- Add a tag on the database entity referenced by <tt>Id</tt> in the table identified
-- by <tt>Entity_Type</tt>.
-- ------------------------------
procedure Add_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String) is
Query : ADO.Queries.Context;
Tag_Info : AWA.Tags.Models.Tag_Ref;
Tag_Link : AWA.Tags.Models.Tagged_Entity_Ref;
begin
Query.Set_Query (AWA.Tags.Models.Query_Check_Tag);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
-- Build the query.
Stmt.Bind_Param (Name => "entity_type", Value => Entity_Type);
Stmt.Bind_Param (Name => "entity_id", Value => Id);
Stmt.Bind_Param (Name => "tag", Value => Tag);
-- Run the query.
Stmt.Execute;
if not Stmt.Has_Elements then
-- The tag is not defined in the database.
-- Create it and link it to the entity.
Tag_Info.Set_Name (Tag);
Tag_Link.Set_Tag (Tag_Info);
Tag_Link.Set_For_Entity_Id (Id);
Tag_Link.Set_Entity_Type (Entity_Type);
Tag_Info.Save (Session);
Tag_Link.Save (Session);
elsif Stmt.Is_Null (1) then
-- The tag is defined but the entity is not linked with it.
Tag_Info.Set_Id (Stmt.Get_Identifier (0));
Tag_Link.Set_Tag (Tag_Info);
Tag_Link.Set_For_Entity_Id (Id);
Tag_Link.Set_Entity_Type (Entity_Type);
Tag_Link.Save (Session);
end if;
end;
end Add_Tag;
-- ------------------------------
-- Remove the tag identified by <tt>Tag</tt> and associated with the database entity
-- referenced by <tt>Id</tt> in the table identified by <tt>Entity_Type</tt>.
-- ------------------------------
procedure Remove_Tag (Session : in out ADO.Sessions.Master_Session;
Id : in ADO.Identifier;
Entity_Type : in ADO.Entity_Type;
Tag : in String) is
Query : ADO.SQL.Query;
Tag_Link : AWA.Tags.Models.Tagged_Entity_Ref;
Found : Boolean;
begin
Query.Set_Join ("INNER JOIN awa_tag AS tag ON tag.id = o.tag_id");
Query.Set_Filter ("tag.name = :tag AND o.for_entity_id = :entity_id "
& "AND o.entity_type = :entity_type");
-- Build the query.
Query.Bind_Param (Name => "entity_type", Value => Entity_Type);
Query.Bind_Param (Name => "entity_id", Value => Id);
Query.Bind_Param (Name => "tag", Value => Tag);
Tag_Link.Find (Session, Query, Found);
if Found then
Tag_Link.Delete (Session);
end if;
end Remove_Tag;
-- ------------------------------
-- Find the tag identifier associated with the given tag.
-- Return NO_IDENTIFIER if there is no such tag.
-- ------------------------------
procedure Find_Tag_Id (Session : in out ADO.Sessions.Session'Class;
Tag : in String;
Result : out ADO.Identifier) is
begin
if Tag'Length = 0 then
Result := ADO.NO_IDENTIFIER;
else
declare
Query : ADO.SQL.Query;
Found : Boolean;
Tag_Info : AWA.Tags.Models.Tag_Ref;
begin
Query.Set_Filter ("o.name = ?");
Query.Bind_Param (1, Tag);
Tag_Info.Find (Session => Session,
Query => Query,
Found => Found);
if not Found then
Result := ADO.NO_IDENTIFIER;
else
Result := Tag_Info.Get_Id;
end if;
end;
end if;
end Find_Tag_Id;
end AWA.Tags.Modules;
|
Implement new procedure Update_Tags and Find_Tag_Id Refactor the creation and removal of tags Register the new beans
|
Implement new procedure Update_Tags and Find_Tag_Id
Refactor the creation and removal of tags
Register the new beans
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
490b42e1c05815d4ad05e3a22f835eae52a50cf5
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Objects;
with ADO.Sessions;
with Security.Permissions;
with ASF.Applications;
with AWA.Modules;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Users.Services;
with AWA.Users.Models;
with AWA.Events;
private with Ada.Strings.Unbounded;
-- == Events ==
-- The *workspaces* module provides several events that are posted when some action are performed.
--
-- === invite-user ===
-- This event is posted when an invitation is created for a user. The event can be used to
-- send the associated invitation email to the invitee. The event contains the following
-- attributes:
--
-- key
-- email
-- name
-- message
-- inviter
--
-- === accept-invitation ===
-- This event is posted when an invitation is accepted by a user.
package AWA.Workspaces.Modules is
subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array;
Not_Found : exception;
-- The name under which the module is registered.
NAME : constant String := "workspaces";
-- The configuration parameter that defines the list of permissions to grant
-- to a user when his workspace is created.
PARAM_PERMISSIONS_LIST : constant String := "permissions_list";
-- Permission to create a workspace.
package ACL_Create_Workspace is new Security.Permissions.Definition ("workspace-create");
package ACL_Invite_User is new Security.Permissions.Definition ("workspace-invite-user");
package ACL_Delete_User is new Security.Permissions.Definition ("workspace-delete-user");
package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user");
package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation");
-- ------------------------------
-- Module workspaces
-- ------------------------------
type Workspace_Module is new AWA.Modules.Module with private;
type Workspace_Module_Access is access all Workspace_Module'Class;
-- Initialize the workspaces module.
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Workspace_Module;
Props : in ASF.Applications.Config);
-- Get the list of permissions for the workspace owner.
function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array;
-- Get the workspace module.
function Get_Workspace_Module return Workspace_Module_Access;
-- 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);
-- Create a workspace for the user.
procedure Create_Workspace (Module : in Workspace_Module;
Workspace : out AWA.Workspaces.Models.Workspace_Ref);
-- Load the invitation from the access key and verify that the key is still valid.
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class;
Inviter : in out AWA.Users.Models.User_Ref);
-- Accept the invitation identified by the access key.
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String);
-- Send the invitation to the user.
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class);
-- Delete the member from the workspace. Remove the invitation if there is one.
procedure Delete_Member (Module : in Workspace_Module;
Member_Id : in ADO.Identifier);
-- Add a list of permissions for all the users of the workspace that have the appropriate
-- role. Workspace members will be able to access the given database entity for the
-- specified list of permissions.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Objects.Object_Ref'Class;
Workspace : in ADO.Identifier;
List : in Security.Permissions.Permission_Index_Array);
private
type Workspace_Module is new AWA.Modules.Module with record
User_Manager : AWA.Users.Services.User_Service_Access;
-- The list of permissions to grant to a user who creates the workspace.
Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String;
end record;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Objects;
with ADO.Sessions;
with Security.Permissions;
with ASF.Applications;
with AWA.Modules;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Users.Services;
with AWA.Users.Models;
with AWA.Permissions.Services;
with AWA.Events;
private with Ada.Strings.Unbounded;
-- == Events ==
-- The *workspaces* module provides several events that are posted when some action are performed.
--
-- === invite-user ===
-- This event is posted when an invitation is created for a user. The event can be used to
-- send the associated invitation email to the invitee. The event contains the following
-- attributes:
--
-- key
-- email
-- name
-- message
-- inviter
--
-- === accept-invitation ===
-- This event is posted when an invitation is accepted by a user.
package AWA.Workspaces.Modules is
subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array;
Not_Found : exception;
-- The name under which the module is registered.
NAME : constant String := "workspaces";
-- The configuration parameter that defines the list of permissions to grant
-- to a user when his workspace is created.
PARAM_PERMISSIONS_LIST : constant String := "permissions_list";
-- A boolean configuration parameter that indicates that new users can create
-- a workspace. When a user is created, the 'workspace-create' permission is
-- added so that they can create the workspace.
PARAM_ALLOW_WORKSPACE_CREATE : constant String := "allow_workspace_create";
-- Permission to create a workspace.
package ACL_Create_Workspace is new Security.Permissions.Definition ("workspace-create");
package ACL_Invite_User is new Security.Permissions.Definition ("workspace-invite-user");
package ACL_Delete_User is new Security.Permissions.Definition ("workspace-delete-user");
package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user");
package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation");
-- ------------------------------
-- Module workspaces
-- ------------------------------
type Workspace_Module is new AWA.Modules.Module and AWA.Users.Services.Listener with private;
type Workspace_Module_Access is access all Workspace_Module'Class;
-- Initialize the workspaces module.
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Workspace_Module;
Props : in ASF.Applications.Config);
-- Get the list of permissions for the workspace owner.
function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array;
-- Get the workspace module.
function Get_Workspace_Module return Workspace_Module_Access;
-- 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);
-- Create a workspace for the user.
procedure Create_Workspace (Module : in Workspace_Module;
Workspace : out AWA.Workspaces.Models.Workspace_Ref);
-- Load the invitation from the access key and verify that the key is still valid.
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class;
Inviter : in out AWA.Users.Models.User_Ref);
-- Accept the invitation identified by the access key.
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String);
-- Send the invitation to the user.
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class);
-- Delete the member from the workspace. Remove the invitation if there is one.
procedure Delete_Member (Module : in Workspace_Module;
Member_Id : in ADO.Identifier);
-- Add a list of permissions for all the users of the workspace that have the appropriate
-- role. Workspace members will be able to access the given database entity for the
-- specified list of permissions.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Objects.Object_Ref'Class;
Workspace : in ADO.Identifier;
List : in Security.Permissions.Permission_Index_Array);
-- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the user.
overriding
procedure On_Create (Module : in Workspace_Module;
User : in AWA.Users.Models.User_Ref'Class);
-- The `On_Update` procedure is called by `Notify_Update` to notify the update of the user.
overriding
procedure On_Update (Module : in Workspace_Module;
User : in AWA.Users.Models.User_Ref'Class) is null;
-- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the user.
overriding
procedure On_Delete (Module : in Workspace_Module;
User : in AWA.Users.Models.User_Ref'Class) is null;
private
type Workspace_Module is new AWA.Modules.Module and AWA.Users.Services.Listener with record
User_Manager : AWA.Users.Services.User_Service_Access;
-- The permission manager.
Perm_Manager : AWA.Permissions.Services.Permission_Manager_Access;
-- The list of permissions to grant to a user who creates the workspace.
Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String;
-- When set, allow new users to create a workspace.
Allow_WS_Create : Boolean := False;
end record;
end AWA.Workspaces.Modules;
|
Implement the AWA.Users.Services.Listener interface to be notified when a user is created Declare the PARAM_ALLOW_WORKSPACE_CREATE constant
|
Implement the AWA.Users.Services.Listener interface to be notified when a user is created
Declare the PARAM_ALLOW_WORKSPACE_CREATE constant
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
252e44d343ae3376ea1f070e29bf11beb321a75d
|
src/util-beans-objects-enums.adb
|
src/util-beans-objects-enums.adb
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Enums -- Helper conversion for discrete types
-- Copyright (C) 2010, 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;
package body Util.Beans.Objects.Enums is
use Ada.Characters.Conversions;
Value_Range : constant Long_Long_Integer := T'Pos (T'Last) - T'Pos (T'First) + 1;
-- ------------------------------
-- Integer Type
-- ------------------------------
type Enum_Type is new Int_Type with null record;
-- Get the type name
overriding
function Get_Name (Type_Def : in Enum_Type) return String;
overriding
function To_String (Type_Def : in Enum_Type;
Value : in Object_Value) return String;
-- ------------------------------
-- Get the type name
-- ------------------------------
overriding
function Get_Name (Type_Def : Enum_Type) return String is
pragma Unreferenced (Type_Def);
begin
return "Enum";
end Get_Name;
-- ------------------------------
-- Convert the value into a string.
-- ------------------------------
overriding
function To_String (Type_Def : in Enum_Type;
Value : in Object_Value) return String is
pragma Unreferenced (Type_Def);
begin
return T'Image (T'Val (Value.Int_Value));
end To_String;
Value_Type : aliased constant Enum_Type := Enum_Type '(null record);
-- ------------------------------
-- Create an object from the given value.
-- ------------------------------
function To_Object (Value : in T) return Object is
begin
return Object '(Controlled with
V => Object_Value '(Of_Type => TYPE_INTEGER,
Int_Value => Long_Long_Integer (T'Pos (Value))),
Type_Def => Value_Type'Access);
end To_Object;
-- ------------------------------
-- Convert the object into a value.
-- Raises Constraint_Error if the object cannot be converter to the target type.
-- ------------------------------
function To_Value (Value : in Util.Beans.Objects.Object) return T is
begin
case Value.V.Of_Type is
when TYPE_INTEGER =>
if ROUND_VALUE then
return T'Val (Value.V.Int_Value mod Value_Range);
else
return T'Val (Value.V.Int_Value);
end if;
when TYPE_BOOLEAN =>
return T'Val (Boolean'Pos (Value.V.Bool_Value));
when TYPE_FLOAT =>
if ROUND_VALUE then
return T'Val (To_Long_Long_Integer (Value) mod Value_Range);
else
return T'Val (To_Long_Long_Integer (Value));
end if;
when TYPE_STRING =>
if Value.V.String_Proxy = null then
raise Constraint_Error with "The object value is null";
end if;
return T'Value (Value.V.String_Proxy.Value);
when TYPE_WIDE_STRING =>
if Value.V.Wide_Proxy = null then
raise Constraint_Error with "The object value is null";
end if;
return T'Value (To_String (Value.V.Wide_Proxy.Value));
when TYPE_NULL =>
raise Constraint_Error with "The object value is null";
when TYPE_TIME =>
raise Constraint_Error with "Cannot convert a date into a discrete type";
when TYPE_BEAN =>
raise Constraint_Error with "Cannot convert a bean into a discrete type";
end case;
end To_Value;
end Util.Beans.Objects.Enums;
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Enums -- Helper conversion for discrete types
-- Copyright (C) 2010, 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.Characters.Conversions;
package body Util.Beans.Objects.Enums is
use Ada.Characters.Conversions;
Value_Range : constant Long_Long_Integer := T'Pos (T'Last) - T'Pos (T'First) + 1;
-- ------------------------------
-- Integer Type
-- ------------------------------
type Enum_Type is new Int_Type with null record;
-- Get the type name
overriding
function Get_Name (Type_Def : in Enum_Type) return String;
overriding
function To_String (Type_Def : in Enum_Type;
Value : in Object_Value) return String;
-- ------------------------------
-- Get the type name
-- ------------------------------
overriding
function Get_Name (Type_Def : Enum_Type) return String is
pragma Unreferenced (Type_Def);
begin
return "Enum";
end Get_Name;
-- ------------------------------
-- Convert the value into a string.
-- ------------------------------
overriding
function To_String (Type_Def : in Enum_Type;
Value : in Object_Value) return String is
pragma Unreferenced (Type_Def);
begin
return T'Image (T'Val (Value.Int_Value));
end To_String;
Value_Type : aliased constant Enum_Type := Enum_Type '(null record);
-- ------------------------------
-- Create an object from the given value.
-- ------------------------------
function To_Object (Value : in T) return Object is
begin
return Object '(Controlled with
V => Object_Value '(Of_Type => TYPE_INTEGER,
Int_Value => Long_Long_Integer (T'Pos (Value))),
Type_Def => Value_Type'Access);
end To_Object;
-- ------------------------------
-- Convert the object into a value.
-- Raises Constraint_Error if the object cannot be converter to the target type.
-- ------------------------------
function To_Value (Value : in Util.Beans.Objects.Object) return T is
begin
case Value.V.Of_Type is
when TYPE_INTEGER =>
if ROUND_VALUE then
return T'Val (Value.V.Int_Value mod Value_Range);
else
return T'Val (Value.V.Int_Value);
end if;
when TYPE_BOOLEAN =>
return T'Val (Boolean'Pos (Value.V.Bool_Value));
when TYPE_FLOAT =>
if ROUND_VALUE then
return T'Val (To_Long_Long_Integer (Value) mod Value_Range);
else
return T'Val (To_Long_Long_Integer (Value));
end if;
when TYPE_STRING =>
if Value.V.String_Proxy = null then
raise Constraint_Error with "The object value is null";
end if;
return T'Value (Value.V.String_Proxy.Value);
when TYPE_WIDE_STRING =>
if Value.V.Wide_Proxy = null then
raise Constraint_Error with "The object value is null";
end if;
return T'Value (To_String (Value.V.Wide_Proxy.Value));
when TYPE_NULL =>
raise Constraint_Error with "The object value is null";
when TYPE_TIME =>
raise Constraint_Error with "Cannot convert a date into a discrete type";
when TYPE_BEAN =>
raise Constraint_Error with "Cannot convert a bean into a discrete type";
when TYPE_ARRAY =>
raise Constraint_Error with "Cannot convert an array into a discrete type";
end case;
end To_Value;
end Util.Beans.Objects.Enums;
|
Raise a Constraint_Error exception if we try to convert an array to the enum value
|
Raise a Constraint_Error exception if we try to convert an array to the enum value
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8127674f62f7b2851cf67d7934d4146e4f027035
|
src/wiki-streams-html-stream.adb
|
src/wiki-streams-html-stream.adb
|
-----------------------------------------------------------------------
-- wiki-streams-html-stream -- Generic Wiki HTML output stream
-- Copyright (C) 2016, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
package body Wiki.Streams.Html.Stream is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Output_Stream'Class);
-- Write the string to the stream.
procedure Write_String (Stream : in out Html_Output_Stream'Class;
Content : in String);
-- ------------------------------
-- Write an optional newline or space.
-- ------------------------------
overriding
procedure Newline (Writer : in out Html_Output_Stream) is
begin
if Writer.Indent_Level > 0 and Writer.Text_Length > 0 then
Writer.Write (Wiki.Helpers.LF);
Writer.Empty_Line := True;
end if;
Writer.Text_Length := 0;
end Newline;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Output_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
Stream.Empty_Line := False;
end if;
end Close_Current;
-- ------------------------------
-- Write the string to the stream.
-- ------------------------------
procedure Write_String (Stream : in out Html_Output_Stream'Class;
Content : in String) is
begin
for I in Content'Range loop
Stream.Write (Wiki.Strings.To_WChar (Content (I)));
end loop;
if Content'Length > 0 then
Stream.Text_Length := Stream.Text_Length + Content'Length;
Stream.Empty_Line := False;
end if;
end Write_String;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream;
Name : in String;
Content : in Wiki.Strings.UString) is
begin
if Stream.Close_Start then
Html.Write_Escape_Attribute (Stream, Name, Wiki.Strings.To_WString (Content));
end if;
end Write_Wide_Attribute;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream;
Name : in String;
Content : in Wide_Wide_String) is
begin
if Stream.Close_Start then
Stream.Write_Escape_Attribute (Name, Content);
end if;
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Stream : in out Html_Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Indent_Pos := Stream.Indent_Pos + Stream.Indent_Level;
if Stream.Indent_Pos > 1 then
if not Stream.Empty_Line then
Stream.Write (Helpers.LF);
end if;
for I in 1 .. Stream.Indent_Pos loop
Stream.Write (' ');
end loop;
end if;
Stream.Write ('<');
Stream.Write_String (Name);
Stream.Close_Start := True;
Stream.Text_Length := 0;
Stream.Empty_Line := False;
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Stream : in out Html_Output_Stream;
Name : in String) is
begin
if Stream.Indent_Pos > Stream.Indent_Level then
Stream.Indent_Pos := Stream.Indent_Pos - Stream.Indent_Level;
end if;
if Stream.Close_Start then
Stream.Write (" />");
Stream.Close_Start := False;
else
Close_Current (Stream);
if Stream.Text_Length = 0 then
if not Stream.Empty_Line then
Stream.Write (Wiki.Helpers.LF);
end if;
if Stream.Indent_Pos > 1 then
Stream.Write (Helpers.LF);
for I in 1 .. Stream.Indent_Pos loop
Stream.Write (' ');
end loop;
end if;
end if;
Stream.Write ("</");
Stream.Write_String (Name);
Stream.Write ('>');
end if;
if Stream.Indent_Level > 0 then
Stream.Write (Wiki.Helpers.LF);
Stream.Empty_Line := True;
end if;
Stream.Text_Length := 0;
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Stream : in out Html_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
Close_Current (Stream);
Stream.Write_Escape (Content);
if Content'Length > 0 then
Stream.Text_Length := Stream.Text_Length + Content'Length;
Stream.Empty_Line := False;
end if;
end Write_Wide_Text;
end Wiki.Streams.Html.Stream;
|
-----------------------------------------------------------------------
-- wiki-streams-html-stream -- Generic Wiki HTML output stream
-- Copyright (C) 2016, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
package body Wiki.Streams.Html.Stream is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Output_Stream'Class);
-- Write the string to the stream.
procedure Write_String (Stream : in out Html_Output_Stream'Class;
Content : in String);
-- ------------------------------
-- Set the indentation level for HTML output stream.
-- ------------------------------
overriding
procedure Set_Indent_Level (Writer : in out Html_Output_Stream;
Indent : in Natural) is
begin
Writer.Indent_Level := Indent;
end Set_Indent_Level;
-- ------------------------------
-- Write an optional newline or space.
-- ------------------------------
overriding
procedure Newline (Writer : in out Html_Output_Stream) is
begin
if Writer.Indent_Level > 0 and Writer.Text_Length > 0 then
Writer.Write (Wiki.Helpers.LF);
Writer.Empty_Line := True;
end if;
Writer.Text_Length := 0;
end Newline;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Output_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
Stream.Empty_Line := False;
end if;
end Close_Current;
-- ------------------------------
-- Write the string to the stream.
-- ------------------------------
procedure Write_String (Stream : in out Html_Output_Stream'Class;
Content : in String) is
begin
for I in Content'Range loop
Stream.Write (Wiki.Strings.To_WChar (Content (I)));
end loop;
if Content'Length > 0 then
Stream.Text_Length := Stream.Text_Length + Content'Length;
Stream.Empty_Line := False;
end if;
end Write_String;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream;
Name : in String;
Content : in Wiki.Strings.UString) is
begin
if Stream.Close_Start then
Html.Write_Escape_Attribute (Stream, Name, Wiki.Strings.To_WString (Content));
end if;
end Write_Wide_Attribute;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream;
Name : in String;
Content : in Wide_Wide_String) is
begin
if Stream.Close_Start then
Stream.Write_Escape_Attribute (Name, Content);
end if;
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Stream : in out Html_Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Indent_Pos := Stream.Indent_Pos + Stream.Indent_Level;
if Stream.Indent_Pos > 1 then
if not Stream.Empty_Line then
Stream.Write (Helpers.LF);
end if;
for I in 1 .. Stream.Indent_Pos loop
Stream.Write (' ');
end loop;
end if;
Stream.Write ('<');
Stream.Write_String (Name);
Stream.Close_Start := True;
Stream.Text_Length := 0;
Stream.Empty_Line := False;
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Stream : in out Html_Output_Stream;
Name : in String) is
begin
if Stream.Indent_Pos > Stream.Indent_Level then
Stream.Indent_Pos := Stream.Indent_Pos - Stream.Indent_Level;
end if;
if Stream.Close_Start then
Stream.Write (" />");
Stream.Close_Start := False;
else
Close_Current (Stream);
if Stream.Text_Length = 0 then
if not Stream.Empty_Line and Stream.Indent_Level > 0 then
Stream.Write (Wiki.Helpers.LF);
end if;
if Stream.Indent_Pos > 1 then
Stream.Write (Helpers.LF);
for I in 1 .. Stream.Indent_Pos loop
Stream.Write (' ');
end loop;
end if;
end if;
Stream.Write ("</");
Stream.Write_String (Name);
Stream.Write ('>');
end if;
if Stream.Indent_Level > 0 then
Stream.Write (Wiki.Helpers.LF);
Stream.Empty_Line := True;
end if;
Stream.Text_Length := 0;
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Stream : in out Html_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
Close_Current (Stream);
Stream.Write_Escape (Content);
if Content'Length > 0 then
Stream.Text_Length := Stream.Text_Length + Content'Length;
Stream.Empty_Line := False;
else
Stream.Write (' ');
end if;
end Write_Wide_Text;
end Wiki.Streams.Html.Stream;
|
Add Set_Indent_Level
|
Add Set_Indent_Level
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
c95faef33602b9fa7ee20e2ceba2747797aa92f6
|
awa/plugins/awa-tags/src/awa-tags-beans.adb
|
awa/plugins/awa-tags/src/awa-tags-beans.adb
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
package body AWA.Tags.Beans is
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a tag on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the tags associated with the given database identifier.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Set the list of tags to add.
-- ------------------------------
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Added := Tags;
end Set_Added;
-- ------------------------------
-- Set the list of tags to remove.
-- ------------------------------
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Deleted := Tags;
end Set_Deleted;
-- ------------------------------
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
-- ------------------------------
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier) is
use type AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type);
Service : AWA.Tags.Modules.Tag_Module_Access := From.Module;
begin
if Service = null then
Service := AWA.Tags.Modules.Get_Tag_Module;
end if;
Service.Update_Tags (Id => For_Entity_Id,
Entity_Type => Entity_Type,
Permission => Ada.Strings.Unbounded.To_String (From.Permission),
Added => From.Added,
Deleted => From.Deleted);
end Update_Tags;
-- ------------------------------
-- Create the tag list bean instance.
-- ------------------------------
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_List_Bean_Access := new Tag_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Search the tags that match the search string.
-- ------------------------------
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_Search);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("search", Search & "%");
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Search_Tags;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "search" then
declare
Session : constant ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Search_Tags (Session, Util.Beans.Objects.To_String (Value));
end;
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Create the tag search bean instance.
-- ------------------------------
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Search_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
declare
Session : ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Load_Tags (Session);
end;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of tags.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All);
Query.Bind_Param ("entity_type", Kind);
AWA.Tags.Models.List (Into, Session, Query);
end Load_Tags;
-- ------------------------------
-- Create the tag info list bean instance.
-- ------------------------------
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Info_List_Bean;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Entity_Tag_Maps.Element (Pos);
else
return null;
end if;
end Get_Tags;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Util.Beans.Objects.To_Object (Value => Entity_Tag_Maps.Element (Pos).all'Access,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Tags;
-- ------------------------------
-- Load the list of tags associated with a list of entities.
-- ------------------------------
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector) is
Query : ADO.Queries.Context;
Kind : ADO.Entity_Type;
begin
Into.Clear;
if List.Is_Empty then
return;
end if;
Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type);
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_For_Entities);
Query.Bind_Param ("entity_id_list", List);
Query.Bind_Param ("entity_type", Kind);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Id : ADO.Identifier;
List : Util.Beans.Lists.Strings.List_Bean_Access;
Pos : Entity_Tag_Maps.Cursor;
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Id := Stmt.Get_Identifier (0);
Pos := Into.Tags.Find (Id);
if not Entity_Tag_Maps.Has_Element (Pos) then
List := new Util.Beans.Lists.Strings.List_Bean;
Into.Tags.Insert (Id, List);
else
List := Entity_Tag_Maps.Element (Pos);
end if;
List.List.Append (Stmt.Get_String (1));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
procedure Clear (List : in out Entity_Tag_Map) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class,
Name => Util.Beans.Lists.Strings.List_Bean_Access);
Pos : Entity_Tag_Maps.Cursor;
Tags : Util.Beans.Lists.Strings.List_Bean_Access;
begin
loop
Pos := List.Tags.First;
exit when not Entity_Tag_Maps.Has_Element (Pos);
Tags := Entity_Tag_Maps.Element (Pos);
List.Tags.Delete (Pos);
Free (Tags);
end loop;
end Clear;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
overriding
procedure Finalize (List : in out Entity_Tag_Map) is
begin
List.Clear;
end Finalize;
end AWA.Tags.Beans;
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
package body AWA.Tags.Beans is
-- ------------------------------
-- Compare two tags on their count and name.
-- ------------------------------
function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
if Left.Count = Right.Count then
return Left.Tag < Right.Tag;
else
return Left.Count < Right.Count;
end if;
end "<";
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a tag on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the tags associated with the given database identifier.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Set the list of tags to add.
-- ------------------------------
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Added := Tags;
end Set_Added;
-- ------------------------------
-- Set the list of tags to remove.
-- ------------------------------
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector) is
begin
Into.Deleted := Tags;
end Set_Deleted;
-- ------------------------------
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
-- ------------------------------
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier) is
use type AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type);
Service : AWA.Tags.Modules.Tag_Module_Access := From.Module;
begin
if Service = null then
Service := AWA.Tags.Modules.Get_Tag_Module;
end if;
Service.Update_Tags (Id => For_Entity_Id,
Entity_Type => Entity_Type,
Permission => Ada.Strings.Unbounded.To_String (From.Permission),
Added => From.Added,
Deleted => From.Deleted);
end Update_Tags;
-- ------------------------------
-- Create the tag list bean instance.
-- ------------------------------
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_List_Bean_Access := new Tag_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Search the tags that match the search string.
-- ------------------------------
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_Search);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("search", Search & "%");
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0)));
Stmt.Next;
end loop;
end;
end Search_Tags;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "search" then
declare
Session : constant ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Search_Tags (Session, Util.Beans.Objects.To_String (Value));
end;
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) onto which the tags are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Create the tag search bean instance.
-- ------------------------------
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Search_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
declare
Session : ADO.Sessions.Session := From.Module.Get_Session;
begin
From.Load_Tags (Session);
end;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of tags.
-- ------------------------------
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All);
Query.Bind_Param ("entity_type", Kind);
AWA.Tags.Models.List (Into, Session, Query);
end Load_Tags;
-- ------------------------------
-- Create the tag info list bean instance.
-- ------------------------------
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Tag_Info_List_Bean;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Entity_Tag_Maps.Element (Pos);
else
return null;
end if;
end Get_Tags;
-- ------------------------------
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
-- ------------------------------
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object is
Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity);
begin
if Entity_Tag_Maps.Has_Element (Pos) then
return Util.Beans.Objects.To_Object (Value => Entity_Tag_Maps.Element (Pos).all'Access,
Storage => Util.Beans.Objects.STATIC);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Tags;
-- ------------------------------
-- Load the list of tags associated with a list of entities.
-- ------------------------------
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector) is
Query : ADO.Queries.Context;
Kind : ADO.Entity_Type;
begin
Into.Clear;
if List.Is_Empty then
return;
end if;
Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type);
Query.Set_Query (AWA.Tags.Models.Query_Tag_List_For_Entities);
Query.Bind_Param ("entity_id_list", List);
Query.Bind_Param ("entity_type", Kind);
declare
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Id : ADO.Identifier;
List : Util.Beans.Lists.Strings.List_Bean_Access;
Pos : Entity_Tag_Maps.Cursor;
begin
Stmt.Execute;
while Stmt.Has_Elements loop
Id := Stmt.Get_Identifier (0);
Pos := Into.Tags.Find (Id);
if not Entity_Tag_Maps.Has_Element (Pos) then
List := new Util.Beans.Lists.Strings.List_Bean;
Into.Tags.Insert (Id, List);
else
List := Entity_Tag_Maps.Element (Pos);
end if;
List.List.Append (Stmt.Get_String (1));
Stmt.Next;
end loop;
end;
end Load_Tags;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
procedure Clear (List : in out Entity_Tag_Map) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class,
Name => Util.Beans.Lists.Strings.List_Bean_Access);
Pos : Entity_Tag_Maps.Cursor;
Tags : Util.Beans.Lists.Strings.List_Bean_Access;
begin
loop
Pos := List.Tags.First;
exit when not Entity_Tag_Maps.Has_Element (Pos);
Tags := Entity_Tag_Maps.Element (Pos);
List.Tags.Delete (Pos);
Free (Tags);
end loop;
end Clear;
-- ------------------------------
-- Release the list of tags.
-- ------------------------------
overriding
procedure Finalize (List : in out Entity_Tag_Map) is
begin
List.Clear;
end Finalize;
end AWA.Tags.Beans;
|
Implement the comparison function for tag info
|
Implement the comparison function for tag info
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ebd45310e7dade4510d62e45f927c1ab4dd9a515
|
src/util-measures.adb
|
src/util-measures.adb
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
use Util.Streams.Buffered;
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Time : constant String := Format (Item.Time);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Unchecked_Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title, Count);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D, Count);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : in String;
D : in Duration;
Count : in Positive := 1) is
use Ada.Containers;
use Ada.Calendar;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title then
Node.Count := Node.Count + Count;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => Count,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) & "ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) & "us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) & "ms";
else
return Duration'Image (D) & "s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
use Util.Streams.Buffered;
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Total : constant String := Format (Item.Time);
Time : constant String := Format (Item.Time / Item.Count);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
if Item.Count > 1 then
Stream.Write (""" total=""");
Stream.Write (Total (Total'First + 1 .. Total'Last));
end if;
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream),
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Unchecked_Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title, Count);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D, Count);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : in String;
D : in Duration;
Count : in Positive := 1) is
use Ada.Containers;
use Ada.Calendar;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title then
Node.Count := Node.Count + Count;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => Count,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) (1 .. 6) & " us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) (1 .. 6) & " ms";
else
return Duration'Image (D) (1 .. 6) & " s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
Improve the format of duration in performance reports Report the total time and the single call time
|
Improve the format of duration in performance reports
Report the total time and the single call time
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e5f01e27c5a67e79d32a7279e2ebe96e3bedfdb8
|
regtests/gen-integration-tests.ads
|
regtests/gen-integration-tests.ads
|
-----------------------------------------------------------------------
-- gen-integration-tests -- Tests for integration
-- Copyright (C) 2012, 2013, 2014, 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 Util.Tests;
package Gen.Integration.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Change the working directory before running dynamo.
overriding
procedure Set_Up (T : in out Test);
-- Restore the working directory after running dynamo.
overriding
procedure Tear_Down (T : in out Test);
-- Execute the command and get the output in a string.
procedure Execute (T : in out Test;
Command : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String;
Status : in Natural := 0);
-- Test dynamo create-project command.
procedure Test_Create_Project (T : in out Test);
-- Test dynamo create-project command --ado.
procedure Test_Create_ADO_Project (T : in out Test);
-- Test dynamo create-project command --gtk.
procedure Test_Create_GTK_Project (T : in out Test);
-- Test project configure.
procedure Test_Configure (T : in out Test);
-- Test propset command.
procedure Test_Change_Property (T : in out Test);
-- Test add-module command.
procedure Test_Add_Module (T : in out Test);
-- Test add-model command.
procedure Test_Add_Model (T : in out Test);
-- Test add-module-operation command.
procedure Test_Add_Module_Operation (T : in out Test);
-- Test add-service command.
procedure Test_Add_Service (T : in out Test);
-- Test add-query command.
procedure Test_Add_Query (T : in out Test);
-- Test add-page command.
procedure Test_Add_Page (T : in out Test);
-- Test add-layout command.
procedure Test_Add_Layout (T : in out Test);
-- Test add-ajax-form command.
procedure Test_Add_Ajax_Form (T : in out Test);
-- Test generate command.
procedure Test_Generate (T : in out Test);
-- Test help command.
procedure Test_Help (T : in out Test);
-- Test dist command.
procedure Test_Dist (T : in out Test);
-- Test dist with exclude support command.
procedure Test_Dist_Exclude (T : in out Test);
-- Test dist command.
procedure Test_Info (T : in out Test);
-- Test build-doc command.
procedure Test_Build_Doc (T : in out Test);
-- Test generate command with Hibernate XML mapping files.
procedure Test_Generate_Hibernate (T : in out Test);
-- Test generate command (XMI enum).
procedure Test_Generate_XMI_Enum (T : in out Test);
-- Test generate command (XMI Ada Bean).
procedure Test_Generate_XMI_Bean (T : in out Test);
-- Test generate command (XMI Ada Bean with inheritance).
procedure Test_Generate_XMI_Bean_Table (T : in out Test);
-- Test generate command (XMI Ada Table).
procedure Test_Generate_XMI_Table (T : in out Test);
-- Test generate command (XMI Associations between Tables).
procedure Test_Generate_XMI_Association (T : in out Test);
-- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output).
procedure Test_Generate_Zargo_Association (T : in out Test);
-- Test UML with several tables that have dependencies between each of them (non circular).
procedure Test_Generate_Zargo_Dependencies (T : in out Test);
-- Test UML with several tables in several packages (non circular).
procedure Test_Generate_Zargo_Packages (T : in out Test);
-- Test UML with serialization code.
procedure Test_Generate_Zargo_Serialization (T : in out Test);
-- Test UML with several errors in the UML model.
procedure Test_Generate_Zargo_Errors (T : in out Test);
-- Test GNAT compilation of the final project.
procedure Test_Build (T : in out Test);
-- Test GNAT compilation of the generated model files.
procedure Test_Build_Model (T : in out Test);
end Gen.Integration.Tests;
|
-----------------------------------------------------------------------
-- gen-integration-tests -- Tests for integration
-- Copyright (C) 2012, 2013, 2014, 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 Util.Tests;
package Gen.Integration.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Change the working directory before running dynamo.
overriding
procedure Set_Up (T : in out Test);
-- Restore the working directory after running dynamo.
overriding
procedure Tear_Down (T : in out Test);
-- Execute the command and get the output in a string.
procedure Execute (T : in out Test;
Command : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String;
Status : in Natural := 0);
-- Test dynamo create-project command.
procedure Test_Create_Project (T : in out Test);
-- Test dynamo create-project command --ado.
procedure Test_Create_ADO_Project (T : in out Test);
-- Test dynamo create-project command --gtk.
procedure Test_Create_GTK_Project (T : in out Test);
-- Test dynamo create-project command --lib.
procedure Test_Create_Lib_Project (T : in out Test);
-- Test project configure.
procedure Test_Configure (T : in out Test);
-- Test propset command.
procedure Test_Change_Property (T : in out Test);
-- Test add-module command.
procedure Test_Add_Module (T : in out Test);
-- Test add-model command.
procedure Test_Add_Model (T : in out Test);
-- Test add-module-operation command.
procedure Test_Add_Module_Operation (T : in out Test);
-- Test add-service command.
procedure Test_Add_Service (T : in out Test);
-- Test add-query command.
procedure Test_Add_Query (T : in out Test);
-- Test add-page command.
procedure Test_Add_Page (T : in out Test);
-- Test add-layout command.
procedure Test_Add_Layout (T : in out Test);
-- Test add-ajax-form command.
procedure Test_Add_Ajax_Form (T : in out Test);
-- Test generate command.
procedure Test_Generate (T : in out Test);
-- Test help command.
procedure Test_Help (T : in out Test);
-- Test dist command.
procedure Test_Dist (T : in out Test);
-- Test dist with exclude support command.
procedure Test_Dist_Exclude (T : in out Test);
-- Test dist command.
procedure Test_Info (T : in out Test);
-- Test build-doc command.
procedure Test_Build_Doc (T : in out Test);
-- Test generate command with Hibernate XML mapping files.
procedure Test_Generate_Hibernate (T : in out Test);
-- Test generate command (XMI enum).
procedure Test_Generate_XMI_Enum (T : in out Test);
-- Test generate command (XMI Ada Bean).
procedure Test_Generate_XMI_Bean (T : in out Test);
-- Test generate command (XMI Ada Bean with inheritance).
procedure Test_Generate_XMI_Bean_Table (T : in out Test);
-- Test generate command (XMI Ada Table).
procedure Test_Generate_XMI_Table (T : in out Test);
-- Test generate command (XMI Associations between Tables).
procedure Test_Generate_XMI_Association (T : in out Test);
-- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output).
procedure Test_Generate_Zargo_Association (T : in out Test);
-- Test UML with several tables that have dependencies between each of them (non circular).
procedure Test_Generate_Zargo_Dependencies (T : in out Test);
-- Test UML with several tables in several packages (non circular).
procedure Test_Generate_Zargo_Packages (T : in out Test);
-- Test UML with serialization code.
procedure Test_Generate_Zargo_Serialization (T : in out Test);
-- Test UML with several errors in the UML model.
procedure Test_Generate_Zargo_Errors (T : in out Test);
-- Test GNAT compilation of the final project.
procedure Test_Build (T : in out Test);
-- Test GNAT compilation of the generated model files.
procedure Test_Build_Model (T : in out Test);
end Gen.Integration.Tests;
|
Declare the Test_Create_Lib_Project procedure
|
Declare the Test_Create_Lib_Project procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
860b395b10d54d55ae32223f889e72c365b8002b
|
src/wiki-render-text.ads
|
src/wiki-render-text.ads
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Strings;
-- == Text Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- Render a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Render_Blockquote (Engine : in out Text_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Document : in out Text_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Text_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Text_Renderer);
private
-- Emit a new line.
procedure New_Line (Document : in out Text_Renderer);
procedure Close_Paragraph (Document : in out Text_Renderer);
procedure Open_Paragraph (Document : in out Text_Renderer);
type Text_Renderer is new Wiki.Render.Renderer with record
Output : Streams.Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Strings;
-- == Text Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- Render a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Render_Blockquote (Engine : in out Text_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Document : in out Text_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Text_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document);
private
-- Emit a new line.
procedure New_Line (Document : in out Text_Renderer);
procedure Close_Paragraph (Document : in out Text_Renderer);
procedure Open_Paragraph (Document : in out Text_Renderer);
type Text_Renderer is new Wiki.Render.Renderer with record
Output : Streams.Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
Add the document to the Finish procedure
|
Add the document to the Finish procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
70352f0c5ab85d5c83ea7fc2a362529e578c3849
|
src/wiki-filters.ads
|
src/wiki-filters.ads
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
with Ada.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Nodes;
with Wiki.Strings;
-- == Filters ==
-- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt>
-- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations
-- and it forwards the different calls to a next wiki document instance. A filter can do some
-- operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type
-- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
-- @include wiki-filters-toc.ads
-- @include wiki-filters-html.ads
package Wiki.Filters is
pragma Preelaborate;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is new Ada.Finalization.Limited_Controlled with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- 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.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Pop a HTML node with the given tag.
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
type Filter_Chain is new Filter_Type with private;
-- Add the filter at beginning of the filter chain.
procedure Add_Filter (Chain : in out Filter_Chain;
Filter : in Filter_Type_Access);
private
type Filter_Type is new Ada.Finalization.Limited_Controlled with record
Next : Filter_Type_Access;
end record;
type Filter_Chain is new Filter_Type with null record;
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.
-----------------------------------------------------------------------
with Ada.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Nodes;
with Wiki.Strings;
-- == Filters ==
-- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt>
-- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations
-- and it forwards the different calls to a next wiki document instance. A filter can do some
-- operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type
-- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
-- @include wiki-filters-toc.ads
-- @include wiki-filters-html.ads
-- @include wiki-filters-collectors.ads
package Wiki.Filters is
pragma Preelaborate;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is new Ada.Finalization.Limited_Controlled with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- 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.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Pop a HTML node with the given tag.
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
type Filter_Chain is new Filter_Type with private;
-- Add the filter at beginning of the filter chain.
procedure Add_Filter (Chain : in out Filter_Chain;
Filter : in Filter_Type_Access);
private
type Filter_Type is new Ada.Finalization.Limited_Controlled with record
Next : Filter_Type_Access;
end record;
type Filter_Chain is new Filter_Type with null record;
end Wiki.Filters;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a644d6d4c9249e6c619f70357bc4b2b89ee3bbb2
|
src/mysql/ado-drivers-connections-mysql.adb
|
src/mysql/ado-drivers-connections-mysql.adb
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- 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 Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.Statements.Mysql;
with ADO.C;
with Mysql.Lib; use Mysql.Lib;
package body ADO.Drivers.Connections.Mysql is
use ADO.Statements.Mysql;
use Util.Log;
use Interfaces.C;
pragma Linker_Options (MYSQL_LIB_NAME);
Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql");
Driver_Name : aliased constant String := "mysql";
Driver : aliased Mysql_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return ADO.Drivers.Connections.Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Autocommit then
Database.Execute ("set autocommit=0");
Database.Autocommit := False;
end if;
Database.Execute ("start transaction;");
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_commit (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot commit transaction";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_rollback (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot rollback transaction";
end if;
end Rollback;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
null;
end Load_Schema;
-- ------------------------------
-- Execute a simple SQL statement
-- ------------------------------
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
begin
Log.Debug ("Execute SQL: {0}", SQL);
if Database.Server = null then
Log.Error ("Database connection is not open");
end if;
Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat));
Log.Debug ("Query result: {0}", int'Image (Result));
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
Log.Info ("Closing connection {0}", Database.Name);
if Database.Server /= null then
mysql_close (Database.Server);
Database.Server := null;
end if;
end Close;
-- ------------------------------
-- Releases the mysql connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release connection {0}", Database.Name);
Database.Close;
end Finalize;
-- ------------------------------
-- Initialize the database connection manager.
--
-- mysql://localhost:3306/db
--
-- ------------------------------
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : out ADO.Drivers.Connections.Database_Connection_Access) is
pragma Unreferenced (D);
Server : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server);
Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database);
Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user"));
Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password"));
Socket : ADO.C.String_Ptr;
Port : unsigned := unsigned (Config.Port);
Flags : constant unsigned_long := 0;
Connection : Mysql_Access;
Socket_Path : constant String := Config.Get_Property ("socket");
Database : constant Database_Connection_Access := new Database_Connection;
begin
if Socket_Path /= "" then
ADO.C.Set_String (Socket, Socket_Path);
end if;
if Port = 0 then
Port := 3306;
end if;
Log.Info ("Connecting to {0}:{1}", To_String (Config.Server), To_String (Config.Database));
Log.Debug ("user={0} password={1}", Config.Get_Property ("user"),
Config.Get_Property ("password"));
Connection := mysql_init (null);
Database.Server := mysql_real_connect (Connection, ADO.C.To_C (Server),
ADO.C.To_C (Login), ADO.C.To_C (Password),
ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags);
if Database.Server = null then
declare
Message : constant String := Strings.Value (Mysql_Error (Connection));
begin
Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message);
mysql_close (Connection);
raise Connection_Error with "Cannot connect to mysql server: " & Message;
end;
end if;
Database.Name := Config.Database;
Database.Count := 1;
Result := Database.all'Access;
end Create_Connection;
-- ------------------------------
-- Initialize the Mysql driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing mysql driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the Mysql driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Mysql_Driver) is
pragma Unreferenced (D);
begin
Log.Debug ("Deleting the mysql driver");
mysql_server_end;
end Finalize;
end ADO.Drivers.Connections.Mysql;
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- 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.Task_Attributes;
with Ada.Finalization;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.Statements.Mysql;
with ADO.C;
with Mysql.Lib; use Mysql.Lib;
package body ADO.Drivers.Connections.Mysql is
use ADO.Statements.Mysql;
use Util.Log;
use Interfaces.C;
pragma Linker_Options (MYSQL_LIB_NAME);
Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql");
Driver_Name : aliased constant String := "mysql";
Driver : aliased Mysql_Driver;
-- This is a little bit overkill but this is portable. We must call the 'mysql_thread_end'
-- operation before a task/thread terminates. The only way to do it is to setup a task
-- attribute which an object that has a finalization procedure.
--
-- The task cleaner attribute is set on tasks that call the 'mysql_connect' operation only.
type Mysql_Task_Cleaner is new Ada.Finalization.Controlled with null record;
-- Invoke the 'mysql_task_end' to release the storage allocated by mysql for the current task.
overriding
procedure Finalize (Object : in out Mysql_Task_Cleaner);
Cleaner : Mysql_Task_Cleaner;
package Mysql_Task_Attribute is
new Ada.Task_Attributes (Mysql_Task_Cleaner, Cleaner);
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return ADO.Drivers.Connections.Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Autocommit then
Database.Execute ("set autocommit=0");
Database.Autocommit := False;
end if;
Database.Execute ("start transaction;");
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_commit (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot commit transaction";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_rollback (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot rollback transaction";
end if;
end Rollback;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
null;
end Load_Schema;
-- ------------------------------
-- Execute a simple SQL statement
-- ------------------------------
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
begin
Log.Debug ("Execute SQL: {0}", SQL);
if Database.Server = null then
Log.Error ("Database connection is not open");
end if;
Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat));
Log.Debug ("Query result: {0}", int'Image (Result));
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
Log.Info ("Closing connection {0}", Database.Name);
if Database.Server /= null then
mysql_close (Database.Server);
Database.Server := null;
end if;
end Close;
-- ------------------------------
-- Releases the mysql connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release connection {0}", Database.Name);
Database.Close;
end Finalize;
-- ------------------------------
-- Initialize the database connection manager.
--
-- mysql://localhost:3306/db
--
-- ------------------------------
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : out ADO.Drivers.Connections.Database_Connection_Access) is
pragma Unreferenced (D);
Server : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server);
Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database);
Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user"));
Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password"));
Socket : ADO.C.String_Ptr;
Port : unsigned := unsigned (Config.Port);
Flags : constant unsigned_long := 0;
Connection : Mysql_Access;
Socket_Path : constant String := Config.Get_Property ("socket");
Database : constant Database_Connection_Access := new Database_Connection;
begin
if Socket_Path /= "" then
ADO.C.Set_String (Socket, Socket_Path);
end if;
if Port = 0 then
Port := 3306;
end if;
Log.Info ("Connecting to {0}:{1}", To_String (Config.Server), To_String (Config.Database));
Log.Debug ("user={0} password={1}", Config.Get_Property ("user"),
Config.Get_Property ("password"));
Connection := mysql_init (null);
Mysql_Task_Attribute.Set_Value (Cleaner);
Database.Server := mysql_real_connect (Connection, ADO.C.To_C (Server),
ADO.C.To_C (Login), ADO.C.To_C (Password),
ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags);
if Database.Server = null then
declare
Message : constant String := Strings.Value (Mysql_Error (Connection));
begin
Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message);
mysql_close (Connection);
raise Connection_Error with "Cannot connect to mysql server: " & Message;
end;
end if;
Database.Name := Config.Database;
Database.Count := 1;
Result := Database.all'Access;
end Create_Connection;
-- ------------------------------
-- Initialize the Mysql driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing mysql driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the Mysql driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Mysql_Driver) is
pragma Unreferenced (D);
begin
Log.Debug ("Deleting the mysql driver");
mysql_server_end;
end Finalize;
-- ------------------------------
-- Invoke the 'mysql_task_end' to release the storage allocated by mysql for the current task.
-- ------------------------------
overriding
procedure Finalize (Object : in out Mysql_Task_Cleaner) is
pragma Unreferenced (Object);
begin
mysql_thread_end;
end Finalize;
end ADO.Drivers.Connections.Mysql;
|
Manage to call 'mysql_thread_end' when a task that created a connection is terminated (necessary to avoid memory leaks in libmysql)
|
Manage to call 'mysql_thread_end' when a task that created a connection is terminated
(necessary to avoid memory leaks in libmysql)
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
bcc9a6e930e13bee4df79d2ec47d1af91d936731
|
src/portscan-ops.ads
|
src/portscan-ops.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Display;
package PortScan.Ops is
package DPY renames Display;
function port_name (id : port_id) return String;
function next_ignored_port return port_id;
function ignore_reason (id : port_id) return String;
function queue_length return Integer;
function skip_verified (id : port_id) return Boolean;
-- Returns true if every port in the queue has all of ports listed in the
-- blocks and blocked_by containers are all also present in the queue
function integrity_intact return Boolean;
-- This removes the first reverse dependency port from all_ports that is
-- found the complete reverse deps list and return the port_id of the
-- deleted port. If the list is empty, return port_match_failed instead.
function skip_next_reverse_dependency (pinnacle : port_id) return port_id;
-- removes processed port from the ranking queue.
procedure unlist_port (id : port_id);
-- Returns the highly priority buildable port
function top_buildable_port return port_id;
-- The port build succeeded, so remove the "blocked_by" designation
-- for all the immediate reverse dependencies.
-- Remove the port from the queue when this is done.
procedure cascade_successful_build (id : port_id);
-- The port build failed, so set all reverse dependences as skipped
-- Remove the port from the queue when this is done.
procedure cascade_failed_build (id : port_id; numskipped : out Natural;
logs : dim_handlers);
-- Kick off bulk run using the given number of builders
-- The rank_queue and all_ports must be already set up (it's recommended
-- To eliminate the ignored ports and subsequent skips first.
procedure parallel_bulk_run (num_builders : builders; logs : dim_handlers);
-- Before starting to build a port, lock it. This is required for
-- parallel building.
procedure lock_package (id : port_id);
-- Kicks off curses or sets color support off. Do it before
-- calling parallel_bulk_run.
procedure initialize_display (num_builders : builders);
-- Unconditionally copies web assets to <log directory/report directory
-- It also provides an initial summary.json data file just the report has something to load
procedure initialize_web_report (num_builders : builders);
-- Call before executing sanity check. It checks the present of build
-- hooks at the synth_conf location and caches the results.
-- It also fires off the first hook (run_start)
procedure initialize_hooks;
-- Exposed for pilot which eliminated ignored ports during the sanity check
procedure record_history_ignored
(elapsed : String;
origin : String;
reason : String;
skips : Natural);
private
-- History log entries average less than 200 bytes. Allot more than twice this amount.
kfile_unit_maxsize : constant Positive := 512;
-- Each history segment is limited to this many log lines
kfile_units_limit : constant Positive := 3;
subtype impulse_range is Integer range 1 .. 500;
subtype kfile_content is String (1 .. kfile_unit_maxsize * kfile_units_limit);
type progress_history is
record
segment : Natural := 0;
segment_count : Natural := 0;
log_entry : Natural := 0;
last_index : Natural := 0;
content : kfile_content;
end record;
type impulse_rec is
record
hack : CAL.Time;
packages : Natural := 0;
virgin : Boolean := True;
end record;
type hook_type is (run_start, run_end, pkg_success, pkg_failure,
pkg_skipped, pkg_ignored);
type machine_state is (idle, tasked, busy, done_failure, done_success,
shutdown);
type dim_instruction is array (builders) of port_id;
type dim_builder_state is array (builders) of machine_state;
type dim_impulse is array (impulse_range) of impulse_rec;
type dim_hooks is array (hook_type) of Boolean;
type dim_hooksloc is array (hook_type) of JT.Text;
history : progress_history;
impulse_counter : impulse_range := impulse_range'Last;
impulse_data : dim_impulse;
curses_support : Boolean;
active_hook : dim_hooks := (False, False, False, False, False, False);
hook_location : constant dim_hooksloc :=
(JT.SUS (PM.synth_confdir & "/hook_run_start"),
JT.SUS (PM.synth_confdir & "/hook_run_end"),
JT.SUS (PM.synth_confdir & "/hook_pkg_success"),
JT.SUS (PM.synth_confdir & "/hook_pkg_failure"),
JT.SUS (PM.synth_confdir & "/hook_pkg_skipped"),
JT.SUS (PM.synth_confdir & "/hook_pkg_ignored"));
function nothing_left (num_builders : builders) return Boolean;
function shutdown_recommended (active_builders : Positive) return Boolean;
function still_ranked (id : port_id) return Boolean;
function rank_arrow (id : port_id) return ranking_crate.Cursor;
function package_name (id : port_id) return String;
function get_swap_status return Float;
function get_instant_load return Float;
function hourly_build_rate return Natural;
function impulse_rate return Natural;
function assemble_HR (slave : builders; pid : port_id;
action : DPY.history_action)
return DPY.history_rec;
function file_is_executable (filename : String) return Boolean;
function nv (name, value : String) return String;
function nv (name : String; value : Integer) return String;
procedure delete_rank (id : port_id);
procedure run_hook (hook : hook_type; envvar_list : String);
procedure check_history_segment_capacity;
procedure handle_first_history_entry;
procedure write_summary_json
(active : Boolean;
states : dim_builder_state;
num_builders : builders;
num_history_files : Natural);
procedure write_history_json;
procedure assimulate_substring
(history : in out progress_history;
substring : String);
procedure record_history_built
(elapsed : String;
slave_id : builders;
origin : String;
duration : String);
procedure record_history_failed
(elapsed : String;
slave_id : builders;
origin : String;
duration : String;
die_phase : String;
skips : Natural);
procedure record_history_skipped
(elapsed : String;
origin : String;
reason : String);
end PortScan.Ops;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Display;
package PortScan.Ops is
package DPY renames Display;
function port_name (id : port_id) return String;
function next_ignored_port return port_id;
function ignore_reason (id : port_id) return String;
function queue_length return Integer;
function skip_verified (id : port_id) return Boolean;
-- Returns true if every port in the queue has all of ports listed in the
-- blocks and blocked_by containers are all also present in the queue
function integrity_intact return Boolean;
-- This removes the first reverse dependency port from all_ports that is
-- found the complete reverse deps list and return the port_id of the
-- deleted port. If the list is empty, return port_match_failed instead.
function skip_next_reverse_dependency (pinnacle : port_id) return port_id;
-- removes processed port from the ranking queue.
procedure unlist_port (id : port_id);
-- Returns the highly priority buildable port
function top_buildable_port return port_id;
-- The port build succeeded, so remove the "blocked_by" designation
-- for all the immediate reverse dependencies.
-- Remove the port from the queue when this is done.
procedure cascade_successful_build (id : port_id);
-- The port build failed, so set all reverse dependences as skipped
-- Remove the port from the queue when this is done.
procedure cascade_failed_build (id : port_id; numskipped : out Natural;
logs : dim_handlers);
-- Kick off bulk run using the given number of builders
-- The rank_queue and all_ports must be already set up (it's recommended
-- To eliminate the ignored ports and subsequent skips first.
procedure parallel_bulk_run (num_builders : builders; logs : dim_handlers);
-- Before starting to build a port, lock it. This is required for
-- parallel building.
procedure lock_package (id : port_id);
-- Kicks off curses or sets color support off. Do it before
-- calling parallel_bulk_run.
procedure initialize_display (num_builders : builders);
-- Unconditionally copies web assets to <log directory/report directory
-- It also provides an initial summary.json data file just the report has something to load
procedure initialize_web_report (num_builders : builders);
-- Call before executing sanity check. It checks the present of build
-- hooks at the synth_conf location and caches the results.
-- It also fires off the first hook (run_start)
procedure initialize_hooks;
-- Exposed for pilot which eliminated ignored ports during the sanity check
procedure record_history_ignored
(elapsed : String;
origin : String;
reason : String;
skips : Natural);
private
-- History log entries average less than 200 bytes. Allot more than twice this amount.
kfile_unit_maxsize : constant Positive := 512;
-- Each history segment is limited to this many log lines
kfile_units_limit : constant Positive := 500;
subtype impulse_range is Integer range 1 .. 500;
subtype kfile_content is String (1 .. kfile_unit_maxsize * kfile_units_limit);
type progress_history is
record
segment : Natural := 0;
segment_count : Natural := 0;
log_entry : Natural := 0;
last_index : Natural := 0;
content : kfile_content;
end record;
type impulse_rec is
record
hack : CAL.Time;
packages : Natural := 0;
virgin : Boolean := True;
end record;
type hook_type is (run_start, run_end, pkg_success, pkg_failure,
pkg_skipped, pkg_ignored);
type machine_state is (idle, tasked, busy, done_failure, done_success,
shutdown);
type dim_instruction is array (builders) of port_id;
type dim_builder_state is array (builders) of machine_state;
type dim_impulse is array (impulse_range) of impulse_rec;
type dim_hooks is array (hook_type) of Boolean;
type dim_hooksloc is array (hook_type) of JT.Text;
history : progress_history;
impulse_counter : impulse_range := impulse_range'Last;
impulse_data : dim_impulse;
curses_support : Boolean;
active_hook : dim_hooks := (False, False, False, False, False, False);
hook_location : constant dim_hooksloc :=
(JT.SUS (PM.synth_confdir & "/hook_run_start"),
JT.SUS (PM.synth_confdir & "/hook_run_end"),
JT.SUS (PM.synth_confdir & "/hook_pkg_success"),
JT.SUS (PM.synth_confdir & "/hook_pkg_failure"),
JT.SUS (PM.synth_confdir & "/hook_pkg_skipped"),
JT.SUS (PM.synth_confdir & "/hook_pkg_ignored"));
function nothing_left (num_builders : builders) return Boolean;
function shutdown_recommended (active_builders : Positive) return Boolean;
function still_ranked (id : port_id) return Boolean;
function rank_arrow (id : port_id) return ranking_crate.Cursor;
function package_name (id : port_id) return String;
function get_swap_status return Float;
function get_instant_load return Float;
function hourly_build_rate return Natural;
function impulse_rate return Natural;
function assemble_HR (slave : builders; pid : port_id;
action : DPY.history_action)
return DPY.history_rec;
function file_is_executable (filename : String) return Boolean;
function nv (name, value : String) return String;
function nv (name : String; value : Integer) return String;
procedure delete_rank (id : port_id);
procedure run_hook (hook : hook_type; envvar_list : String);
procedure check_history_segment_capacity;
procedure handle_first_history_entry;
procedure write_summary_json
(active : Boolean;
states : dim_builder_state;
num_builders : builders;
num_history_files : Natural);
procedure write_history_json;
procedure assimulate_substring
(history : in out progress_history;
substring : String);
procedure record_history_built
(elapsed : String;
slave_id : builders;
origin : String;
duration : String);
procedure record_history_failed
(elapsed : String;
slave_id : builders;
origin : String;
duration : String;
die_phase : String;
skips : Natural);
procedure record_history_skipped
(elapsed : String;
origin : String;
reason : String);
end PortScan.Ops;
|
Bump kfile units to 500 as intended
|
Bump kfile units to 500 as intended
The ajax works with multiple kfiles as expected during testing.
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
1c0e61df6f1232f6a9f7499be9afa25241af6b41
|
src/wiki-helpers.ads
|
src/wiki-helpers.ads
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
package Wiki.Helpers is
pragma Preelaborate;
LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#);
CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#);
HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#);
-- Returns True if the character is a space or tab.
function Is_Space (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the character is a space, tab or a newline.
function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the text is a valid URL
function Is_Url (Text : in Wiki.Strings.WString) return Boolean;
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean;
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean;
end Wiki.Helpers;
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
package Wiki.Helpers is
pragma Preelaborate;
LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#);
CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#);
HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#);
-- Returns True if the character is a space or tab.
function Is_Space (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the character is a space, tab or a newline.
function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the character is a line terminator.
function Is_Newline (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the text is a valid URL
function Is_Url (Text : in Wiki.Strings.WString) return Boolean;
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean;
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean;
end Wiki.Helpers;
|
Declare the Is_Newline function
|
Declare the Is_Newline function
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
8d4bbc23306661a72e23f5c37d7e275820dcdf3e
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
private with Wiki.Buffers;
private with Util.Stacks;
private with Wiki.Nodes;
private with Wiki.Html_Parser;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
subtype Parser_Type is Parser;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Trim_End is (None, Left, Right, Both);
type Block;
type Content_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Content_Access;
Last : Natural := 0;
Content : Wiki.Strings.WString (1 .. Len);
end record;
procedure Next (Content : in out Content_Access;
Pos : in out Positive) with Inline_Always;
use Wiki.Strings.Wide_Wide_Builders;
type Block_Type is record
Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH;
Level : Natural := 0;
Marker : Wiki.Strings.WChar := ' ';
Number : Integer := 0;
end record;
type Parser_State_Type is (State_Html_Doctype,
State_Html_Comment,
State_Html_Attribute,
State_Html_Element);
type Block_Access is access all Block_Type;
package Block_Stack is new Util.Stacks (Element_Type => Block_Type,
Element_Type_Access => Block_Access);
type Parser_Handler is access procedure (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access);
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Previous_Syntax : Wiki_Syntax;
Document : Wiki.Documents.Document;
Parse_Block : Parser_Handler;
Parse_Inline : Parser_Handler;
Format : Wiki.Format_Map;
Line : Wiki.Strings.BString (512);
Text : Wiki.Strings.BString (512);
Line_Buffer : Wiki.Buffers.Builder (512);
Text_Buffer : Wiki.Buffers.Builder (512);
Line_Length : Natural := 0;
Line_Pos : Natural := 0;
Empty_Line : Boolean := True;
Is_Last_Line : Boolean := False;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
In_Table : Boolean := False;
Need_Paragraph : Boolean := True;
Pending_Paragraph : Boolean := False;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE;
Blocks : Block_Stack.Stack;
Previous_Line_Empty : Boolean := False;
Header_Level : Natural := 0;
Is_Empty_Paragraph : Boolean := True;
Pre_Tag_Counter : Natural := 0;
-- Pre-format code block
Preformat_Fence : Wiki.Strings.WChar;
Preformat_Indent : Natural := 0;
Preformat_Fcount : Natural := 0;
Preformat_Format : Wiki.Strings.BString (32);
Html : Wiki.Html_Parser.Parser_Type;
end record;
-- Read the next wiki input line in the line buffer.
procedure Read_Line (Parser : in out Parser_Type'Class;
Buffer : out Wiki.Buffers.Buffer_Access);
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser'Class;
Token : out Wiki.Strings.WChar);
pragma Inline (Peek);
function Is_List_Item (P : in Parser;
Level : in Natural) return Boolean;
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser;
Trim : in Trim_End := None);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
procedure Pop_List (P : in out Parser;
Level : in Natural;
Marker : in Wiki.Strings.WChar);
procedure Pop_List (P : in out Parser);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Process_Html (P : in out Parser;
Kind : in Wiki.Html_Parser.State_Type;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a single character sequence.
-- Example:
-- _name_ *bold* `code`
procedure Parse_Format (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence.
-- Example:
-- --name-- **bold** ~~strike~~
procedure Parse_Format_Double (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Push a new block kind on the block stack.
procedure Push_Block (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer := 0;
Marker : in Wiki.Strings.WChar := ' ';
Number : in Integer := 0);
-- Pop the current block stack.
procedure Pop_Block (P : in out Parser);
procedure Pop_All (P : in out Parser);
procedure Pop_Block_Until (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer);
procedure Append_Text (P : in out Parser;
Text : in Wiki.Strings.BString;
From : in Positive;
To : in Positive);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
private with Wiki.Buffers;
private with Util.Stacks;
private with Wiki.Nodes;
private with Wiki.Html_Parser;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
subtype Parser_Type is Parser;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Trim_End is (None, Left, Right, Both);
type Block;
type Content_Access is access all Block;
type Block (Len : Positive) is limited record
Next_Block : Content_Access;
Last : Natural := 0;
Content : Wiki.Strings.WString (1 .. Len);
end record;
procedure Next (Content : in out Content_Access;
Pos : in out Positive) with Inline_Always;
use Wiki.Strings.Wide_Wide_Builders;
type Block_Type is record
Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH;
Level : Natural := 0;
Marker : Wiki.Strings.WChar := ' ';
Number : Integer := 0;
end record;
type Parser_State_Type is (State_Html_Doctype,
State_Html_Comment,
State_Html_Attribute,
State_Html_Element);
type Block_Access is access all Block_Type;
package Block_Stack is new Util.Stacks (Element_Type => Block_Type,
Element_Type_Access => Block_Access);
type Parser_Handler is access procedure (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access);
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Previous_Syntax : Wiki_Syntax;
Document : Wiki.Documents.Document;
Parse_Block : Parser_Handler;
Parse_Inline : Parser_Handler;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Line_Buffer : Wiki.Buffers.Builder (512);
Text_Buffer : Wiki.Buffers.Builder (512);
Empty_Line : Boolean := True;
Is_Last_Line : Boolean := False;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
In_Table : Boolean := False;
Need_Paragraph : Boolean := True;
Pending_Paragraph : Boolean := False;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE;
Blocks : Block_Stack.Stack;
Previous_Line_Empty : Boolean := False;
Header_Level : Natural := 0;
Is_Empty_Paragraph : Boolean := True;
Pre_Tag_Counter : Natural := 0;
-- Pre-format code block
Preformat_Fence : Wiki.Strings.WChar;
Preformat_Indent : Natural := 0;
Preformat_Fcount : Natural := 0;
Preformat_Format : Wiki.Strings.BString (32);
Html : Wiki.Html_Parser.Parser_Type;
end record;
-- Read the next wiki input line in the line buffer.
procedure Read_Line (Parser : in out Parser_Type'Class;
Buffer : out Wiki.Buffers.Buffer_Access);
function Is_List_Item (P : in Parser;
Level : in Natural) return Boolean;
function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access;
From : in Positive;
Token : in Wiki.Strings.WChar) return Boolean;
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser;
Trim : in Trim_End := None);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
procedure Pop_List (P : in out Parser;
Level : in Natural;
Marker : in Wiki.Strings.WChar);
procedure Pop_List (P : in out Parser);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Process_Html (P : in out Parser;
Kind : in Wiki.Html_Parser.State_Type;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a single character sequence.
-- Example:
-- _name_ *bold* `code`
procedure Parse_Format (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence.
-- Example:
-- --name-- **bold** ~~strike~~
procedure Parse_Format_Double (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Push a new block kind on the block stack.
procedure Push_Block (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer := 0;
Marker : in Wiki.Strings.WChar := ' ';
Number : in Integer := 0);
-- Pop the current block stack.
procedure Pop_Block (P : in out Parser);
procedure Pop_All (P : in out Parser);
procedure Pop_Block_Until (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer);
procedure Append_Text (P : in out Parser;
Text : in Wiki.Strings.BString;
From : in Positive;
To : in Positive);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
Remove old parser line information
|
Remove old parser line information
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
9edc3804e4a81a1de1cc794e018aff574aef2501
|
regtests/security-random-tests.adb
|
regtests/security-random-tests.adb
|
-----------------------------------------------------------------------
-- security-random-tests - Tests for random package
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Ada.Text_IO;
package body Security.Random.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Random");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Random.Generate",
Test_Generate'Access);
end Add_Tests;
-- ------------------------------
-- Test Yadis discovery using static files
-- ------------------------------
procedure Test_Generate (T : in out Test) is
use Ada.Strings.Unbounded;
G : Generator;
Max : constant Ada.Streams.Stream_Element_Offset := 10;
begin
for I in 1 .. Max loop
declare
use type Ada.Streams.Stream_Element;
S : Ada.Streams.Stream_Element_Array (1 .. I)
:= (others => 0);
Rand : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Try 5 times to fill the array with random patterns and make sure
-- we don't get any 0.
for Retry in 1 .. 5 loop
G.Generate (S);
exit when (for all R of S => R /= 0);
end loop;
T.Assert ((for all R of S => R /= 0), "Generator failed to initialize all bytes");
G.Generate (Positive (I), Rand);
T.Assert (Length (Rand) > 0, "Generator failed to produce a base64url sequence");
end;
end loop;
end Test_Generate;
end Security.Random.Tests;
|
-----------------------------------------------------------------------
-- security-random-tests - Tests for random package
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
package body Security.Random.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Random");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Random.Generate",
Test_Generate'Access);
end Add_Tests;
-- ------------------------------
-- Test Yadis discovery using static files
-- ------------------------------
procedure Test_Generate (T : in out Test) is
use Ada.Strings.Unbounded;
G : Generator;
Max : constant Ada.Streams.Stream_Element_Offset := 10;
begin
for I in 1 .. Max loop
declare
use type Ada.Streams.Stream_Element;
S : Ada.Streams.Stream_Element_Array (1 .. I)
:= (others => 0);
Rand : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Try 5 times to fill the array with random patterns and make sure
-- we don't get any 0.
for Retry in 1 .. 5 loop
G.Generate (S);
exit when (for all R of S => R /= 0);
end loop;
T.Assert ((for all R of S => R /= 0), "Generator failed to initialize all bytes");
G.Generate (Positive (I), Rand);
T.Assert (Length (Rand) > 0, "Generator failed to produce a base64url sequence");
end;
end loop;
end Test_Generate;
end Security.Random.Tests;
|
Remove unused with clause
|
Remove unused with clause
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
214308e41493e10a0a7997ee8469f5c9ed058bc8
|
regtests/util-properties-tests.adb
|
regtests/util-properties-tests.adb
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
use Util;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted");
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
end Add_Tests;
end Util.Properties.Tests;
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted");
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
end Add_Tests;
end Util.Properties.Tests;
|
Remove unused use clause
|
Remove unused use clause
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
44182ead6125b1ebc43a8adeb7590b3c63f52205
|
orka/src/orka/linux/orka-os.adb
|
orka/src/orka/linux/orka-os.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Interfaces.C.Strings;
with System;
with Ada.Characters.Latin_1;
package body Orka.OS is
procedure Set_Task_Name (Name : in String) is
use Interfaces.C;
PR_SET_NAME : constant := 15;
function prctl
(option : int;
arg2 : Strings.chars_ptr;
arg3, arg4, arg5 : unsigned_long := 0) return int
with Import, Convention => C, External_Name => "prctl";
C_Name_Str : Strings.chars_ptr := Strings.New_String (Name);
Result : int;
begin
Result := prctl (PR_SET_NAME, C_Name_Str);
Strings.Free (C_Name_Str);
pragma Assert (Result = 0);
end Set_Task_Name;
----------------------------------------------------------------------------
type Clock_Kind is (Realtime, Monotonic);
for Clock_Kind use
(Realtime => 0,
Monotonic => 1);
for Clock_Kind'Size use Interfaces.C.int'Size;
type Timespec is record
Seconds : aliased Interfaces.C.long;
Nanoseconds : aliased Interfaces.C.long;
end record
with Convention => C;
function C_Clock_Gettime
(Kind : Clock_Kind;
Time : access Timespec) return Interfaces.C.int
with Import, Convention => C, External_Name => "clock_gettime";
function Monotonic_Clock return Duration is
use type Interfaces.C.int;
Value : aliased Timespec;
Result : Interfaces.C.int;
begin
Result := C_Clock_Gettime (Monotonic, Value'Access);
pragma Assert (Result = 0);
-- Makes compiler happy and can be optimized away (unlike raise Program_Error)
return Duration (Value.Seconds) + Duration (Value.Nanoseconds) / 1e9;
end Monotonic_Clock;
function Monotonic_Clock return Time is (Time (Duration'(Monotonic_Clock)));
----------------------------------------------------------------------------
subtype Size_Type is Interfaces.C.unsigned_long;
procedure C_Fwrite
(Value : String;
Size : Size_Type;
Count : Size_Type;
File : System.Address)
with Import, Convention => C, External_Name => "fwrite";
File_Standard_Output : constant System.Address
with Import, Convention => C, External_Name => "stdout";
File_Standard_Error : constant System.Address
with Import, Convention => C, External_Name => "stderr";
procedure Put_Line (Value : String; Kind : File_Kind := Standard_Output) is
package L1 renames Ada.Characters.Latin_1;
C_Value : constant String := Value & L1.LF;
begin
C_Fwrite (C_Value, 1, C_Value'Length,
(case Kind is
when Standard_Output => File_Standard_Output,
when Standard_Error => File_Standard_Error));
end Put_Line;
end Orka.OS;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Interfaces.C.Strings;
with System;
with Ada.Characters.Latin_1;
package body Orka.OS is
procedure Set_Task_Name (Name : in String) is
use Interfaces.C;
PR_SET_NAME : constant := 15;
function prctl
(option : int;
arg2 : Strings.chars_ptr;
arg3, arg4, arg5 : unsigned_long := 0) return int
with Import, Convention => C, External_Name => "prctl";
C_Name_Str : Strings.chars_ptr := Strings.New_String (Name);
Result : int;
begin
Result := prctl (PR_SET_NAME, C_Name_Str);
Strings.Free (C_Name_Str);
pragma Assert (Result = 0);
end Set_Task_Name;
----------------------------------------------------------------------------
type Clock_Kind is (Realtime, Monotonic);
for Clock_Kind use
(Realtime => 0,
Monotonic => 1);
for Clock_Kind'Size use Interfaces.C.int'Size;
type Timespec is record
Seconds : aliased Interfaces.C.long;
Nanoseconds : aliased Interfaces.C.long;
end record
with Convention => C;
function C_Clock_Gettime
(Kind : Clock_Kind;
Time : access Timespec) return Interfaces.C.int
with Import, Convention => C, External_Name => "clock_gettime";
function Monotonic_Clock return Duration is
Value : aliased Timespec;
Unused_Result : Interfaces.C.int;
begin
Unused_Result := C_Clock_Gettime (Monotonic, Value'Access);
return Duration (Value.Seconds) + Duration (Value.Nanoseconds) / 1e9;
end Monotonic_Clock;
function Monotonic_Clock return Time is (Time (Duration'(Monotonic_Clock)));
----------------------------------------------------------------------------
subtype Size_Type is Interfaces.C.unsigned_long;
procedure C_Fwrite
(Value : String;
Size : Size_Type;
Count : Size_Type;
File : System.Address)
with Import, Convention => C, External_Name => "fwrite";
File_Standard_Output : constant System.Address
with Import, Convention => C, External_Name => "stdout";
File_Standard_Error : constant System.Address
with Import, Convention => C, External_Name => "stderr";
procedure Put_Line (Value : String; Kind : File_Kind := Standard_Output) is
package L1 renames Ada.Characters.Latin_1;
C_Value : constant String := Value & L1.LF;
begin
C_Fwrite (C_Value, 1, C_Value'Length,
(case Kind is
when Standard_Output => File_Standard_Output,
when Standard_Error => File_Standard_Error));
end Put_Line;
end Orka.OS;
|
Remove assertion in function Monotonic_Clock in package Orka.OS
|
orka: Remove assertion in function Monotonic_Clock in package Orka.OS
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
fff6d2767f33d809b1cfc21bf8e46413c4c17625
|
matp/src/events/mat-events-timelines.ads
|
matp/src/events/mat-events-timelines.ads
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- 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.Containers.Vectors;
with MAT.Expressions;
with MAT.Events.Targets;
package MAT.Events.Timelines is
-- Describe a section of the timeline. The section has a starting and ending
-- event that marks the boundary of the section within the collected events.
-- The timeline section gives the duration and some statistics about memory
-- allocation made in the section.
type Timeline_Info is record
Start_Id : MAT.Events.Targets.Event_Id_Type := 0;
Start_Time : MAT.Types.Target_Tick_Ref := 0;
End_Id : MAT.Events.Targets.Event_Id_Type := 0;
End_Time : MAT.Types.Target_Tick_Ref := 0;
Duration : MAT.Types.Target_Time := 0;
Malloc_Count : Natural := 0;
Realloc_Count : Natural := 0;
Free_Count : Natural := 0;
end record;
package Timeline_Info_Vectors is
new Ada.Containers.Vectors (Positive, Timeline_Info);
subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector;
subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events;
Into : in out Timeline_Info_Vector);
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Targets.Probe_Event_Type;
Max : in Positive;
List : in out MAT.Events.Targets.Target_Event_Vector);
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Targets.Size_Event_Info_Map);
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Natural;
Frames : in out MAT.Events.Targets.Frame_Event_Info_Map);
end MAT.Events.Timelines;
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- 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.Containers.Vectors;
with MAT.Expressions;
with MAT.Events.Targets;
package MAT.Events.Timelines is
-- Describe a section of the timeline. The section has a starting and ending
-- event that marks the boundary of the section within the collected events.
-- The timeline section gives the duration and some statistics about memory
-- allocation made in the section.
type Timeline_Info is record
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Duration : MAT.Types.Target_Time := 0;
Malloc_Count : Natural := 0;
Realloc_Count : Natural := 0;
Free_Count : Natural := 0;
end record;
package Timeline_Info_Vectors is
new Ada.Containers.Vectors (Positive, Timeline_Info);
subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector;
subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class;
Into : in out Timeline_Info_Vector);
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Targets.Probe_Event_Type;
Max : in Positive;
List : in out MAT.Events.Targets.Target_Event_Vector);
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Targets.Size_Event_Info_Map);
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Natural;
Frames : in out MAT.Events.Targets.Frame_Event_Info_Map);
end MAT.Events.Timelines;
|
Store the first and last event in the Timeline_Info record
|
Store the first and last event in the Timeline_Info record
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ccd17fd1b1f8f09482d011790db2fd6deca3a53c
|
regtests/ado-statements-tests.adb
|
regtests/ado-statements-tests.adb
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings.Transforms;
with ADO.Utils;
with ADO.Sessions;
with Regtests.Statements.Model;
package body ADO.Statements.Tests is
use Util.Tests;
procedure Populate (Tst : in out Test);
function Get_Sum (T : in Test;
Table : in String) return Natural;
-- Test the query statement Get_Xxx operation for various types.
generic
type T (<>) is private;
with function Get_Value (Stmt : in ADO.Statements.Query_Statement;
Column : in Natural) return T is <>;
Name : String;
Column : String;
procedure Test_Query_Get_Value_T (Tst : in out Test);
procedure Populate (Tst : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
DB.Begin_Transaction;
for I in 1 .. 10 loop
declare
Item : Regtests.Statements.Model.Table_Ref;
begin
Item.Set_Id_Value (ADO.Identifier (I * I));
Item.Set_Int_Value (I);
Item.Set_Bool_Value ((I mod 2) = 0);
Item.Set_String_Value ("Item" & Integer'Image (I));
Item.Set_Time_Value (Ada.Calendar.Clock);
Item.Set_Entity_Value (ADO.Entity_Type (10 - I));
Item.Save (DB);
Tst.Assert (Item.Is_Inserted, "Item inserted in database");
end;
end loop;
DB.Commit;
end Populate;
-- ------------------------------
-- Test the query statement Get_Xxx operation for various types.
-- ------------------------------
procedure Test_Query_Get_Value_T (Tst : in out Test) is
Stmt : ADO.Statements.Query_Statement;
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
begin
Populate (Tst);
-- Check that Get_Value raises an exception if the statement is invalid.
begin
declare
V : T := Get_Value (Stmt, 0);
pragma Unreferenced (V);
begin
Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name);
end;
exception
when Invalid_Statement =>
null;
end;
-- Execute a query to fetch one column.
Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1");
Stmt.Execute;
-- Verify the query result and the Get_Value operation.
Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for "
& Name & ":" & Column);
Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for "
& Name & ":" & Column);
Util.Tests.Assert_Equals (Tst, Column,
Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)),
"The query returns an invalid column name");
declare
V : T := Get_Value (Stmt, 0);
pragma Unreferenced (V);
begin
Stmt.Clear;
end;
end Test_Query_Get_Value_T;
procedure Test_Query_Get_Int64 is
new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value");
procedure Test_Query_Get_Integer is
new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value");
procedure Test_Query_Get_Nullable_Integer is
new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer,
"Get_Nullable_Integer", "int_value");
procedure Test_Query_Get_Nullable_Entity_Type is
new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type,
"Get_Nullable_Entity_Type", "entity_value");
procedure Test_Query_Get_Natural is
new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value");
procedure Test_Query_Get_Identifier is
new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier,
"Get_Identifier", "id_value");
procedure Test_Query_Get_Boolean is
new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value");
procedure Test_Query_Get_String is
new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value");
package Caller is new Util.Test_Caller (Test, "ADO.Statements");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Statements.Save",
Test_Save'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64",
Test_Query_Get_Int64'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer",
Test_Query_Get_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer",
Test_Query_Get_Nullable_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural",
Test_Query_Get_Natural'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier",
Test_Query_Get_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean",
Test_Query_Get_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_String",
Test_Query_Get_String'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type",
Test_Query_Get_Nullable_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Create_Statement (using $entity_type[])",
Test_Entity_Types'Access);
end Add_Tests;
function Get_Sum (T : in Test;
Table : in String) return Natural is
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM "
& Table);
begin
Stmt.Execute;
T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table);
return Stmt.Get_Integer (0);
end Get_Sum;
function Get_Sum (T : in Test;
Table : in String;
Ids : in ADO.Utils.Identifier_Vector) return Natural is
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM "
& Table
& " WHERE id IN (:ids)");
begin
Stmt.Bind_Param ("ids", Ids);
Stmt.Execute;
T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table);
return Stmt.Get_Integer (0);
end Get_Sum;
-- ------------------------------
-- Test creation of several rows in test_table with different column type.
-- ------------------------------
procedure Test_Save (T : in out Test) is
First : constant Natural := Get_Sum (T, "test_table");
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
List : ADO.Utils.Identifier_Vector;
begin
DB.Begin_Transaction;
for I in 1 .. 10 loop
declare
Item : Regtests.Statements.Model.Table_Ref;
begin
Item.Set_Id_Value (ADO.Identifier (I * I));
Item.Set_Int_Value (I);
Item.Set_Bool_Value ((I mod 2) = 0);
Item.Set_String_Value ("Item" & Integer'Image (I));
Item.Set_Time_Value (Ada.Calendar.Clock);
Item.Set_Entity_Value (ADO.Entity_Type (10 - I));
Item.Save (DB);
List.Append (Item.Get_Id);
end;
end loop;
DB.Commit;
Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"),
"The SUM query returns an invalid value for test_table");
Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List),
"The SUM query returns an invalid value for test_table");
end Test_Save;
-- ------------------------------
-- Test queries using the $entity_type[] cache group.
-- ------------------------------
procedure Test_Entity_Types (T : in out Test) is
DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Query_Statement;
Count : Natural := 0;
begin
Stmt := DB.Create_Statement ("SELECT name FROM entity_type "
& "WHERE entity_type.id = $entity_type[test_user]");
Stmt.Execute;
while Stmt.Has_Elements loop
Util.Tests.Assert_Equals (T, "test_user", Stmt.Get_String (0), "Invalid query response");
Count := Count + 1;
Stmt.Next;
end loop;
Util.Tests.Assert_Equals (T, 1, Count, "Query must return one row");
end Test_Entity_Types;
end ADO.Statements.Tests;
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings.Transforms;
with ADO.Utils;
with ADO.Sessions;
with Regtests.Statements.Model;
package body ADO.Statements.Tests is
use Util.Tests;
procedure Populate (Tst : in out Test);
function Get_Sum (T : in Test;
Table : in String) return Natural;
function Get_Sum (T : in Test;
Table : in String;
Ids : in ADO.Utils.Identifier_Vector) return Natural;
-- Test the query statement Get_Xxx operation for various types.
generic
type T (<>) is private;
with function Get_Value (Stmt : in ADO.Statements.Query_Statement;
Column : in Natural) return T is <>;
Name : String;
Column : String;
procedure Test_Query_Get_Value_T (Tst : in out Test);
procedure Populate (Tst : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
DB.Begin_Transaction;
for I in 1 .. 10 loop
declare
Item : Regtests.Statements.Model.Table_Ref;
begin
Item.Set_Id_Value (ADO.Identifier (I * I));
Item.Set_Int_Value (I);
Item.Set_Bool_Value ((I mod 2) = 0);
Item.Set_String_Value ("Item" & Integer'Image (I));
Item.Set_Time_Value (Ada.Calendar.Clock);
Item.Set_Entity_Value (ADO.Entity_Type (10 - I));
Item.Save (DB);
Tst.Assert (Item.Is_Inserted, "Item inserted in database");
end;
end loop;
DB.Commit;
end Populate;
-- ------------------------------
-- Test the query statement Get_Xxx operation for various types.
-- ------------------------------
procedure Test_Query_Get_Value_T (Tst : in out Test) is
Stmt : ADO.Statements.Query_Statement;
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
begin
Populate (Tst);
-- Check that Get_Value raises an exception if the statement is invalid.
begin
declare
V : T := Get_Value (Stmt, 0);
pragma Unreferenced (V);
begin
Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name);
end;
exception
when Invalid_Statement =>
null;
end;
-- Execute a query to fetch one column.
Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1");
Stmt.Execute;
-- Verify the query result and the Get_Value operation.
Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for "
& Name & ":" & Column);
Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for "
& Name & ":" & Column);
Util.Tests.Assert_Equals (Tst, Column,
Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)),
"The query returns an invalid column name");
declare
V : T := Get_Value (Stmt, 0);
pragma Unreferenced (V);
begin
Stmt.Clear;
end;
end Test_Query_Get_Value_T;
procedure Test_Query_Get_Int64 is
new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value");
procedure Test_Query_Get_Integer is
new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value");
procedure Test_Query_Get_Nullable_Integer is
new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer,
"Get_Nullable_Integer", "int_value");
procedure Test_Query_Get_Nullable_Entity_Type is
new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type,
"Get_Nullable_Entity_Type", "entity_value");
procedure Test_Query_Get_Natural is
new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value");
procedure Test_Query_Get_Identifier is
new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier,
"Get_Identifier", "id_value");
procedure Test_Query_Get_Boolean is
new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value");
procedure Test_Query_Get_String is
new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value");
package Caller is new Util.Test_Caller (Test, "ADO.Statements");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Statements.Save",
Test_Save'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64",
Test_Query_Get_Int64'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer",
Test_Query_Get_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer",
Test_Query_Get_Nullable_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural",
Test_Query_Get_Natural'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier",
Test_Query_Get_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean",
Test_Query_Get_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_String",
Test_Query_Get_String'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type",
Test_Query_Get_Nullable_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Statements.Create_Statement (using $entity_type[])",
Test_Entity_Types'Access);
end Add_Tests;
function Get_Sum (T : in Test;
Table : in String) return Natural is
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM "
& Table);
begin
Stmt.Execute;
T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table);
return Stmt.Get_Integer (0);
end Get_Sum;
function Get_Sum (T : in Test;
Table : in String;
Ids : in ADO.Utils.Identifier_Vector) return Natural is
DB : constant ADO.Sessions.Session := Regtests.Get_Database;
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM "
& Table
& " WHERE id IN (:ids)");
begin
Stmt.Bind_Param ("ids", Ids);
Stmt.Execute;
T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table);
return Stmt.Get_Integer (0);
end Get_Sum;
-- ------------------------------
-- Test creation of several rows in test_table with different column type.
-- ------------------------------
procedure Test_Save (T : in out Test) is
First : constant Natural := Get_Sum (T, "test_table");
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
List : ADO.Utils.Identifier_Vector;
begin
DB.Begin_Transaction;
for I in 1 .. 10 loop
declare
Item : Regtests.Statements.Model.Table_Ref;
begin
Item.Set_Id_Value (ADO.Identifier (I * I));
Item.Set_Int_Value (I);
Item.Set_Bool_Value ((I mod 2) = 0);
Item.Set_String_Value ("Item" & Integer'Image (I));
Item.Set_Time_Value (Ada.Calendar.Clock);
Item.Set_Entity_Value (ADO.Entity_Type (10 - I));
Item.Save (DB);
List.Append (Item.Get_Id);
end;
end loop;
DB.Commit;
Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"),
"The SUM query returns an invalid value for test_table");
Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List),
"The SUM query returns an invalid value for test_table");
end Test_Save;
-- ------------------------------
-- Test queries using the $entity_type[] cache group.
-- ------------------------------
procedure Test_Entity_Types (T : in out Test) is
DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Query_Statement;
Count : Natural := 0;
begin
Stmt := DB.Create_Statement ("SELECT name FROM entity_type "
& "WHERE entity_type.id = $entity_type[test_user]");
Stmt.Execute;
while Stmt.Has_Elements loop
Util.Tests.Assert_Equals (T, "test_user", Stmt.Get_String (0), "Invalid query response");
Count := Count + 1;
Stmt.Next;
end loop;
Util.Tests.Assert_Equals (T, 1, Count, "Query must return one row");
end Test_Entity_Types;
end ADO.Statements.Tests;
|
Declare the Get_Sum function
|
Declare the Get_Sum function
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
dc8e85bcee934c33fad647429b6771b714af077e
|
src/natools-web-list_templates.ads
|
src/natools-web-list_templates.ads
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Web.List_Templates provides an abstraction around list rendering --
-- parameters, and a generic procedure to use it. --
------------------------------------------------------------------------------
with Ada.Containers;
with Ada.Iterator_Interfaces;
with Natools.S_Expressions.Atom_Refs;
with Natools.S_Expressions.Caches;
with Natools.S_Expressions.Lockable;
with Natools.Web.Sites;
package Natools.Web.List_Templates is
type Count is new Ada.Containers.Count_Type;
type Direction is (Forward, Backward);
type List_End is (Beginning, Ending);
type Parameters is record
Ellipses_Are_Items : Boolean := False;
Ellipsis_Prefix : S_Expressions.Atom_Refs.Immutable_Reference;
Ellipsis_Suffix : S_Expressions.Atom_Refs.Immutable_Reference;
Going : Direction := Forward;
Shown_End : List_End := Beginning;
If_Empty : S_Expressions.Atom_Refs.Immutable_Reference;
Limit : Count := 0;
Prefix : S_Expressions.Atom_Refs.Immutable_Reference;
Separator : S_Expressions.Atom_Refs.Immutable_Reference;
Suffix : S_Expressions.Atom_Refs.Immutable_Reference;
Template : S_Expressions.Caches.Cursor;
end record;
procedure Read_Parameters
(Object : in out Parameters;
Expression : in out S_Expressions.Lockable.Descriptor'Class);
function Read_Parameters
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Parameters;
generic
with package Iterators is new Ada.Iterator_Interfaces (<>);
with procedure Render
(Exchange : in out Sites.Exchange;
Position : in Iterators.Cursor;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is <>;
procedure Render
(Exchange : in out Sites.Exchange;
Iterator : in Iterators.Reversible_Iterator'Class;
Param : in Parameters);
end Natools.Web.List_Templates;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Web.List_Templates provides an abstraction around list rendering --
-- parameters, and a generic procedure to use it. --
-- When the list is empty, only If_Empty is output, otherwise the following --
-- scheme is rendered: --
-- <prefix> [<ellipsis_prefix>] <item_1> <separator> <item_2> ... --
-- ... <separator> <item_n> [<ellipsis_suffix>] <suffix> --
-- The optional ellipses are output when the list is only partially output. --
-- Ellipses_Are_Items controls whether the non-empty ellipses count towards --
-- the given limit. --
-- Shown_End controls whether partially rendered lists omit items at the --
-- beginning or at the end of the displayed list (i.e. after taking into --
-- account Going). --
------------------------------------------------------------------------------
with Ada.Containers;
with Ada.Iterator_Interfaces;
with Natools.S_Expressions.Atom_Refs;
with Natools.S_Expressions.Caches;
with Natools.S_Expressions.Lockable;
with Natools.Web.Sites;
package Natools.Web.List_Templates is
type Count is new Ada.Containers.Count_Type;
type Direction is (Forward, Backward);
type List_End is (Beginning, Ending);
type Parameters is record
Ellipses_Are_Items : Boolean := False;
Ellipsis_Prefix : S_Expressions.Atom_Refs.Immutable_Reference;
Ellipsis_Suffix : S_Expressions.Atom_Refs.Immutable_Reference;
Going : Direction := Forward;
Shown_End : List_End := Beginning;
If_Empty : S_Expressions.Atom_Refs.Immutable_Reference;
Limit : Count := 0;
Prefix : S_Expressions.Atom_Refs.Immutable_Reference;
Separator : S_Expressions.Atom_Refs.Immutable_Reference;
Suffix : S_Expressions.Atom_Refs.Immutable_Reference;
Template : S_Expressions.Caches.Cursor;
end record;
procedure Read_Parameters
(Object : in out Parameters;
Expression : in out S_Expressions.Lockable.Descriptor'Class);
function Read_Parameters
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Parameters;
generic
with package Iterators is new Ada.Iterator_Interfaces (<>);
with procedure Render
(Exchange : in out Sites.Exchange;
Position : in Iterators.Cursor;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is <>;
procedure Render
(Exchange : in out Sites.Exchange;
Iterator : in Iterators.Reversible_Iterator'Class;
Param : in Parameters);
end Natools.Web.List_Templates;
|
document the new fields in the package description comment
|
list_templates: document the new fields in the package description comment
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
6f3432452c7e32c387606fbec7ff81db9adba81c
|
src/sys/os-windows/util-processes-os.adb
|
src/sys/os-windows/util-processes-os.adb
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Ada.Unchecked_Deallocation;
with Ada.Characters.Conversions;
with Util.Log.Loggers;
package body Util.Processes.Os is
use type Interfaces.C.size_t;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Os");
procedure Free is
new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array,
Name => Wchar_Ptr);
function To_WSTR (Value : in String) return Wchar_Ptr;
-- ------------------------------
-- Wait for the process to exit.
-- ------------------------------
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is
use type Util.Streams.Output_Stream_Access;
Result : DWORD;
T : DWORD;
Code : aliased DWORD;
Status : BOOL;
begin
-- Close the input stream pipe if there is one.
if Proc.Input /= null then
Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close;
end if;
if Timeout < 0.0 then
T := DWORD'Last;
else
T := DWORD (Timeout * 1000.0);
end if;
Log.Debug ("Waiting {0}", DWORD'Image (T));
Result := Wait_For_Single_Object (H => Sys.Process_Info.hProcess,
Time => T);
Log.Debug ("Status {0}", DWORD'Image (Result));
Status := Get_Exit_Code_Process (Proc => Sys.Process_Info.hProcess,
Code => Code'Unchecked_Access);
if Status = 0 then
Log.Error ("Process is still running. Error {0}", Integer'Image (Get_Last_Error));
end if;
Proc.Exit_Value := Integer (Code);
Log.Debug ("Process exit is: {0}", Integer'Image (Proc.Exit_Value));
end Wait;
-- ------------------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- ------------------------------
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is
pragma Unreferenced (Proc);
Result : Integer;
pragma Unreferenced (Result);
begin
Result := Terminate_Process (Sys.Process_Info.hProcess, DWORD (Signal));
end Stop;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class) is
Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir);
begin
Free (Sys.Dir);
if Dir'Length > 0 then
if not Ada.Directories.Exists (Dir)
or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory
then
raise Ada.Directories.Name_Error with "Invalid directory: " & Dir;
end if;
Sys.Dir := To_WSTR (Dir);
end if;
end Prepare_Working_Directory;
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
use Util.Streams.Raw;
use Ada.Characters.Conversions;
use Interfaces.C;
use type System.Address;
Result : Integer;
Startup : aliased Startup_Info;
R : BOOL;
begin
Sys.Prepare_Working_Directory (Proc);
-- Since checks are disabled, verify by hand that the argv table is correct.
if Sys.Command = null or else Sys.Command'Length < 1 then
raise Program_Error with "Invalid process argument list";
end if;
Startup.cb := Startup'Size / 8;
Startup.hStdInput := Get_Std_Handle (STD_INPUT_HANDLE);
Startup.hStdOutput := Get_Std_Handle (STD_OUTPUT_HANDLE);
Startup.hStdError := Get_Std_Handle (STD_ERROR_HANDLE);
if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then
Build_Output_Pipe (Proc, Startup);
end if;
if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then
Build_Input_Pipe (Proc, Startup);
end if;
-- Start the child process.
Result := Create_Process (System.Null_Address,
Sys.Command.all'Address,
null,
null,
True,
16#0#,
System.Null_Address,
Sys.Dir,
Startup'Unchecked_Access,
Sys.Process_Info'Unchecked_Access);
-- Close the handles which are not necessary.
if Startup.hStdInput /= Get_Std_Handle (STD_INPUT_HANDLE) then
R := Close_Handle (Startup.hStdInput);
end if;
if Startup.hStdOutput /= Get_Std_Handle (STD_OUTPUT_HANDLE) then
R := Close_Handle (Startup.hStdOutput);
end if;
if Startup.hStdError /= Get_Std_Handle (STD_ERROR_HANDLE) then
R := Close_Handle (Startup.hStdError);
end if;
if Result /= 1 then
Result := Get_Last_Error;
Log.Error ("Process creation failed: {0}", Integer'Image (Result));
raise Process_Error with "Cannot create process";
end if;
Proc.Pid := Process_Identifier (Sys.Process_Info.dwProcessId);
end Spawn;
-- ------------------------------
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
-- ------------------------------
function Create_Stream (File : in Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access is
Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream;
begin
Stream.Initialize (File);
return Stream;
end Create_Stream;
-- ------------------------------
-- Build the output pipe redirection to read the process output.
-- ------------------------------
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info) is
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Read_Pipe_Handle : aliased HANDLE;
Error_Handle : aliased HANDLE;
Result : BOOL;
Current_Proc : constant HANDLE := Get_Current_Process;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := True;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Read_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Read_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
raise Program_Error with "Cannot create pipe";
end if;
Result := Close_Handle (Read_Handle);
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Error_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 1,
Options => 2);
if Result = 0 then
raise Program_Error with "Cannot create pipe";
end if;
Into.dwFlags := 16#100#;
Into.hStdOutput := Write_Handle;
Into.hStdError := Error_Handle;
Proc.Output := Create_Stream (Read_Pipe_Handle).all'Access;
end Build_Output_Pipe;
-- ------------------------------
-- Build the input pipe redirection to write the process standard input.
-- ------------------------------
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info) is
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Write_Pipe_Handle : aliased HANDLE;
Result : BOOL;
Current_Proc : constant HANDLE := Get_Current_Process;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := True;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Write_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
raise Program_Error with "Cannot create pipe";
end if;
Result := Close_Handle (Write_Handle);
Into.dwFlags := 16#100#;
Into.hStdInput := Read_Handle;
Proc.Input := Create_Stream (Write_Pipe_Handle).all'Access;
end Build_Input_Pipe;
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
Len : Interfaces.C.size_t := Arg'Length;
begin
if Sys.Command /= null then
Len := Len + Sys.Command'Length + 2;
declare
S : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Len);
begin
S (Sys.Command'Range) := Sys.Command.all;
Free (Sys.Command);
Sys.Command := S;
end;
Sys.Command (Sys.Pos) := Interfaces.C.To_C (' ');
Sys.Pos := Sys.Pos + 1;
else
Sys.Command := new Interfaces.C.wchar_array (0 .. Len + 1);
Sys.Pos := 0;
end if;
for I in Arg'Range loop
Sys.Command (Sys.Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (Arg (I)));
Sys.Pos := Sys.Pos + 1;
end loop;
Sys.Command (Sys.Pos) := Interfaces.C.wide_nul;
end Append_Argument;
function To_WSTR (Value : in String) return Wchar_Ptr is
Result : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Value'Length + 1);
Pos : Interfaces.C.size_t := 0;
begin
for C of Value loop
Result (Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (C));
Pos := Pos + 1;
end loop;
Result (Pos) := Interfaces.C.wide_nul;
return Result;
end To_WSTR;
-- ------------------------------
-- Set the process input, output and error streams to redirect and use specified files.
-- ------------------------------
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access) is
begin
if Input'Length > 0 then
Sys.In_File := To_WSTR (Input);
end if;
if Output'Length > 0 then
Sys.Out_File := To_WSTR (Output);
Sys.Out_Append := Append_Output;
end if;
if Error'Length > 0 then
Sys.Err_File := To_WSTR (Error);
Sys.Err_Append := Append_Error;
end if;
Sys.To_Close := To_Close;
end Set_Streams;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
use type System.Address;
Result : BOOL;
pragma Unreferenced (Result);
begin
if Sys.Process_Info.hProcess /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hProcess);
Sys.Process_Info.hProcess := NO_FILE;
end if;
if Sys.Process_Info.hThread /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hThread);
Sys.Process_Info.hThread := NO_FILE;
end if;
Free (Sys.In_File);
Free (Sys.Out_File);
Free (Sys.Err_File);
Free (Sys.Dir);
Free (Sys.Command);
end Finalize;
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Ada.Unchecked_Deallocation;
with Ada.Characters.Conversions;
with Ada.Directories;
with Util.Log.Loggers;
package body Util.Processes.Os is
use type Interfaces.C.size_t;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Os");
procedure Free is
new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array,
Name => Wchar_Ptr);
function To_WSTR (Value : in String) return Wchar_Ptr;
-- ------------------------------
-- Wait for the process to exit.
-- ------------------------------
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is
use type Util.Streams.Output_Stream_Access;
Result : DWORD;
T : DWORD;
Code : aliased DWORD;
Status : BOOL;
begin
-- Close the input stream pipe if there is one.
if Proc.Input /= null then
Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close;
end if;
if Timeout < 0.0 then
T := DWORD'Last;
else
T := DWORD (Timeout * 1000.0);
end if;
Log.Debug ("Waiting {0}", DWORD'Image (T));
Result := Wait_For_Single_Object (H => Sys.Process_Info.hProcess,
Time => T);
Log.Debug ("Status {0}", DWORD'Image (Result));
Status := Get_Exit_Code_Process (Proc => Sys.Process_Info.hProcess,
Code => Code'Unchecked_Access);
if Status = 0 then
Log.Error ("Process is still running. Error {0}", Integer'Image (Get_Last_Error));
end if;
Proc.Exit_Value := Integer (Code);
Log.Debug ("Process exit is: {0}", Integer'Image (Proc.Exit_Value));
end Wait;
-- ------------------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- ------------------------------
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is
pragma Unreferenced (Proc);
Result : Integer;
pragma Unreferenced (Result);
begin
Result := Terminate_Process (Sys.Process_Info.hProcess, DWORD (Signal));
end Stop;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class) is
Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir);
begin
Free (Sys.Dir);
if Dir'Length > 0 then
if not Ada.Directories.Exists (Dir)
or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory
then
raise Ada.Directories.Name_Error with "Invalid directory: " & Dir;
end if;
Sys.Dir := To_WSTR (Dir);
end if;
end Prepare_Working_Directory;
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
use Util.Streams.Raw;
use Ada.Characters.Conversions;
use Interfaces.C;
use type System.Address;
Result : Integer;
Startup : aliased Startup_Info;
R : BOOL;
begin
Sys.Prepare_Working_Directory (Proc);
-- Since checks are disabled, verify by hand that the argv table is correct.
if Sys.Command = null or else Sys.Command'Length < 1 then
raise Program_Error with "Invalid process argument list";
end if;
Startup.cb := Startup'Size / 8;
Startup.hStdInput := Get_Std_Handle (STD_INPUT_HANDLE);
Startup.hStdOutput := Get_Std_Handle (STD_OUTPUT_HANDLE);
Startup.hStdError := Get_Std_Handle (STD_ERROR_HANDLE);
if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then
Build_Output_Pipe (Proc, Startup);
end if;
if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then
Build_Input_Pipe (Proc, Startup);
end if;
-- Start the child process.
Result := Create_Process (System.Null_Address,
Sys.Command.all'Address,
null,
null,
True,
16#0#,
System.Null_Address,
Sys.Dir.all'Address,
Startup'Unchecked_Access,
Sys.Process_Info'Unchecked_Access);
-- Close the handles which are not necessary.
if Startup.hStdInput /= Get_Std_Handle (STD_INPUT_HANDLE) then
R := Close_Handle (Startup.hStdInput);
end if;
if Startup.hStdOutput /= Get_Std_Handle (STD_OUTPUT_HANDLE) then
R := Close_Handle (Startup.hStdOutput);
end if;
if Startup.hStdError /= Get_Std_Handle (STD_ERROR_HANDLE) then
R := Close_Handle (Startup.hStdError);
end if;
if Result /= 1 then
Result := Get_Last_Error;
Log.Error ("Process creation failed: {0}", Integer'Image (Result));
raise Process_Error with "Cannot create process";
end if;
Proc.Pid := Process_Identifier (Sys.Process_Info.dwProcessId);
end Spawn;
-- ------------------------------
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
-- ------------------------------
function Create_Stream (File : in Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access is
Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream;
begin
Stream.Initialize (File);
return Stream;
end Create_Stream;
-- ------------------------------
-- Build the output pipe redirection to read the process output.
-- ------------------------------
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info) is
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Read_Pipe_Handle : aliased HANDLE;
Error_Handle : aliased HANDLE;
Result : BOOL;
Current_Proc : constant HANDLE := Get_Current_Process;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := True;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Read_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Read_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
raise Program_Error with "Cannot create pipe";
end if;
Result := Close_Handle (Read_Handle);
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Error_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 1,
Options => 2);
if Result = 0 then
raise Program_Error with "Cannot create pipe";
end if;
Into.dwFlags := 16#100#;
Into.hStdOutput := Write_Handle;
Into.hStdError := Error_Handle;
Proc.Output := Create_Stream (Read_Pipe_Handle).all'Access;
end Build_Output_Pipe;
-- ------------------------------
-- Build the input pipe redirection to write the process standard input.
-- ------------------------------
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info) is
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Write_Pipe_Handle : aliased HANDLE;
Result : BOOL;
Current_Proc : constant HANDLE := Get_Current_Process;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := True;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Write_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
raise Program_Error with "Cannot create pipe";
end if;
Result := Close_Handle (Write_Handle);
Into.dwFlags := 16#100#;
Into.hStdInput := Read_Handle;
Proc.Input := Create_Stream (Write_Pipe_Handle).all'Access;
end Build_Input_Pipe;
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
Len : Interfaces.C.size_t := Arg'Length;
begin
if Sys.Command /= null then
Len := Len + Sys.Command'Length + 2;
declare
S : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Len);
begin
S (Sys.Command'Range) := Sys.Command.all;
Free (Sys.Command);
Sys.Command := S;
end;
Sys.Command (Sys.Pos) := Interfaces.C.To_C (' ');
Sys.Pos := Sys.Pos + 1;
else
Sys.Command := new Interfaces.C.wchar_array (0 .. Len + 1);
Sys.Pos := 0;
end if;
for I in Arg'Range loop
Sys.Command (Sys.Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (Arg (I)));
Sys.Pos := Sys.Pos + 1;
end loop;
Sys.Command (Sys.Pos) := Interfaces.C.wide_nul;
end Append_Argument;
function To_WSTR (Value : in String) return Wchar_Ptr is
Result : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Value'Length + 1);
Pos : Interfaces.C.size_t := 0;
begin
for C of Value loop
Result (Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (C));
Pos := Pos + 1;
end loop;
Result (Pos) := Interfaces.C.wide_nul;
return Result;
end To_WSTR;
-- ------------------------------
-- Set the process input, output and error streams to redirect and use specified files.
-- ------------------------------
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access) is
begin
if Input'Length > 0 then
Sys.In_File := To_WSTR (Input);
end if;
if Output'Length > 0 then
Sys.Out_File := To_WSTR (Output);
Sys.Out_Append := Append_Output;
end if;
if Error'Length > 0 then
Sys.Err_File := To_WSTR (Error);
Sys.Err_Append := Append_Error;
end if;
Sys.To_Close := To_Close;
end Set_Streams;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
use type System.Address;
Result : BOOL;
pragma Unreferenced (Result);
begin
if Sys.Process_Info.hProcess /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hProcess);
Sys.Process_Info.hProcess := NO_FILE;
end if;
if Sys.Process_Info.hThread /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hThread);
Sys.Process_Info.hThread := NO_FILE;
end if;
Free (Sys.In_File);
Free (Sys.Out_File);
Free (Sys.Err_File);
Free (Sys.Dir);
Free (Sys.Command);
end Finalize;
end Util.Processes.Os;
|
Fix compilation on Windows
|
Fix compilation on Windows
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2f34fd67ddedd0d36cd9e78300fe20f866e76b2b
|
mat/src/gtk/mat-targets-gtkmat.adb
|
mat/src/gtk/mat-targets-gtkmat.adb
|
-----------------------------------------------------------------------
-- mat-targets-gtkmat - Gtk target management
-- 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 Glib.Error;
with Glib.Object;
with Gtk.Main;
with Gtk.Label;
with Gtk.Frame;
with MAT.Callbacks;
with MAT.Consoles.Text;
with MAT.Consoles.Gtkmat;
package body MAT.Targets.Gtkmat is
-- ------------------------------
-- Initialize the target instance.
-- ------------------------------
overriding
procedure Initialize (Target : in out Target_Type) is
begin
Target.Options.Interactive := False;
Target.Options.Graphical := True;
Target.Console := new MAT.Consoles.Text.Console_Type;
end Initialize;
-- ------------------------------
-- Initialize the widgets and create the Gtk gui.
-- ------------------------------
procedure Initialize_Widget (Target : in out Target_Type;
Widget : out Gtk.Widget.Gtk_Widget) is
Error : aliased Glib.Error.GError;
Result : Glib.Guint;
begin
if Target.Options.Graphical then
Gtk.Main.Init;
Gtkada.Builder.Gtk_New (Target.Builder);
Result := Target.Builder.Add_From_File ("mat.glade", Error'Access);
MAT.Callbacks.Initialize (Target'Unchecked_Access, Target.Builder);
Target.Builder.Do_Connect;
Widget := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main"));
Target.Gtk_Console := new MAT.Consoles.Gtkmat.Console_Type;
Target.Gtk_Console.Initialize
(Gtk.Frame.Gtk_Frame (Target.Builder.Get_Object ("consoleFrame")));
Target.Console := Target.Gtk_Console.all'Access;
else
Widget := null;
end if;
end Initialize_Widget;
-- ------------------------------
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
-- ------------------------------
overriding
procedure Interactive (Target : in out Target_Type) is
Main : Gtk.Widget.Gtk_Widget;
begin
if Target.Options.Graphical then
Main := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main"));
Main.Show_All;
end if;
if Target.Options.Interactive and Target.Options.Graphical then
Target.Gui_Task.Start (Target'Unchecked_Access);
end if;
if Target.Options.Graphical then
Gtk.Main.Main;
else
MAT.Targets.Target_Type (Target).Interactive;
end if;
end Interactive;
task body Gtk_Loop is
Main : Target_Type_Access;
begin
select
accept Start (Target : in Target_Type_Access) do
Main := Target;
end Start;
MAT.Targets.Target_Type (Main.all).Interactive;
or
terminate;
end select;
end Gtk_Loop;
-- ------------------------------
-- Set the UI label with the given value.
-- ------------------------------
procedure Set_Label (Target : in Target_Type;
Name : in String;
Value : in String) is
use type Glib.Object.GObject;
Object : constant Glib.Object.GObject := Target.Builder.Get_Object (Name);
Label : Gtk.Label.Gtk_Label;
begin
if Object /= null then
Label := Gtk.Label.Gtk_Label (Object);
Label.Set_Label (Value);
end if;
end Set_Label;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
overriding
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access) is
begin
MAT.Targets.Target_Type (Target).Create_Process (Pid, Path, Process);
Target.Set_Label ("process_info", "Pid:" & MAT.Types.Target_Process_Ref'Image (Pid));
end Create_Process;
-- ------------------------------
-- Refresh the information about the current process.
-- ------------------------------
procedure Refresh_Process (Target : in out Target_Type) is
use type MAT.Events.Targets.Target_Events_Access;
Counter : Integer;
Stats : MAT.Memory.Targets.Memory_Stat;
begin
if Target.Current = null or else Target.Current.Events = null then
return;
end if;
Counter := Target.Current.Events.Get_Event_Counter;
if Counter = Target.Previous_Event_Counter then
return;
end if;
Target.Previous_Event_Counter := Counter;
Target.Set_Label ("event_info", "Events:" & Integer'Image (Counter));
Target.Current.Memory.Stat_Information (Stats);
Target.Set_Label ("thread_info", "Threads:"
& Natural'Image (Stats.Thread_Count));
Target.Set_Label ("mem_used_info", "Used:"
& MAT.Types.Target_Size'Image (Stats.Total_Alloc));
Target.Set_Label ("mem_free_info", "Free:"
& MAT.Types.Target_Size'Image (Stats.Total_Free));
end Refresh_Process;
end MAT.Targets.Gtkmat;
|
-----------------------------------------------------------------------
-- mat-targets-gtkmat - Gtk target management
-- 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 Glib.Error;
with Glib.Object;
with Gtk.Main;
with Gtk.Label;
with Gtk.Frame;
with MAT.Callbacks;
with MAT.Consoles.Text;
with MAT.Consoles.Gtkmat;
package body MAT.Targets.Gtkmat is
-- ------------------------------
-- Initialize the target instance.
-- ------------------------------
overriding
procedure Initialize (Target : in out Target_Type) is
begin
Target.Options.Interactive := False;
Target.Options.Graphical := True;
Target.Console := new MAT.Consoles.Text.Console_Type;
end Initialize;
-- ------------------------------
-- Release the storage.
-- ------------------------------
overriding
procedure Finalize (Target : in out Target_Type) is
use type Gtk.Widget.Gtk_Widget;
begin
if Target.Main /= null then
Target.Main.Destroy;
Target.About.Destroy;
Target.Chooser.Destroy;
end if;
end Finalize;
-- ------------------------------
-- Initialize the widgets and create the Gtk gui.
-- ------------------------------
procedure Initialize_Widget (Target : in out Target_Type;
Widget : out Gtk.Widget.Gtk_Widget) is
Error : aliased Glib.Error.GError;
Result : Glib.Guint;
begin
if Target.Options.Graphical then
Gtk.Main.Init;
Gtkada.Builder.Gtk_New (Target.Builder);
Result := Target.Builder.Add_From_File ("mat.glade", Error'Access);
MAT.Callbacks.Initialize (Target'Unchecked_Access, Target.Builder);
Target.Builder.Do_Connect;
Widget := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main"));
Target.Main := Widget;
Target.About := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("about"));
Target.Chooser := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("filechooser"));
Target.Gtk_Console := new MAT.Consoles.Gtkmat.Console_Type;
Target.Gtk_Console.Initialize
(Gtk.Frame.Gtk_Frame (Target.Builder.Get_Object ("consoleFrame")));
Target.Console := Target.Gtk_Console.all'Access;
else
Widget := null;
end if;
end Initialize_Widget;
-- ------------------------------
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
-- ------------------------------
overriding
procedure Interactive (Target : in out Target_Type) is
Main : Gtk.Widget.Gtk_Widget;
begin
if Target.Options.Graphical then
Main := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main"));
Main.Show_All;
end if;
if Target.Options.Interactive and Target.Options.Graphical then
Target.Gui_Task.Start (Target'Unchecked_Access);
end if;
if Target.Options.Graphical then
Gtk.Main.Main;
else
MAT.Targets.Target_Type (Target).Interactive;
end if;
end Interactive;
task body Gtk_Loop is
Main : Target_Type_Access;
begin
select
accept Start (Target : in Target_Type_Access) do
Main := Target;
end Start;
MAT.Targets.Target_Type (Main.all).Interactive;
or
terminate;
end select;
end Gtk_Loop;
-- ------------------------------
-- Set the UI label with the given value.
-- ------------------------------
procedure Set_Label (Target : in Target_Type;
Name : in String;
Value : in String) is
use type Glib.Object.GObject;
Object : constant Glib.Object.GObject := Target.Builder.Get_Object (Name);
Label : Gtk.Label.Gtk_Label;
begin
if Object /= null then
Label := Gtk.Label.Gtk_Label (Object);
Label.Set_Label (Value);
end if;
end Set_Label;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
overriding
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access) is
begin
MAT.Targets.Target_Type (Target).Create_Process (Pid, Path, Process);
Target.Set_Label ("process_info", "Pid:" & MAT.Types.Target_Process_Ref'Image (Pid));
end Create_Process;
-- ------------------------------
-- Refresh the information about the current process.
-- ------------------------------
procedure Refresh_Process (Target : in out Target_Type) is
use type MAT.Events.Targets.Target_Events_Access;
Counter : Integer;
Stats : MAT.Memory.Targets.Memory_Stat;
begin
if Target.Current = null or else Target.Current.Events = null then
return;
end if;
Counter := Target.Current.Events.Get_Event_Counter;
if Counter = Target.Previous_Event_Counter then
return;
end if;
Target.Previous_Event_Counter := Counter;
Target.Set_Label ("event_info", "Events:" & Integer'Image (Counter));
Target.Current.Memory.Stat_Information (Stats);
Target.Set_Label ("thread_info", "Threads:"
& Natural'Image (Stats.Thread_Count));
Target.Set_Label ("mem_used_info", "Used:"
& MAT.Types.Target_Size'Image (Stats.Total_Alloc));
Target.Set_Label ("mem_free_info", "Free:"
& MAT.Types.Target_Size'Image (Stats.Total_Free));
end Refresh_Process;
end MAT.Targets.Gtkmat;
|
Implement the Finalize procedure to release some widgets and other data
|
Implement the Finalize procedure to release some widgets and other data
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
b4be8b307c62d0c7ed6e0460371b9869140f776a
|
src/sys/os-freebsd32/util-systems-constants.ads
|
src/sys/os-freebsd32/util-systems-constants.ads
|
-- Generated by utildgen.c from system includes
with Interfaces.C;
package Util.Systems.Constants is
pragma Pure;
-- Flags used when opening a file with open/creat.
O_RDONLY : constant Interfaces.C.int := 8#000000#;
O_WRONLY : constant Interfaces.C.int := 8#000001#;
O_RDWR : constant Interfaces.C.int := 8#000002#;
O_CREAT : constant Interfaces.C.int := 8#001000#;
O_EXCL : constant Interfaces.C.int := 8#004000#;
O_TRUNC : constant Interfaces.C.int := 8#002000#;
O_APPEND : constant Interfaces.C.int := 8#000010#;
O_CLOEXEC : constant Interfaces.C.int := 8#4000000#;
O_SYNC : constant Interfaces.C.int := 8#000200#;
O_DIRECT : constant Interfaces.C.int := 8#200000#;
O_NONBLOCK : constant Interfaces.C.int := 8#000004#;
-- Flags used by fcntl
F_SETFL : constant Interfaces.C.int := 4;
F_GETFL : constant Interfaces.C.int := 3;
FD_CLOEXEC : constant Interfaces.C.int := 1;
-- Flags used by dlopen
RTLD_LAZY : constant Interfaces.C.int := 8#000001#;
RTLD_NOW : constant Interfaces.C.int := 8#000002#;
RTLD_NOLOAD : constant Interfaces.C.int := 8#020000#;
RTLD_DEEPBIND : constant Interfaces.C.int := 8#000000#;
RTLD_GLOBAL : constant Interfaces.C.int := 8#000400#;
RTLD_LOCAL : constant Interfaces.C.int := 8#000000#;
RTLD_NODELETE : constant Interfaces.C.int := 8#010000#;
DLL_OPTIONS : constant String := "-ldl";
end Util.Systems.Constants;
|
-- Generated by utildgen.c from system includes
with Interfaces.C;
package Util.Systems.Constants is
pragma Pure;
-- Flags used when opening a file with open/creat.
O_RDONLY : constant Interfaces.C.int := 8#000000#;
O_WRONLY : constant Interfaces.C.int := 8#000001#;
O_RDWR : constant Interfaces.C.int := 8#000002#;
O_CREAT : constant Interfaces.C.int := 8#001000#;
O_EXCL : constant Interfaces.C.int := 8#004000#;
O_TRUNC : constant Interfaces.C.int := 8#002000#;
O_APPEND : constant Interfaces.C.int := 8#000010#;
O_CLOEXEC : constant Interfaces.C.int := 8#4000000#;
O_SYNC : constant Interfaces.C.int := 8#000200#;
O_DIRECT : constant Interfaces.C.int := 8#200000#;
O_NONBLOCK : constant Interfaces.C.int := 8#000004#;
-- Flags used by fcntl
F_SETFL : constant Interfaces.C.int := 4;
F_GETFL : constant Interfaces.C.int := 3;
FD_CLOEXEC : constant Interfaces.C.int := 1;
-- Flags used by dlopen
RTLD_LAZY : constant Interfaces.C.int := 8#000001#;
RTLD_NOW : constant Interfaces.C.int := 8#000002#;
RTLD_NOLOAD : constant Interfaces.C.int := 8#020000#;
RTLD_DEEPBIND : constant Interfaces.C.int := 8#000000#;
RTLD_GLOBAL : constant Interfaces.C.int := 8#000400#;
RTLD_LOCAL : constant Interfaces.C.int := 8#000000#;
RTLD_NODELETE : constant Interfaces.C.int := 8#010000#;
DLL_OPTIONS : constant String := "-ldl";
SYMBOL_PREFIX : constant String := "";
end Util.Systems.Constants;
|
Declare SYMBOL_PREFIX
|
Declare SYMBOL_PREFIX
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c20f2969d680ac7c4c37c824a493c9aa0d6ade2a
|
src/natools-s_expressions-generic_caches.adb
|
src/natools-s_expressions-generic_caches.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Generic_Caches is
--------------------
-- Tree Interface --
--------------------
procedure Append
(Exp : in out Tree;
Kind : in Node_Kind;
Data : in Atom_Access := null)
is
N : Node_Access;
begin
case Kind is
when Atom_Node =>
N := new Node'(Kind => Atom_Node,
Parent | Next => null, Data => Data);
when List_Node =>
N := new Node'(Kind => List_Node, Parent | Next | Child => null);
end case;
if Exp.Root = null then
pragma Assert (Exp.Last = null);
Exp.Root := N;
else
pragma Assert (Exp.Last /= null);
if Exp.Opening then
pragma Assert (Exp.Last.Kind = List_Node);
pragma Assert (Exp.Last.Child = null);
Exp.Last.Child := N;
N.Parent := Exp.Last;
else
pragma Assert (Exp.Last.Next = null);
Exp.Last.Next := N;
N.Parent := Exp.Last.Parent;
end if;
end if;
Exp.Last := N;
Exp.Opening := Kind = List_Node;
end Append;
procedure Close_List (Exp : in out Tree) is
begin
if Exp.Opening then
Exp.Opening := False;
elsif Exp.Last /= null and then Exp.Last.Parent /= null then
Exp.Last := Exp.Last.Parent;
end if;
end Close_List;
function Create_Tree return Tree is
begin
return Tree'(Ada.Finalization.Limited_Controlled
with Root | Last => null, Opening => False);
end Create_Tree;
function Duplicate (Source : Tree) return Tree is
function Dup_List (First, Parent : Node_Access) return Node_Access;
function Dup_Node (N, Parent : Node_Access) return Node_Access;
New_Last : Node_Access := null;
function Dup_List (First, Parent : Node_Access) return Node_Access is
Source : Node_Access := First;
Result, Target : Node_Access;
begin
if First = null then
return null;
end if;
Result := Dup_Node (First, Parent);
Target := Result;
loop
Source := Source.Next;
exit when Source = null;
Target.Next := Dup_Node (Source, Parent);
Target := Target.Next;
end loop;
return Result;
end Dup_List;
function Dup_Node (N, Parent : Node_Access) return Node_Access is
Result : Node_Access;
begin
if N = null then
return null;
end if;
case N.Kind is
when Atom_Node =>
Result := new Node'(Kind => Atom_Node,
Parent => Parent,
Next => null,
Data => new Atom'(N.Data.all));
when List_Node =>
Result := new Node'(Kind => List_Node,
Parent => Parent,
Next => null,
Child => Dup_List (N.Child, N));
end case;
if N = Source.Last then
New_Last := Result;
end if;
return Result;
end Dup_Node;
begin
return Result : Tree do
Result.Root := Dup_List (Source.Root, null);
pragma Assert ((New_Last = null) = (Source.Last = null));
Result.Last := New_Last;
Result.Opening := Source.Opening;
end return;
end Duplicate;
overriding procedure Finalize (Object : in out Tree) is
procedure List_Free (First : in out Node_Access);
procedure List_Free (First : in out Node_Access) is
Next : Node_Access := First;
Cur : Node_Access;
begin
while Next /= null loop
Cur := Next;
case Cur.Kind is
when Atom_Node =>
Unchecked_Free (Cur.Data);
when List_Node =>
List_Free (Cur.Child);
end case;
Next := Cur.Next;
Unchecked_Free (Cur);
end loop;
First := null;
end List_Free;
begin
List_Free (Object.Root);
Object.Last := null;
Object.Opening := False;
end Finalize;
-----------------------
-- Writing Interface --
-----------------------
function Duplicate (Cache : Reference) return Reference is
function Dup_Tree return Tree;
function Dup_Tree return Tree is
begin
return Duplicate (Cache.Exp.Query.Data.all);
end Dup_Tree;
begin
return Reference'(Exp => Trees.Create (Dup_Tree'Access));
end Duplicate;
-----------------------
-- Printer Interface --
-----------------------
overriding procedure Open_List (Output : in out Reference) is
begin
Output.Exp.Update.Data.Append (List_Node);
end Open_List;
overriding procedure Append_Atom
(Output : in out Reference; Data : in Atom) is
begin
if Output.Exp.Is_Empty then
Output.Exp.Replace (Create_Tree'Access);
end if;
Output.Exp.Update.Data.Append (Atom_Node, new Atom'(Data));
end Append_Atom;
overriding procedure Close_List (Output : in out Reference) is
begin
Output.Exp.Update.Data.Close_List;
end Close_List;
-------------------------
-- Reading Subprograms --
-------------------------
function First (Cache : Reference'Class) return Cursor is
N : Node_Access;
begin
if Cache.Exp.Is_Empty then
return Cursor'(others => <>);
else
N := Cache.Exp.Query.Data.Root;
pragma Assert (N /= null);
return Cursor'(Exp => Cache.Exp, Position => N,
Opening => N.Kind = List_Node);
end if;
end First;
--------------------------
-- Descriptor Interface --
--------------------------
overriding function Current_Event (Object : in Cursor)
return Events.Event is
begin
if Object.Position = null then
return Events.End_Of_Input;
end if;
case Object.Position.Kind is
when Atom_Node =>
return Events.Add_Atom;
when List_Node =>
if Object.Opening then
return Events.Open_List;
else
return Events.Close_List;
end if;
end case;
end Current_Event;
overriding function Current_Atom (Object : in Cursor) return Atom is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
return Object.Position.Data.all;
end Current_Atom;
overriding function Current_Level (Object : in Cursor) return Natural is
Result : Natural := 0;
N : Node_Access := Object.Position;
begin
while N /= null loop
Result := Result + 1;
N := N.Parent;
end loop;
return Natural'Max (Result, 1) - 1;
end Current_Level;
overriding procedure Query_Atom
(Object : in Cursor;
Process : not null access procedure (Data : in Atom)) is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
Process.all (Object.Position.Data.all);
end Query_Atom;
overriding procedure Read_Atom
(Object : in Cursor;
Data : out Atom;
Length : out Count)
is
Transferred : Count;
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
Length := Object.Position.Data'Length;
Transferred := Count'Min (Data'Length, Length);
Data (Data'First .. Data'First + Transferred - 1)
:= Object.Position.Data (Object.Position.Data'First
.. Object.Position.Data'First + Transferred - 1);
end Read_Atom;
overriding procedure Next
(Object : in out Cursor;
Event : out Events.Event) is
begin
if Object.Position = null then
Event := Events.Error;
return;
end if;
if Object.Opening then
pragma Assert (Object.Position.Kind = List_Node);
if Object.Position.Child = null then
Object.Opening := False;
else
pragma Assert (Object.Position.Child.Parent = Object.Position);
Object.Position := Object.Position.Child;
Object.Opening := Object.Position.Kind = List_Node;
end if;
elsif Object.Position.Next /= null then
pragma Assert (Object.Position.Next.Parent = Object.Position.Parent);
Object.Position := Object.Position.Next;
Object.Opening := Object.Position.Kind = List_Node;
elsif Object.Position.Parent /= null then
pragma Assert (Object.Position.Parent.Kind = List_Node);
Object.Position := Object.Position.Parent;
Object.Opening := False;
else
Object.Position := null;
end if;
Event := Object.Current_Event;
end Next;
end Natools.S_Expressions.Generic_Caches;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Generic_Caches is
--------------------
-- Tree Interface --
--------------------
procedure Append
(Exp : in out Tree;
Kind : in Node_Kind;
Data : in Atom_Access := null)
is
N : Node_Access;
begin
case Kind is
when Atom_Node =>
N := new Node'(Kind => Atom_Node,
Parent | Next => null, Data => Data);
when List_Node =>
N := new Node'(Kind => List_Node, Parent | Next | Child => null);
end case;
if Exp.Root = null then
pragma Assert (Exp.Last = null);
Exp.Root := N;
else
pragma Assert (Exp.Last /= null);
if Exp.Opening then
pragma Assert (Exp.Last.Kind = List_Node);
pragma Assert (Exp.Last.Child = null);
Exp.Last.Child := N;
N.Parent := Exp.Last;
else
pragma Assert (Exp.Last.Next = null);
Exp.Last.Next := N;
N.Parent := Exp.Last.Parent;
end if;
end if;
Exp.Last := N;
Exp.Opening := Kind = List_Node;
end Append;
procedure Close_List (Exp : in out Tree) is
begin
if Exp.Opening then
Exp.Opening := False;
elsif Exp.Last /= null and then Exp.Last.Parent /= null then
Exp.Last := Exp.Last.Parent;
end if;
end Close_List;
function Create_Tree return Tree is
begin
return Tree'(Ada.Finalization.Limited_Controlled
with Root | Last => null, Opening => False);
end Create_Tree;
function Duplicate (Source : Tree) return Tree is
function Dup_List (First, Parent : Node_Access) return Node_Access;
function Dup_Node (N, Parent : Node_Access) return Node_Access;
New_Last : Node_Access := null;
function Dup_List (First, Parent : Node_Access) return Node_Access is
Source : Node_Access := First;
Result, Target : Node_Access;
begin
if First = null then
return null;
end if;
Result := Dup_Node (First, Parent);
Target := Result;
loop
Source := Source.Next;
exit when Source = null;
Target.Next := Dup_Node (Source, Parent);
Target := Target.Next;
end loop;
return Result;
end Dup_List;
function Dup_Node (N, Parent : Node_Access) return Node_Access is
Result : Node_Access;
begin
if N = null then
return null;
end if;
case N.Kind is
when Atom_Node =>
Result := new Node'(Kind => Atom_Node,
Parent => Parent,
Next => null,
Data => new Atom'(N.Data.all));
when List_Node =>
Result := new Node'(Kind => List_Node,
Parent => Parent,
Next => null,
Child => null);
Result.Child := Dup_List (N.Child, Result);
end case;
if N = Source.Last then
New_Last := Result;
end if;
return Result;
end Dup_Node;
begin
return Result : Tree do
Result.Root := Dup_List (Source.Root, null);
pragma Assert ((New_Last = null) = (Source.Last = null));
Result.Last := New_Last;
Result.Opening := Source.Opening;
end return;
end Duplicate;
overriding procedure Finalize (Object : in out Tree) is
procedure List_Free (First : in out Node_Access);
procedure List_Free (First : in out Node_Access) is
Next : Node_Access := First;
Cur : Node_Access;
begin
while Next /= null loop
Cur := Next;
case Cur.Kind is
when Atom_Node =>
Unchecked_Free (Cur.Data);
when List_Node =>
List_Free (Cur.Child);
end case;
Next := Cur.Next;
Unchecked_Free (Cur);
end loop;
First := null;
end List_Free;
begin
List_Free (Object.Root);
Object.Last := null;
Object.Opening := False;
end Finalize;
-----------------------
-- Writing Interface --
-----------------------
function Duplicate (Cache : Reference) return Reference is
function Dup_Tree return Tree;
function Dup_Tree return Tree is
begin
return Duplicate (Cache.Exp.Query.Data.all);
end Dup_Tree;
begin
return Reference'(Exp => Trees.Create (Dup_Tree'Access));
end Duplicate;
-----------------------
-- Printer Interface --
-----------------------
overriding procedure Open_List (Output : in out Reference) is
begin
Output.Exp.Update.Data.Append (List_Node);
end Open_List;
overriding procedure Append_Atom
(Output : in out Reference; Data : in Atom) is
begin
if Output.Exp.Is_Empty then
Output.Exp.Replace (Create_Tree'Access);
end if;
Output.Exp.Update.Data.Append (Atom_Node, new Atom'(Data));
end Append_Atom;
overriding procedure Close_List (Output : in out Reference) is
begin
Output.Exp.Update.Data.Close_List;
end Close_List;
-------------------------
-- Reading Subprograms --
-------------------------
function First (Cache : Reference'Class) return Cursor is
N : Node_Access;
begin
if Cache.Exp.Is_Empty then
return Cursor'(others => <>);
else
N := Cache.Exp.Query.Data.Root;
pragma Assert (N /= null);
return Cursor'(Exp => Cache.Exp, Position => N,
Opening => N.Kind = List_Node);
end if;
end First;
--------------------------
-- Descriptor Interface --
--------------------------
overriding function Current_Event (Object : in Cursor)
return Events.Event is
begin
if Object.Position = null then
return Events.End_Of_Input;
end if;
case Object.Position.Kind is
when Atom_Node =>
return Events.Add_Atom;
when List_Node =>
if Object.Opening then
return Events.Open_List;
else
return Events.Close_List;
end if;
end case;
end Current_Event;
overriding function Current_Atom (Object : in Cursor) return Atom is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
return Object.Position.Data.all;
end Current_Atom;
overriding function Current_Level (Object : in Cursor) return Natural is
Result : Natural := 0;
N : Node_Access := Object.Position;
begin
while N /= null loop
Result := Result + 1;
N := N.Parent;
end loop;
return Natural'Max (Result, 1) - 1;
end Current_Level;
overriding procedure Query_Atom
(Object : in Cursor;
Process : not null access procedure (Data : in Atom)) is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
Process.all (Object.Position.Data.all);
end Query_Atom;
overriding procedure Read_Atom
(Object : in Cursor;
Data : out Atom;
Length : out Count)
is
Transferred : Count;
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
Length := Object.Position.Data'Length;
Transferred := Count'Min (Data'Length, Length);
Data (Data'First .. Data'First + Transferred - 1)
:= Object.Position.Data (Object.Position.Data'First
.. Object.Position.Data'First + Transferred - 1);
end Read_Atom;
overriding procedure Next
(Object : in out Cursor;
Event : out Events.Event) is
begin
if Object.Position = null then
Event := Events.Error;
return;
end if;
if Object.Opening then
pragma Assert (Object.Position.Kind = List_Node);
if Object.Position.Child = null then
Object.Opening := False;
else
pragma Assert (Object.Position.Child.Parent = Object.Position);
Object.Position := Object.Position.Child;
Object.Opening := Object.Position.Kind = List_Node;
end if;
elsif Object.Position.Next /= null then
pragma Assert (Object.Position.Next.Parent = Object.Position.Parent);
Object.Position := Object.Position.Next;
Object.Opening := Object.Position.Kind = List_Node;
elsif Object.Position.Parent /= null then
pragma Assert (Object.Position.Parent.Kind = List_Node);
Object.Position := Object.Position.Parent;
Object.Opening := False;
else
Object.Position := null;
end if;
Event := Object.Current_Event;
end Next;
end Natools.S_Expressions.Generic_Caches;
|
fix duplication of child lists
|
s_expressions-generic_caches: fix duplication of child lists
|
Ada
|
isc
|
faelys/natools
|
c738648dd8e4d148b624c6514c431fa359affbfe
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Objects.Time;
with ADO;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
package AWA.Wikis.Beans is
type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record
-- The wiki module instance.
Module : Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_View_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_View_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the information about the wiki page to display it.
overriding
procedure Load (Bean : in out Wiki_View_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_View_Bean bean instance.
function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Service : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Service : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Service : Modules.Wiki_Module_Access := null;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Objects.Time;
with ADO;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
package AWA.Wikis.Beans is
type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record
-- The wiki module instance.
Module : Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_View_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_View_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the information about the wiki page to display it.
overriding
procedure Load (Bean : in out Wiki_View_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_View_Bean bean instance.
function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
Rename Service into Module in the bean record declarations
|
Rename Service into Module in the bean record declarations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
aaf606711bbb96962d8cb251d12d057dc0a289f4
|
src/gen-model.ads
|
src/gen-model.ads
|
-----------------------------------------------------------------------
-- gen-model -- Model for Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Util.Log;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Objects.Maps;
with DOM.Core;
package Gen.Model is
-- Exception raised if a name is already registered in the model.
-- This exception is raised if a table, an enum is already defined.
Name_Exist : exception;
-- ------------------------------
-- Model Definition
-- ------------------------------
type Definition is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with private;
type Definition_Access is access all Definition'Class;
-- Prepare the generation of the model.
procedure Prepare (O : in out Definition) is null;
-- Get the object unique name.
function Get_Name (From : in Definition) return String;
function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String;
-- Set the object unique name.
procedure Set_Name (Def : in out Definition;
Name : in String);
procedure Set_Name (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String);
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Attribute (From : in Definition;
Name : in String) return String;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Attribute (From : in Definition;
Name : in String) return Ada.Strings.Unbounded.Unbounded_String;
-- Set the comment associated with the element.
procedure Set_Comment (Def : in out Definition;
Comment : in String);
-- Get the comment associated with the element.
function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object;
-- Set the location (file and line) where the model element is defined in the XMI file.
procedure Set_Location (Node : in out Definition;
Location : in String);
-- Get the location file and line where the model element is defined.
function Get_Location (Node : in Definition) return String;
-- Initialize the definition from the DOM node attributes.
procedure Initialize (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Node : in DOM.Core.Node);
-- Validate the definition by checking and reporting problems to the logger interface.
procedure Validate (Def : in out Definition;
Log : in out Util.Log.Logging'Class);
private
type Definition is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with record
Row_Index : Natural;
Def_Name : Ada.Strings.Unbounded.Unbounded_String;
Attrs : Util.Beans.Objects.Maps.Map_Bean;
Comment : Util.Beans.Objects.Object;
Location : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Gen.Model;
|
-----------------------------------------------------------------------
-- gen-model -- Model for Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Util.Log;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Objects.Maps;
with DOM.Core;
package Gen.Model is
-- Exception raised if a name is already registered in the model.
-- This exception is raised if a table, an enum is already defined.
Name_Exist : exception;
-- ------------------------------
-- Model Definition
-- ------------------------------
type Definition is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with private;
type Definition_Access is access all Definition'Class;
-- Prepare the generation of the model.
procedure Prepare (O : in out Definition) is null;
-- Get the object unique name.
function Get_Name (From : in Definition) return String;
function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String;
-- Set the object unique name.
procedure Set_Name (Def : in out Definition;
Name : in String);
procedure Set_Name (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String);
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Attribute (From : in Definition;
Name : in String) return String;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Attribute (From : in Definition;
Name : in String) return Ada.Strings.Unbounded.Unbounded_String;
-- Set the comment associated with the element.
procedure Set_Comment (Def : in out Definition;
Comment : in String);
-- Get the comment associated with the element.
function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object;
-- Set the location (file and line) where the model element is defined in the XMI file.
procedure Set_Location (Node : in out Definition;
Location : in String);
-- Get the location file and line where the model element is defined.
function Get_Location (Node : in Definition) return String;
-- Initialize the definition from the DOM node attributes.
procedure Initialize (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Node : in DOM.Core.Node);
-- Validate the definition by checking and reporting problems to the logger interface.
procedure Validate (Def : in out Definition;
Log : in out Util.Log.Logging'Class);
private
procedure Set_Index (Def : in out Definition;
Index : in Natural);
type Definition is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with record
Row_Index : Natural;
Def_Name : Ada.Strings.Unbounded.Unbounded_String;
Attrs : Util.Beans.Objects.Maps.Map_Bean;
Comment : Util.Beans.Objects.Object;
Location : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Gen.Model;
|
Declare the Set_Index procedure for a workarround on GNAT 2020 issue
|
Declare the Set_Index procedure for a workarround on GNAT 2020 issue
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
3c04f38bed4fd37c31e12b69dabfc00678d0d1cb
|
components/src/io_expander/MCP23xxx/mcp23x08.adb
|
components/src/io_expander/MCP23xxx/mcp23x08.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2018, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with HAL.GPIO; use HAL.GPIO;
package body MCP23x08 is
function To_UInt8 is
new Ada.Unchecked_Conversion (Source => ALl_IO_Array,
Target => UInt8);
function To_All_IO_Array is
new Ada.Unchecked_Conversion (Source => UInt8,
Target => ALl_IO_Array);
procedure Loc_IO_Write
(This : in out MCP23x08_IO_Expander'Class;
WriteAddr : Register_Address;
Value : UInt8)
with Inline_Always;
procedure Loc_IO_Read
(This : MCP23x08_IO_Expander'Class;
ReadAddr : Register_Address;
Value : out UInt8)
with Inline_Always;
procedure Set_Bit
(This : in out MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin);
procedure Clear_Bit
(This : in out MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin);
function Read_Bit
(This : MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin)
return Boolean;
------------------
-- Loc_IO_Write --
------------------
procedure Loc_IO_Write
(This : in out MCP23x08_IO_Expander'Class;
WriteAddr : Register_Address;
Value : UInt8)
is
begin
IO_Write (This, WriteAddr, Value);
end Loc_IO_Write;
-----------------
-- Loc_IO_Read --
-----------------
procedure Loc_IO_Read
(This : MCP23x08_IO_Expander'Class;
ReadAddr : Register_Address;
Value : out UInt8)
is
begin
IO_Read (This, ReadAddr, Value);
end Loc_IO_Read;
-------------
-- Set_Bit --
-------------
procedure Set_Bit
(This : in out MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin)
is
Prev, Next : UInt8;
begin
Loc_IO_Read (This, RegAddr, Prev);
Next := Prev or Pin'Enum_Rep;
if Next /= Prev then
Loc_IO_Write (This, RegAddr, Next);
end if;
end Set_Bit;
---------------
-- Clear_Bit --
---------------
procedure Clear_Bit
(This : in out MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin)
is
Prev, Next : UInt8;
begin
Loc_IO_Read (This, RegAddr, Prev);
Next := Prev and (not Pin'Enum_Rep);
if Next /= Prev then
Loc_IO_Write (This, RegAddr, Next);
end if;
end Clear_Bit;
--------------
-- Read_Bit --
--------------
function Read_Bit
(This : MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin)
return Boolean
is
Reg : UInt8;
begin
Loc_IO_Read (This, RegAddr, Reg);
return (Reg and Pin'Enum_Rep) /= 0;
end Read_Bit;
---------------
-- Configure --
---------------
procedure Configure (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin;
Output : Boolean;
Pull_Up : Boolean)
is
begin
This.Configure_Mode (Pin, Output);
This.Configure_Pull (Pin, Pull_Up);
end Configure;
procedure Configure_Mode (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin;
Output : Boolean)
is
begin
if Output then
Clear_Bit (This, IO_DIRECTION_REG, Pin);
else
Set_Bit (This, IO_DIRECTION_REG, Pin);
end if;
end Configure_Mode;
---------------
-- Is_Output --
---------------
function Is_Output (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
return Boolean
is
begin
return not Read_Bit (This, IO_DIRECTION_REG, Pin);
end Is_Output;
--------------------
-- Configure_Pull --
--------------------
procedure Configure_Pull (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin;
Pull_Up : Boolean)
is
begin
if Pull_Up then
Set_Bit (This, PULL_UP_REG, Pin);
else
Clear_Bit (This, PULL_UP_REG, Pin);
end if;
end Configure_Pull;
-------------
-- Pull_Up --
-------------
function Pull_Up (This : MCP23x08_IO_Expander;
Pin : MCP23x08_Pin) return Boolean
is
begin
return Read_Bit (This, PULL_UP_REG, Pin);
end Pull_Up;
---------
-- Set --
---------
function Set (This : MCP23x08_IO_Expander;
Pin : MCP23x08_Pin) return Boolean
is
Val : UInt8;
begin
Loc_IO_Read (This, LOGIC_LEVLEL_REG, Val);
return (Pin'Enum_Rep and Val) /= 0;
end Set;
---------
-- Set --
---------
procedure Set (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
is
begin
Set_Bit (This, LOGIC_LEVLEL_REG, Pin);
end Set;
-----------
-- Clear --
-----------
procedure Clear (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
is
begin
Clear_Bit (This, LOGIC_LEVLEL_REG, Pin);
end Clear;
------------
-- Toggle --
------------
procedure Toggle (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
is
begin
if This.Set (Pin) then
This.Clear (Pin);
else
This.Set (Pin);
end if;
end Toggle;
------------
-- All_IO --
------------
function All_IO (This : in out MCP23x08_IO_Expander) return ALl_IO_Array is
Val : UInt8;
begin
Loc_IO_Read (This, LOGIC_LEVLEL_REG, Val);
return To_All_IO_Array (Val);
end All_IO;
----------------
-- Set_All_IO --
----------------
procedure Set_All_IO (This : in out MCP23x08_IO_Expander; IOs : ALl_IO_Array) is
begin
Loc_IO_Write (This, LOGIC_LEVLEL_REG, To_UInt8 (IOs));
end Set_All_IO;
-------------------
-- As_GPIO_Point --
-------------------
function As_GPIO_Point (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
return not null HAL.GPIO.Any_GPIO_Point
is
begin
This.Points (Pin) := (Device => This'Unchecked_Access,
Pin => Pin);
return This.Points (Pin)'Unchecked_Access;
end As_GPIO_Point;
----------
-- Mode --
----------
overriding
function Mode (This : MCP23_GPIO_Point) return HAL.GPIO.GPIO_Mode is
pragma Unreferenced (This);
begin
return HAL.GPIO.Output;
end Mode;
--------------
-- Set_Mode --
--------------
overriding
procedure Set_Mode (This : in out MCP23_GPIO_Point;
Mode : HAL.GPIO.GPIO_Config_Mode)
is
begin
This.Device.Configure_Mode (Pin => This.Pin,
Output => (Mode = HAL.GPIO.Output));
end Set_Mode;
-------------------
-- Pull_Resistor --
-------------------
overriding
function Pull_Resistor (This : MCP23_GPIO_Point)
return HAL.GPIO.GPIO_Pull_Resistor
is
begin
return (if This.Device.Pull_Up (This.Pin) then
HAL.GPIO.Pull_Up
else
HAL.GPIO.Floating);
end Pull_Resistor;
-----------------------
-- Set_Pull_Resistor --
-----------------------
overriding
procedure Set_Pull_Resistor (This : in out MCP23_GPIO_Point;
Pull : HAL.GPIO.GPIO_Pull_Resistor)
is
begin
This.Device.Configure_Pull (This.Pin, Pull = HAL.GPIO.Pull_Up);
end Set_Pull_Resistor;
---------
-- Set --
---------
overriding
function Set (This : MCP23_GPIO_Point) return Boolean is
begin
return This.Device.Set (This.Pin);
end Set;
---------
-- Set --
---------
overriding
procedure Set (This : in out MCP23_GPIO_Point) is
begin
This.Device.Set (This.Pin);
end Set;
-----------
-- Clear --
-----------
overriding
procedure Clear (This : in out MCP23_GPIO_Point) is
begin
This.Device.Clear (This.Pin);
end Clear;
------------
-- Toggle --
------------
overriding
procedure Toggle (This : in out MCP23_GPIO_Point) is
begin
This.Device.Toggle (This.Pin);
end Toggle;
end MCP23x08;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2018, 2022, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with HAL.GPIO; use HAL.GPIO;
package body MCP23x08 is
function To_UInt8 is
new Ada.Unchecked_Conversion (Source => ALl_IO_Array,
Target => UInt8);
function To_All_IO_Array is
new Ada.Unchecked_Conversion (Source => UInt8,
Target => ALl_IO_Array);
procedure Loc_IO_Write
(This : in out MCP23x08_IO_Expander'Class;
WriteAddr : Register_Address;
Value : UInt8)
with Inline_Always;
procedure Loc_IO_Read
(This : MCP23x08_IO_Expander'Class;
ReadAddr : Register_Address;
Value : out UInt8)
with Inline_Always;
procedure Set_Bit
(This : in out MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin);
procedure Clear_Bit
(This : in out MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin);
function Read_Bit
(This : MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin)
return Boolean;
------------------
-- Loc_IO_Write --
------------------
procedure Loc_IO_Write
(This : in out MCP23x08_IO_Expander'Class;
WriteAddr : Register_Address;
Value : UInt8)
is
begin
IO_Write (This, WriteAddr, Value);
end Loc_IO_Write;
-----------------
-- Loc_IO_Read --
-----------------
procedure Loc_IO_Read
(This : MCP23x08_IO_Expander'Class;
ReadAddr : Register_Address;
Value : out UInt8)
is
begin
IO_Read (This, ReadAddr, Value);
end Loc_IO_Read;
-------------
-- Set_Bit --
-------------
procedure Set_Bit
(This : in out MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin)
is
Prev, Next : UInt8;
begin
Loc_IO_Read (This, RegAddr, Prev);
Next := Prev or Pin'Enum_Rep;
if Next /= Prev then
Loc_IO_Write (This, RegAddr, Next);
end if;
end Set_Bit;
---------------
-- Clear_Bit --
---------------
procedure Clear_Bit
(This : in out MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin)
is
Prev, Next : UInt8;
begin
Loc_IO_Read (This, RegAddr, Prev);
Next := Prev and (not Pin'Enum_Rep);
if Next /= Prev then
Loc_IO_Write (This, RegAddr, Next);
end if;
end Clear_Bit;
--------------
-- Read_Bit --
--------------
function Read_Bit
(This : MCP23x08_IO_Expander;
RegAddr : Register_Address;
Pin : MCP23x08_Pin)
return Boolean
is
Reg : UInt8;
begin
Loc_IO_Read (This, RegAddr, Reg);
return (Reg and Pin'Enum_Rep) /= 0;
end Read_Bit;
---------------
-- Configure --
---------------
procedure Configure (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin;
Output : Boolean;
Pull_Up : Boolean)
is
begin
This.Configure_Mode (Pin, Output);
This.Configure_Pull (Pin, Pull_Up);
end Configure;
procedure Configure_Mode (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin;
Output : Boolean)
is
begin
if Output then
Clear_Bit (This, IO_DIRECTION_REG, Pin);
else
Set_Bit (This, IO_DIRECTION_REG, Pin);
end if;
end Configure_Mode;
---------------
-- Is_Output --
---------------
function Is_Output (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
return Boolean
is
begin
return not Read_Bit (This, IO_DIRECTION_REG, Pin);
end Is_Output;
--------------------
-- Configure_Pull --
--------------------
procedure Configure_Pull (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin;
Pull_Up : Boolean)
is
begin
if Pull_Up then
Set_Bit (This, PULL_UP_REG, Pin);
else
Clear_Bit (This, PULL_UP_REG, Pin);
end if;
end Configure_Pull;
-------------
-- Pull_Up --
-------------
function Pull_Up (This : MCP23x08_IO_Expander;
Pin : MCP23x08_Pin) return Boolean
is
begin
return Read_Bit (This, PULL_UP_REG, Pin);
end Pull_Up;
---------
-- Set --
---------
function Set (This : MCP23x08_IO_Expander;
Pin : MCP23x08_Pin) return Boolean
is
Val : UInt8;
begin
Loc_IO_Read (This, LOGIC_LEVLEL_REG, Val);
return (Pin'Enum_Rep and Val) /= 0;
end Set;
---------
-- Set --
---------
procedure Set (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
is
begin
Set_Bit (This, LOGIC_LEVLEL_REG, Pin);
end Set;
-----------
-- Clear --
-----------
procedure Clear (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
is
begin
Clear_Bit (This, LOGIC_LEVLEL_REG, Pin);
end Clear;
------------
-- Toggle --
------------
procedure Toggle (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
is
begin
if This.Set (Pin) then
This.Clear (Pin);
else
This.Set (Pin);
end if;
end Toggle;
------------
-- All_IO --
------------
function All_IO (This : in out MCP23x08_IO_Expander) return ALl_IO_Array is
Val : UInt8;
begin
Loc_IO_Read (This, LOGIC_LEVLEL_REG, Val);
return To_All_IO_Array (Val);
end All_IO;
----------------
-- Set_All_IO --
----------------
procedure Set_All_IO (This : in out MCP23x08_IO_Expander; IOs : ALl_IO_Array) is
begin
Loc_IO_Write (This, LOGIC_LEVLEL_REG, To_UInt8 (IOs));
end Set_All_IO;
-------------------
-- As_GPIO_Point --
-------------------
function As_GPIO_Point (This : in out MCP23x08_IO_Expander;
Pin : MCP23x08_Pin)
return not null HAL.GPIO.Any_GPIO_Point
is
begin
This.Points (Pin) := (Device => This'Unchecked_Access,
Pin => Pin);
return This.Points (Pin)'Unchecked_Access;
end As_GPIO_Point;
----------
-- Mode --
----------
overriding
function Mode (This : MCP23_GPIO_Point) return HAL.GPIO.GPIO_Mode is
begin
if This.Device.Is_Output (This.Pin) then
return HAL.GPIO.Output;
else
return HAL.GPIO.Input;
end if;
end Mode;
--------------
-- Set_Mode --
--------------
overriding
procedure Set_Mode (This : in out MCP23_GPIO_Point;
Mode : HAL.GPIO.GPIO_Config_Mode)
is
begin
This.Device.Configure_Mode (Pin => This.Pin,
Output => (Mode = HAL.GPIO.Output));
end Set_Mode;
-------------------
-- Pull_Resistor --
-------------------
overriding
function Pull_Resistor (This : MCP23_GPIO_Point)
return HAL.GPIO.GPIO_Pull_Resistor
is
begin
return (if This.Device.Pull_Up (This.Pin) then
HAL.GPIO.Pull_Up
else
HAL.GPIO.Floating);
end Pull_Resistor;
-----------------------
-- Set_Pull_Resistor --
-----------------------
overriding
procedure Set_Pull_Resistor (This : in out MCP23_GPIO_Point;
Pull : HAL.GPIO.GPIO_Pull_Resistor)
is
begin
This.Device.Configure_Pull (This.Pin, Pull = HAL.GPIO.Pull_Up);
end Set_Pull_Resistor;
---------
-- Set --
---------
overriding
function Set (This : MCP23_GPIO_Point) return Boolean is
begin
return This.Device.Set (This.Pin);
end Set;
---------
-- Set --
---------
overriding
procedure Set (This : in out MCP23_GPIO_Point) is
begin
This.Device.Set (This.Pin);
end Set;
-----------
-- Clear --
-----------
overriding
procedure Clear (This : in out MCP23_GPIO_Point) is
begin
This.Device.Clear (This.Pin);
end Clear;
------------
-- Toggle --
------------
overriding
procedure Toggle (This : in out MCP23_GPIO_Point) is
begin
This.Device.Toggle (This.Pin);
end Toggle;
end MCP23x08;
|
implement function Mode to fix issue #412 (#413)
|
implement function Mode to fix issue #412 (#413)
|
Ada
|
bsd-3-clause
|
simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
b4ca80f307193dfd4432bfce52784a2b9c622df5
|
src/natools-web-pages.adb
|
src/natools-web-pages.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.Static_Maps.Web.Pages;
with Natools.Web.Error_Pages;
with Natools.Web.Exchanges;
package body Natools.Web.Pages is
procedure Append
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Data : in S_Expressions.Atom);
procedure Execute
(Data : in out Page_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Sub_Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Expression : in out S_Expressions.Lockable.Descriptor'Class;
Lookup_Element : in Boolean := False;
Lookup_Template : in Boolean := False);
procedure Sub_Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Fallback : in out S_Expressions.Lockable.Descriptor'Class;
Lookup_Element : in Boolean;
Lookup_Template : in Boolean)
with Pre => Lookup_Element or Lookup_Template;
---------------------------
-- Page Data Constructor --
---------------------------
procedure Execute
(Data : in out Page_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
package Components renames Natools.Static_Maps.Web.Pages;
begin
case Components.To_Component (S_Expressions.To_String (Name)) is
when Components.Error =>
Log (Severities.Error, "Unknown page component """
& S_Expressions.To_String (Name) & '"');
when Components.Elements =>
Containers.Set_Expressions (Data.Elements, Arguments);
when Components.Tags =>
Tags.Append (Data.Tags, Arguments);
end case;
end Execute;
procedure Read_Page is new S_Expressions.Interpreter_Loop
(Page_Data, Meaningless_Type, Execute);
-------------------
-- Page Renderer --
-------------------
procedure Append
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Data : in S_Expressions.Atom)
is
pragma Unreferenced (Page);
begin
Exchange.Append (Data);
end Append;
procedure Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
use type S_Expressions.Events.Event;
package Commands renames Natools.Static_Maps.Web.Pages;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Unknown_Command =>
null;
when Commands.Element =>
Sub_Render (Exchange, Page, Arguments, Lookup_Element => True);
when Commands.Element_Or_Template =>
Sub_Render
(Exchange, Page, Arguments,
Lookup_Element => True,
Lookup_Template => True);
when Commands.My_Tags =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
declare
Prefix : constant S_Expressions.Atom
:= Arguments.Current_Atom;
begin
Arguments.Next;
Tags.Render
(Exchange,
Page.Tags,
Exchange.Site.Get_Tags,
Prefix,
Arguments);
end;
end if;
when Commands.Tags =>
Tags.Render
(Exchange,
Exchange.Site.Get_Tags,
Arguments,
Page.Tags);
when Commands.Template =>
Sub_Render (Exchange, Page, Arguments, Lookup_Template => True);
end case;
end Render;
procedure Render_Page is new S_Expressions.Interpreter_Loop
(Sites.Exchange, Page_Data, Render, Append);
procedure Sub_Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Expression : in out S_Expressions.Lockable.Descriptor'Class;
Lookup_Element : in Boolean := False;
Lookup_Template : in Boolean := False)
is
use type S_Expressions.Events.Event;
begin
if (Lookup_Element or Lookup_Template)
and then Expression.Current_Event = S_Expressions.Events.Add_Atom
then
declare
Name : constant S_Expressions.Atom := Expression.Current_Atom;
begin
Expression.Next;
Sub_Render
(Exchange, Page,
Name, Expression,
Lookup_Element, Lookup_Template);
end;
else
Render_Page (Expression, Exchange, Page);
end if;
end Sub_Render;
procedure Sub_Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Fallback : in out S_Expressions.Lockable.Descriptor'Class;
Lookup_Element : in Boolean;
Lookup_Template : in Boolean)
is
Template : S_Expressions.Caches.Cursor;
Found : Boolean;
begin
if Lookup_Element then
Page.Get_Element (Name, Template, Found);
if Found then
Render_Page (Template, Exchange, Page);
return;
end if;
end if;
if Lookup_Template then
Exchange.Site.Get_Template (Name, Template, Found);
if Found then
Render_Page (Template, Exchange, Page);
return;
end if;
end if;
case Fallback.Current_Event is
when S_Expressions.Events.Close_List
| S_Expressions.Events.End_Of_Input
| S_Expressions.Events.Error
=>
Log (Severities.Error,
"Page expression """
& S_Expressions.To_String (Name)
& """ not found");
return;
when S_Expressions.Events.Open_List
| S_Expressions.Events.Add_Atom
=>
Render_Page (Fallback, Exchange, Page);
end case;
end Sub_Render;
-------------------------
-- Page_Data Interface --
-------------------------
procedure Get_Element
(Data : in Page_Data;
Name : in S_Expressions.Atom;
Element : out S_Expressions.Caches.Cursor;
Found : out Boolean)
is
Cursor : constant Containers.Expression_Maps.Cursor
:= Data.Elements.Find (Name);
begin
Found := Containers.Expression_Maps.Has_Element (Cursor);
if Found then
Element := Containers.Expression_Maps.Element (Cursor);
end if;
end Get_Element;
----------------------
-- Public Interface --
----------------------
function Create
(File_Path, Web_Path : in S_Expressions.Atom)
return Page_Ref
is
function Create_Page return Page_Data;
function Create_Page return Page_Data is
Reader : Natools.S_Expressions.File_Readers.S_Reader
:= Natools.S_Expressions.File_Readers.Reader
(S_Expressions.To_String (File_Path));
begin
return Result : Page_Data
:= (File_Path =>
S_Expressions.Atom_Ref_Constructors.Create (File_Path),
Web_Path =>
S_Expressions.Atom_Ref_Constructors.Create (Web_Path),
Tags => <>,
Elements => <>)
do
Read_Page (Reader, Result, Meaningless_Value);
end return;
end Create_Page;
begin
return (Ref => Data_Refs.Create (Create_Page'Access));
end Create;
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in Page_Ref;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render_Page
(Expression,
Exchange,
Object.Ref.Query.Data.all);
end Render;
overriding procedure Respond
(Object : in out Page_Ref;
Exchange : in out Sites.Exchange;
Extra_Path : in S_Expressions.Atom) is
begin
if Extra_Path'Length > 0 then
return;
end if;
declare
Accessor : constant Data_Refs.Accessor := Object.Ref.Query;
Null_Expression : S_Expressions.Caches.Cursor;
begin
Check_Method :
declare
use Exchanges;
Allowed : Boolean;
begin
Error_Pages.Check_Method
(Exchange,
Exchange.Site,
(GET, HEAD),
Allowed);
if not Allowed then
return;
end if;
end Check_Method;
Sub_Render
(Exchange,
Accessor.Data.all,
Exchange.Site.Default_Template,
Null_Expression,
Lookup_Element => True,
Lookup_Template => True);
end;
end Respond;
end Natools.Web.Pages;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.Static_Maps.Web.Pages;
with Natools.Web.Error_Pages;
with Natools.Web.Exchanges;
package body Natools.Web.Pages is
procedure Append
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Data : in S_Expressions.Atom);
procedure Execute
(Data : in out Page_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Read_Page is new S_Expressions.Interpreter_Loop
(Page_Data, Meaningless_Type, Execute);
procedure Render_Page is new S_Expressions.Interpreter_Loop
(Sites.Exchange, Page_Data, Render, Append);
---------------------------
-- Page Data Constructor --
---------------------------
procedure Execute
(Data : in out Page_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
package Components renames Natools.Static_Maps.Web.Pages;
begin
case Components.To_Component (S_Expressions.To_String (Name)) is
when Components.Error =>
Log (Severities.Error, "Unknown page component """
& S_Expressions.To_String (Name) & '"');
when Components.Elements =>
Containers.Set_Expressions (Data.Elements, Arguments);
when Components.Tags =>
Tags.Append (Data.Tags, Arguments);
end case;
end Execute;
-------------------
-- Page Renderer --
-------------------
procedure Append
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Data : in S_Expressions.Atom)
is
pragma Unreferenced (Page);
begin
Exchange.Append (Data);
end Append;
procedure Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
use type S_Expressions.Events.Event;
package Commands renames Natools.Static_Maps.Web.Pages;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Unknown_Command =>
null;
when Commands.Element =>
declare
Template : S_Expressions.Caches.Cursor
:= Exchange.Site.Get_Template
(Page.Elements,
Arguments,
Lookup_Template => False);
begin
Render_Page (Template, Exchange, Page);
end;
when Commands.Element_Or_Template =>
declare
Template : S_Expressions.Caches.Cursor
:= Exchange.Site.Get_Template (Page.Elements, Arguments);
begin
Render_Page (Template, Exchange, Page);
end;
when Commands.My_Tags =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
declare
Prefix : constant S_Expressions.Atom
:= Arguments.Current_Atom;
begin
Arguments.Next;
Tags.Render
(Exchange,
Page.Tags,
Exchange.Site.Get_Tags,
Prefix,
Arguments);
end;
end if;
when Commands.Tags =>
Tags.Render
(Exchange,
Exchange.Site.Get_Tags,
Arguments,
Page.Tags);
when Commands.Template =>
declare
Template : S_Expressions.Caches.Cursor
:= Exchange.Site.Get_Template
(Page.Elements,
Arguments,
Lookup_Element => False);
begin
Render_Page (Template, Exchange, Page);
end;
end case;
end Render;
-------------------------
-- Page_Data Interface --
-------------------------
procedure Get_Element
(Data : in Page_Data;
Name : in S_Expressions.Atom;
Element : out S_Expressions.Caches.Cursor;
Found : out Boolean)
is
Cursor : constant Containers.Expression_Maps.Cursor
:= Data.Elements.Find (Name);
begin
Found := Containers.Expression_Maps.Has_Element (Cursor);
if Found then
Element := Containers.Expression_Maps.Element (Cursor);
end if;
end Get_Element;
----------------------
-- Public Interface --
----------------------
function Create
(File_Path, Web_Path : in S_Expressions.Atom)
return Page_Ref
is
function Create_Page return Page_Data;
function Create_Page return Page_Data is
Reader : Natools.S_Expressions.File_Readers.S_Reader
:= Natools.S_Expressions.File_Readers.Reader
(S_Expressions.To_String (File_Path));
begin
return Result : Page_Data
:= (File_Path =>
S_Expressions.Atom_Ref_Constructors.Create (File_Path),
Web_Path =>
S_Expressions.Atom_Ref_Constructors.Create (Web_Path),
Tags => <>,
Elements => <>)
do
Read_Page (Reader, Result, Meaningless_Value);
end return;
end Create_Page;
begin
return (Ref => Data_Refs.Create (Create_Page'Access));
end Create;
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in Page_Ref;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render_Page
(Expression,
Exchange,
Object.Ref.Query.Data.all);
end Render;
overriding procedure Respond
(Object : in out Page_Ref;
Exchange : in out Sites.Exchange;
Extra_Path : in S_Expressions.Atom) is
begin
if Extra_Path'Length > 0 then
return;
end if;
declare
Accessor : constant Data_Refs.Accessor := Object.Ref.Query;
Expression : S_Expressions.Caches.Cursor;
begin
Check_Method :
declare
use Exchanges;
Allowed : Boolean;
begin
Error_Pages.Check_Method
(Exchange,
Exchange.Site,
(GET, HEAD),
Allowed);
if not Allowed then
return;
end if;
end Check_Method;
Expression := Exchange.Site.Get_Template
(Accessor.Data.Elements,
Expression,
Exchange.Site.Default_Template,
Lookup_Element => True,
Lookup_Template => True,
Lookup_Name => True);
Render_Page (Expression, Exchange, Accessor.Data.all);
end;
end Respond;
end Natools.Web.Pages;
|
replace Sub_Render by calls using the new Sites.Get_Template high-level accessor
|
pages: replace Sub_Render by calls using the new Sites.Get_Template high-level accessor
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
ec98ac7472e2b65689832b8684d6822186550b35
|
src/security-contexts.ads
|
src/security-contexts.ads
|
-----------------------------------------------------------------------
-- security-contexts -- Context to provide security information and verify permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Strings.Maps;
with Security.Permissions;
-- == Security Context ==
-- The security context provides contextual information for a security controller to
-- verify that a permission is granted.
-- This security context is used as follows:
--
-- * An instance of the security context is declared within a function/procedure as
-- a local variable
--
-- * This instance will be associated with the current thread through a task attribute
--
-- * The security context is populated with information to identify the current user,
-- his roles, permissions and other information that could be used by security controllers
--
-- * To verify a permission, the current security context is retrieved and the
-- <b>Has_Permission</b> operation is called,
--
-- * The <b>Has_Permission</b> will first look in a small cache stored in the security context.
--
-- * When not present in the cache, it will use the security manager to find the
-- security controller associated with the permission to verify
--
-- * The security controller will be called with the security context to check the permission.
-- The whole job of checking the permission is done by the security controller.
-- The security controller retrieves information from the security context to decide
-- whether the permission is granted or not.
--
-- * The result produced by the security controller is then saved in the local cache.
--
package Security.Contexts is
Invalid_Context : exception;
type Security_Context is new Ada.Finalization.Limited_Controlled with private;
type Security_Context_Access is access all Security_Context'Class;
-- Get the application associated with the current service operation.
function Get_User_Principal (Context : in Security_Context'Class)
return Security.Principal_Access;
pragma Inline_Always (Get_User_Principal);
-- Get the permission manager.
function Get_Permission_Manager (Context : in Security_Context'Class)
return Security.Permissions.Permission_Manager_Access;
pragma Inline_Always (Get_Permission_Manager);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
procedure Has_Permission (Context : in out Security_Context;
Permission : in Security.Permissions.Permission_Index;
Result : out Boolean);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
procedure Has_Permission (Context : in out Security_Context;
Permission : in String;
Result : out Boolean);
-- Initializes the service context. By creating the <b>Security_Context</b> variable,
-- the instance will be associated with the current task attribute. If the current task
-- already has a security context, the new security context is installed, the old one
-- being kept.
overriding
procedure Initialize (Context : in out Security_Context);
-- Finalize the security context releases any object. The previous security context is
-- restored to the current task attribute.
overriding
procedure Finalize (Context : in out Security_Context);
-- Set the current application and user context.
procedure Set_Context (Context : in out Security_Context;
Manager : in Security.Permissions.Permission_Manager_Access;
Principal : in Security.Principal_Access);
-- Add a context information represented by <b>Value</b> under the name identified by
-- <b>Name</b> in the security context <b>Context</b>.
procedure Add_Context (Context : in out Security_Context;
Name : in String;
Value : in String);
-- Get the context information registered under the name <b>Name</b> in the security
-- context <b>Context</b>.
-- Raises <b>Invalid_Context</b> if there is no such information.
function Get_Context (Context : in Security_Context;
Name : in String) return String;
-- Returns True if a context information was registered under the name <b>Name</b>.
function Has_Context (Context : in Security_Context;
Name : in String) return Boolean;
-- Get the current security context.
-- Returns null if the current thread is not associated with any security context.
function Current return Security_Context_Access;
pragma Inline_Always (Current);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean;
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
function Has_Permission (Permission : in String) return Boolean;
private
type Permission_Cache is record
Perm : Security.Permissions.Permission_Type;
Result : Boolean;
end record;
type Security_Context is new Ada.Finalization.Limited_Controlled with record
Previous : Security_Context_Access := null;
Manager : Security.Permissions.Permission_Manager_Access := null;
Principal : Security.Principal_Access := null;
Context : Util.Strings.Maps.Map;
end record;
end Security.Contexts;
|
-----------------------------------------------------------------------
-- security-contexts -- Context to provide security information and verify permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Strings.Maps;
with Security.Permissions;
with Security.Policies;
-- == Security Context ==
-- The security context provides contextual information for a security controller to
-- verify that a permission is granted.
-- This security context is used as follows:
--
-- * An instance of the security context is declared within a function/procedure as
-- a local variable
--
-- * This instance will be associated with the current thread through a task attribute
--
-- * The security context is populated with information to identify the current user,
-- his roles, permissions and other information that could be used by security controllers
--
-- * To verify a permission, the current security context is retrieved and the
-- <b>Has_Permission</b> operation is called,
--
-- * The <b>Has_Permission</b> will first look in a small cache stored in the security context.
--
-- * When not present in the cache, it will use the security manager to find the
-- security controller associated with the permission to verify
--
-- * The security controller will be called with the security context to check the permission.
-- The whole job of checking the permission is done by the security controller.
-- The security controller retrieves information from the security context to decide
-- whether the permission is granted or not.
--
-- * The result produced by the security controller is then saved in the local cache.
--
package Security.Contexts is
Invalid_Context : exception;
type Security_Context is new Ada.Finalization.Limited_Controlled with private;
type Security_Context_Access is access all Security_Context'Class;
-- Get the application associated with the current service operation.
function Get_User_Principal (Context : in Security_Context'Class)
return Security.Principal_Access;
pragma Inline_Always (Get_User_Principal);
-- Get the permission manager.
function Get_Permission_Manager (Context : in Security_Context'Class)
return Security.Policies.Policy_Manager_Access;
pragma Inline_Always (Get_Permission_Manager);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
procedure Has_Permission (Context : in out Security_Context;
Permission : in Security.Permissions.Permission_Index;
Result : out Boolean);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
procedure Has_Permission (Context : in out Security_Context;
Permission : in String;
Result : out Boolean);
-- Initializes the service context. By creating the <b>Security_Context</b> variable,
-- the instance will be associated with the current task attribute. If the current task
-- already has a security context, the new security context is installed, the old one
-- being kept.
overriding
procedure Initialize (Context : in out Security_Context);
-- Finalize the security context releases any object. The previous security context is
-- restored to the current task attribute.
overriding
procedure Finalize (Context : in out Security_Context);
-- Set the current application and user context.
procedure Set_Context (Context : in out Security_Context;
Manager : in Security.Policies.Policy_Manager_Access;
Principal : in Security.Principal_Access);
-- Add a context information represented by <b>Value</b> under the name identified by
-- <b>Name</b> in the security context <b>Context</b>.
procedure Add_Context (Context : in out Security_Context;
Name : in String;
Value : in String);
-- Get the context information registered under the name <b>Name</b> in the security
-- context <b>Context</b>.
-- Raises <b>Invalid_Context</b> if there is no such information.
function Get_Context (Context : in Security_Context;
Name : in String) return String;
-- Returns True if a context information was registered under the name <b>Name</b>.
function Has_Context (Context : in Security_Context;
Name : in String) return Boolean;
-- Get the current security context.
-- Returns null if the current thread is not associated with any security context.
function Current return Security_Context_Access;
pragma Inline_Always (Current);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean;
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
function Has_Permission (Permission : in String) return Boolean;
private
type Permission_Cache is record
Perm : Security.Permissions.Permission_Type;
Result : Boolean;
end record;
type Security_Context is new Ada.Finalization.Limited_Controlled with record
Previous : Security_Context_Access := null;
Manager : Security.Policies.Policy_Manager_Access := null;
Principal : Security.Principal_Access := null;
Context : Util.Strings.Maps.Map;
end record;
end Security.Contexts;
|
Use the Policy manager
|
Use the Policy manager
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
fe13ecfe48b1d7a5881ebb409129d6632bb35724
|
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;
with Security.Contexts;
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;
-- ------------------------------
-- Checks whether the permission defined by the <b>Permission</b> is granted
-- for the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
-- ------------------------------
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
use type Permissions.Permission_Index;
begin
if Permission.Id >= Manager.Last_Index then
return False;
end if;
declare
C : constant Controller_Access := Manager.Permissions (Permission.Id);
begin
if C = null then
return False;
else
return C.Has_Permission (Context, Permission);
end if;
end;
end Has_Permission;
-- ------------------------------
-- 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;
|
-----------------------------------------------------------------------
-- 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;
with Security.Contexts;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- ------------------------------
-- 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;
-- ------------------------------
-- Checks whether the permission defined by the <b>Permission</b> is granted
-- for the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
-- ------------------------------
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
use type Permissions.Permission_Index;
begin
if Permission.Id >= Manager.Last_Index then
return False;
end if;
declare
C : constant Controller_Access := Manager.Permissions (Permission.Id);
begin
if C = null then
return False;
else
return C.Has_Permission (Context, Permission);
end if;
end;
end Has_Permission;
-- ------------------------------
-- 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;
|
Remove Get_Name
|
Remove Get_Name
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
3a5eb19c62312f18422ef0555e3ffa646f6cfc25
|
src/asf-components.ads
|
src/asf-components.ads
|
-----------------------------------------------------------------------
-- components -- Component tree
-- 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 <bASF.Components</b> describes the components that form the
-- tree view. Each component has attributes and children. Children
-- represent sub-components and attributes control the rendering and
-- behavior of the component.
--
-- The component tree is created from the <b>ASF.Views</b> tag nodes
-- for each request. Unlike tag nodes, the component tree is not shared.
with Ada.Strings.Unbounded;
with EL.Objects;
with EL.Expressions;
limited with ASF.Views.Nodes;
package ASF.Components is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Attribute of a component
-- ------------------------------
type UIAttribute is private;
private
type UIAttribute_Access is access all UIAttribute;
type UIAttribute is record
Definition : access ASF.Views.Nodes.Tag_Attribute;
Name : Unbounded_String;
Value : EL.Objects.Object;
Expr : EL.Expressions.Expression;
Next_Attr : UIAttribute_Access;
end record;
end ASF.Components;
|
-----------------------------------------------------------------------
-- components -- Component tree
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <bASF.Components</b> describes the components that form the
-- tree view. Each component has attributes and children. Children
-- represent sub-components and attributes control the rendering and
-- behavior of the component.
--
-- The component tree is created from the <b>ASF.Views</b> tag nodes
-- for each request. Unlike tag nodes, the component tree is not shared.
with Ada.Strings.Unbounded;
with EL.Objects;
with EL.Expressions;
limited with ASF.Views.Nodes;
package ASF.Components is
use Ada.Strings.Unbounded;
-- Flag indicating whether or not this component should be rendered
-- (during Render Response Phase), or processed on any subsequent form submit.
-- The default value for this property is true.
RENDERED_NAME : constant String := "rendered";
-- A localized user presentable name for the component.
LABEL_NAME : constant String := "label";
-- Converter instance registered with the component.
CONVERTER_NAME : constant String := "converter";
-- A ValueExpression enabled attribute that, if present, will be used as the text
-- of the converter message, replacing any message that comes from the converter.
CONVERTER_MESSAGE_NAME : constant String := "converterMessage";
-- A ValueExpression enabled attribute that, if present, will be used as the text
-- of the validator message, replacing any message that comes from the validator.
VALIDATOR_MESSAGE_NAME : constant String := "validatorMessage";
-- Flag indicating that the user is required to provide a submitted value for
-- the input component.
REQUIRED_NAME : constant String := "required";
-- A ValueExpression enabled attribute that, if present, will be used as the
-- text of the validation message for the "required" facility, if the "required"
-- facility is used.
REQUIRED_MESSAGE_NAME : constant String := "requiredMessage";
-- ------------------------------
-- Attribute of a component
-- ------------------------------
type UIAttribute is private;
private
type UIAttribute_Access is access all UIAttribute;
type UIAttribute is record
Definition : access ASF.Views.Nodes.Tag_Attribute;
Name : Unbounded_String;
Value : EL.Objects.Object;
Expr : EL.Expressions.Expression;
Next_Attr : UIAttribute_Access;
end record;
end ASF.Components;
|
Define the name of commonly used attributes
|
Define the name of commonly used attributes
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
f11991460d0b65198c3d12308c06ef79f167a996
|
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.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;
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;
procedure Get_User is
new Mapping.Rest_Get (Mapping.Person, Mapping.Person_Access,
Mapping.Person_Mapper.Set_Context);
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.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;
|
Use the generic Rest_Get operation
|
Use the generic Rest_Get operation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
06806fb2d61173a453bd8ce1806d0bb4dfbabdcb
|
regtests/dlls/util-systems-dlls-tests.adb
|
regtests/dlls/util-systems-dlls-tests.adb
|
-----------------------------------------------------------------------
-- util-systems-dlls-tests -- Unit tests for shared libraries
-- Copyright (C) 2013, 2017, 2019, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Systems.DLLs.Tests is
use Util.Tests;
use type System.Address;
procedure Load_Library (T : in out Test;
Lib : out Handle);
package Caller is new Util.Test_Caller (Test, "Systems.Dlls");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load",
Test_Load'Access);
Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol",
Test_Get_Symbol'Access);
end Add_Tests;
procedure Load_Library (T : in out Test;
Lib : out Handle) is
Lib1 : Handle;
Lib2 : Handle;
Lib3 : Handle;
Lib4 : Handle;
Lib5 : Handle;
Lib6 : Handle;
begin
begin
Lib1 := Util.Systems.DLLs.Load ("libcrypto.so");
T.Assert (Lib1 /= Null_Handle, "Load operation returned null");
Lib := Lib1;
exception
when Load_Error =>
Lib1 := Null_Handle;
end;
begin
Lib2 := Util.Systems.DLLs.Load ("libgmp.dylib");
T.Assert (Lib2 /= Null_Handle, "Load operation returned null");
Lib := Lib2;
exception
when Load_Error =>
Lib2 := Null_Handle;
end;
begin
Lib3 := Util.Systems.DLLs.Load ("zlib1.dll");
T.Assert (Lib3 /= Null_Handle, "Load operation returned null");
Lib := Lib3;
exception
when Load_Error =>
Lib3 := Null_Handle;
end;
begin
Lib4 := Util.Systems.DLLs.Load ("libz.so");
T.Assert (Lib4 /= Null_Handle, "Load operation returned null");
Lib := Lib4;
exception
when Load_Error =>
Lib4 := Null_Handle;
end;
begin
Lib5 := Util.Systems.DLLs.Load ("libgmp.so");
T.Assert (Lib5 /= Null_Handle, "Load operation returned null");
Lib := Lib5;
exception
when Load_Error =>
Lib5 := Null_Handle;
end;
begin
Lib6 := Util.Systems.DLLs.Load ("libexpat-1.dll");
T.Assert (Lib6 /= Null_Handle, "Load operation returned null");
Lib := Lib6;
exception
when Load_Error =>
Lib6 := Null_Handle;
end;
T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 /= Null_Handle
or Lib4 /= Null_Handle or Lib5 /= Null_Handle or Lib6 /= Null_Handle,
"At least one Load operation should have succeeded");
end Load_Library;
-- ------------------------------
-- Test the loading a shared library.
-- ------------------------------
procedure Test_Load (T : in out Test) is
Lib : Handle;
begin
Load_Library (T, Lib);
begin
Lib := Util.Systems.DLLs.Load ("some-invalid-library");
T.Fail ("Load must raise an exception");
exception
when Load_Error =>
null;
end;
end Test_Load;
-- ------------------------------
-- Test getting a shared library symbol.
-- ------------------------------
procedure Test_Get_Symbol (T : in out Test) is
Lib : Handle;
Sym : System.Address := System.Null_Address;
begin
Load_Library (T, Lib);
T.Assert (Lib /= Null_Handle, "Load operation returned null");
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "__gmpf_cmp");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
-- We must have found one of the two symbols
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol");
T.Fail ("The Get_Symbol operation must raise an exception");
exception
when Not_Found =>
null;
end;
end Test_Get_Symbol;
end Util.Systems.DLLs.Tests;
|
-----------------------------------------------------------------------
-- util-systems-dlls-tests -- Unit tests for shared libraries
-- Copyright (C) 2013, 2017, 2019, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Systems.DLLs.Tests is
use Util.Tests;
use type System.Address;
procedure Load_Library (T : in out Test;
Lib : out Handle);
package Caller is new Util.Test_Caller (Test, "Systems.Dlls");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load",
Test_Load'Access);
Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol",
Test_Get_Symbol'Access);
end Add_Tests;
procedure Load_Library (T : in out Test;
Lib : out Handle) is
Lib1 : Handle;
Lib2 : Handle;
Lib3 : Handle;
Lib4 : Handle;
Lib5 : Handle;
Lib6 : Handle;
begin
begin
Lib1 := Util.Systems.DLLs.Load ("libcrypto.so");
T.Assert (Lib1 /= Null_Handle, "Load operation returned null");
Lib := Lib1;
exception
when Load_Error =>
Lib1 := Null_Handle;
end;
begin
Lib2 := Util.Systems.DLLs.Load ("libgmp.dylib");
T.Assert (Lib2 /= Null_Handle, "Load operation returned null");
Lib := Lib2;
exception
when Load_Error =>
Lib2 := Null_Handle;
end;
begin
Lib3 := Util.Systems.DLLs.Load ("zlib1.dll");
T.Assert (Lib3 /= Null_Handle, "Load operation returned null");
Lib := Lib3;
exception
when Load_Error =>
Lib3 := Null_Handle;
end;
begin
Lib4 := Util.Systems.DLLs.Load ("libz.so");
T.Assert (Lib4 /= Null_Handle, "Load operation returned null");
Lib := Lib4;
exception
when Load_Error =>
Lib4 := Null_Handle;
end;
begin
Lib5 := Util.Systems.DLLs.Load ("libgmp.so");
T.Assert (Lib5 /= Null_Handle, "Load operation returned null");
Lib := Lib5;
exception
when Load_Error =>
Lib5 := Null_Handle;
end;
begin
Lib6 := Util.Systems.DLLs.Load ("libexpat-1.dll");
T.Assert (Lib6 /= Null_Handle, "Load operation returned null");
Lib := Lib6;
exception
when Load_Error =>
Lib6 := Null_Handle;
end;
T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 /= Null_Handle
or Lib4 /= Null_Handle or Lib5 /= Null_Handle or Lib6 /= Null_Handle,
"At least one Load operation should have succeeded");
end Load_Library;
-- ------------------------------
-- Test the loading a shared library.
-- ------------------------------
procedure Test_Load (T : in out Test) is
Lib : Handle;
begin
Load_Library (T, Lib);
begin
Lib := Util.Systems.DLLs.Load ("some-invalid-library");
T.Fail ("Load must raise an exception");
exception
when Load_Error =>
null;
end;
end Test_Load;
-- ------------------------------
-- Test getting a shared library symbol.
-- ------------------------------
procedure Test_Get_Symbol (T : in out Test) is
Lib : Handle;
Sym : System.Address := System.Null_Address;
begin
Load_Library (T, Lib);
T.Assert (Lib /= Null_Handle, "Load operation returned null");
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "__gmpf_cmp");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "XML_ParserCreate");
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
exception
when Not_Found =>
null;
end;
-- We must have found one of the two symbols
T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null");
begin
Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol");
T.Fail ("The Get_Symbol operation must raise an exception");
exception
when Not_Found =>
null;
end;
end Test_Get_Symbol;
end Util.Systems.DLLs.Tests;
|
Update the DLL unit test for Windows
|
Update the DLL unit test for Windows
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2d3188e29abc224fc361a0b1cd05d4eeeaeb834e
|
awa/regtests/security-auth-fake.adb
|
awa/regtests/security-auth-fake.adb
|
-----------------------------------------------------------------------
-- security-auth-fake -- A fake OAuth provider for unit tests
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Security.Auth.Fake is
-- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt>
-- and <tt>openid.callback_url</tt> parameters to configure the realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID) is
begin
null;
end Initialize;
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
null;
end Discover;
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
null;
end Associate;
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
begin
return "/fake-authorization-server";
end Get_Authentication_URL;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
Email : constant String := Request.Get_Parameter ("email");
Claimed_Id : constant String := Request.Get_Parameter ("claimed_id");
Identity : constant String := Request.Get_Parameter ("id");
begin
Result.Identity := To_Unbounded_String (Identity);
Result.Claimed_Id := To_Unbounded_String (Claimed_Id);
Result.Email := To_Unbounded_String (Email);
end Verify;
end Security.Auth.Fake;
|
-----------------------------------------------------------------------
-- security-auth-fake -- A fake OAuth provider for unit tests
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Security.Auth.Fake is
-- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt>
-- and <tt>openid.callback_url</tt> parameters to configure the realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID) is
begin
null;
end Initialize;
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
null;
end Discover;
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
null;
end Associate;
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
begin
return "/fake-authorization-server";
end Get_Authentication_URL;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
Email : constant String := Request.Get_Parameter ("email");
Claimed_Id : constant String := Request.Get_Parameter ("claimed_id");
Identity : constant String := Request.Get_Parameter ("id");
begin
if Email'Length = 0 or Identity'Length = 0 then
Result.Status := Security.Auth.CANCEL;
else
Result.Status := Security.Auth.AUTHENTICATED;
end if;
Result.Identity := To_Unbounded_String (Identity);
Result.Claimed_Id := To_Unbounded_String (Claimed_Id);
Result.Email := To_Unbounded_String (Email);
end Verify;
end Security.Auth.Fake;
|
Fix the Verify procedure to setup the result status
|
Fix the Verify procedure to setup the result status
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
c736b820187c845b227d25f89fef4549af630ddc
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sqlite3_H;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.C;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
No_Callback : constant Sqlite3_H.sqlite3_callback := null;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
-- ------------------------------
-- Check for an error after executing a sqlite statement.
-- ------------------------------
procedure Check_Error (Connection : in Sqlite_Access;
Result : in int) is
begin
if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Error {0}: {1}", int'Image (Result), Msg);
end;
end if;
end Check_Error;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
-- Database.Execute ("begin transaction;");
null;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
-- Database.Execute ("commit transaction;");
null;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
-- Database.Execute ("rollback transaction;");
null;
end Rollback;
procedure Sqlite3_Free (Arg1 : Strings.chars_ptr);
pragma Import (C, sqlite3_free, "sqlite3_free");
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
use type Strings.chars_ptr;
SQL_Stat : ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
Error_Msg : Strings.chars_ptr;
begin
Log.Debug ("Execute: {0}", SQL);
for Retry in 1 .. 100 loop
Result := Sqlite3_H.sqlite3_exec (Database.Server, ADO.C.To_C (SQL_Stat), No_Callback,
System.Null_Address, Error_Msg'Address);
exit when Result /= Sqlite3_H.SQLITE_BUSY;
delay 0.01 * Retry;
end loop;
Check_Error (Database.Server, Result);
if Error_Msg /= Strings.Null_Ptr then
Log.Error ("Error: {0}", Strings.Value (Error_Msg));
Sqlite3_Free (Error_Msg);
end if;
-- Free
-- Strings.Free (SQL_Stat);
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
pragma Unreferenced (Database);
Result : int;
begin
Log.Info ("Close connection");
-- if Database.Count = 1 then
-- Result := Sqlite3_H.sqlite3_close (Database.Server);
-- Database.Server := System.Null_Address;
-- end if;
pragma Unreferenced (Result);
end Close;
-- ------------------------------
-- Releases the sqlite connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
Result : int;
begin
Log.Debug ("Release connection");
Result := Sqlite3_H.sqlite3_close (Database.Server);
Database.Server := System.Null_Address;
pragma Unreferenced (Result);
end Finalize;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
DB : Ref.Ref;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
pragma Unreferenced (D);
use Strings;
use type System.Address;
Name : constant String := To_String (Config.Database);
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased System.Address;
Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Log.Info ("Opening database {0}", Name);
if not DB.Is_Null then
Result := Ref.Create (DB.Value);
return;
end if;
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
raise DB_Error;
end if;
declare
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name, Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name, Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & To_String (Name) & "=" & Escape (Item);
begin
Log.Info ("Configure database with {0}", SQL);
Database.Execute (SQL);
end Configure;
begin
Database.Server := Handle;
Database.Name := Config.Database;
DB := Ref.Create (Database.all'Access);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Properties.Iterate (Process => Configure'Access);
Result := Ref.Create (Database.all'Access);
end;
end Create_Connection;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
end ADO.Drivers.Connections.Sqlite;
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sqlite3_H;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.C;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
No_Callback : constant Sqlite3_H.sqlite3_callback := null;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
-- ------------------------------
-- Check for an error after executing a sqlite statement.
-- ------------------------------
procedure Check_Error (Connection : in Sqlite_Access;
Result : in int) is
begin
if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Error {0}: {1}", int'Image (Result), Msg);
end;
end if;
end Check_Error;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
-- Database.Execute ("begin transaction;");
null;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
-- Database.Execute ("commit transaction;");
null;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
-- Database.Execute ("rollback transaction;");
null;
end Rollback;
procedure Sqlite3_Free (Arg1 : Strings.chars_ptr);
pragma Import (C, sqlite3_free, "sqlite3_free");
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
use type Strings.chars_ptr;
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
Error_Msg : Strings.chars_ptr;
begin
Log.Debug ("Execute: {0}", SQL);
for Retry in 1 .. 100 loop
Result := Sqlite3_H.sqlite3_exec (Database.Server, ADO.C.To_C (SQL_Stat), No_Callback,
System.Null_Address, Error_Msg'Address);
exit when Result /= Sqlite3_H.SQLITE_BUSY;
delay 0.01 * Retry;
end loop;
Check_Error (Database.Server, Result);
if Error_Msg /= Strings.Null_Ptr then
Log.Error ("Error: {0}", Strings.Value (Error_Msg));
Sqlite3_Free (Error_Msg);
end if;
-- Free
-- Strings.Free (SQL_Stat);
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
pragma Unreferenced (Database);
Result : int;
begin
Log.Info ("Close connection");
-- if Database.Count = 1 then
-- Result := Sqlite3_H.sqlite3_close (Database.Server);
-- Database.Server := System.Null_Address;
-- end if;
pragma Unreferenced (Result);
end Close;
-- ------------------------------
-- Releases the sqlite connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
Result : int;
begin
Log.Debug ("Release connection");
Result := Sqlite3_H.sqlite3_close (Database.Server);
Database.Server := System.Null_Address;
pragma Unreferenced (Result);
end Finalize;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
DB : Ref.Ref;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
pragma Unreferenced (D);
use Strings;
use type System.Address;
Name : constant String := To_String (Config.Database);
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased System.Address;
Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Log.Info ("Opening database {0}", Name);
if not DB.Is_Null then
Result := Ref.Create (DB.Value);
return;
end if;
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
raise DB_Error;
end if;
declare
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name, Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name, Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & To_String (Name) & "=" & Escape (Item);
begin
Log.Info ("Configure database with {0}", SQL);
Database.Execute (SQL);
end Configure;
begin
Database.Server := Handle;
Database.Name := Config.Database;
DB := Ref.Create (Database.all'Access);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Properties.Iterate (Process => Configure'Access);
Result := Ref.Create (Database.all'Access);
end;
end Create_Connection;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
end ADO.Drivers.Connections.Sqlite;
|
Make the SQL_Stat local variable constant
|
Make the SQL_Stat local variable constant
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
f6afa46ee828ed8a5e37e953cdb2d53371f32957
|
src/sys/streams/util-streams-buffered.ads
|
src/sys/streams/util-streams-buffered.ads
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
-- == Buffered Streams ==
-- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output
-- and input stream respectively which manages an output or input buffer. The data is
-- first written to the buffer and when the buffer is full or flushed, it gets written
-- to the target output stream.
--
-- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well
-- as the target output stream onto which the data will be flushed. For example, a
-- pipe stream could be created and configured to use the buffer as follows:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Output_Buffer_Stream;
-- ...
-- Buffer.Initialize (Output => Pipe'Unchecked_Access,
-- Size => 1024);
--
-- In this example, the buffer of 1024 bytes is configured to flush its content to the
-- pipe input stream so that what is written to the buffer will be received as input by
-- the program.
-- The `Output_Buffer_Stream` provides write operation that deal only with binary data
-- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from
-- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides
-- several operations to write character and strings.
--
-- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size
-- and either an input stream or an input content. When configured, the input stream is used
-- to fill the input stream buffer. The buffer configuration is very similar as the
-- output stream:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024);
--
-- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus
-- getting the program's output.
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 Ada.Finalization.Limited_Controlled
and 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 : access Output_Stream'Class;
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);
-- Flush the buffer stream to the unbounded string.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String);
-- Flush the stream and release the buffer.
overriding
procedure Finalize (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 : access Input_Stream'Class;
Size : in Positive);
-- Initialize the stream from the buffer created for an output stream.
procedure Initialize (Stream : in out Input_Buffer_Stream;
From : in out Output_Buffer_Stream'Class);
-- 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 : access Output_Stream'Class;
No_Flush : Boolean := False;
end record;
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 : access Input_Stream'Class;
-- 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, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
-- == Buffered Streams ==
-- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output
-- and input stream respectively which manages an output or input buffer. The data is
-- first written to the buffer and when the buffer is full or flushed, it gets written
-- to the target output stream.
--
-- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well
-- as the target output stream onto which the data will be flushed. For example, a
-- pipe stream could be created and configured to use the buffer as follows:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Output_Buffer_Stream;
-- ...
-- Buffer.Initialize (Output => Pipe'Access,
-- Size => 1024);
--
-- In this example, the buffer of 1024 bytes is configured to flush its content to the
-- pipe input stream so that what is written to the buffer will be received as input by
-- the program.
-- The `Output_Buffer_Stream` provides write operation that deal only with binary data
-- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from
-- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides
-- several operations to write character and strings.
--
-- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size
-- and either an input stream or an input content. When configured, the input stream is used
-- to fill the input stream buffer. The buffer configuration is very similar as the
-- output stream:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Access, Size => 1024);
--
-- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus
-- getting the program's output.
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 Ada.Finalization.Limited_Controlled
and 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 : access Output_Stream'Class;
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);
-- Flush the buffer stream to the unbounded string.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String);
-- Flush the stream and release the buffer.
overriding
procedure Finalize (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 : access Input_Stream'Class;
Size : in Positive);
-- Initialize the stream from the buffer created for an output stream.
procedure Initialize (Stream : in out Input_Buffer_Stream;
From : in out Output_Buffer_Stream'Class);
-- 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 : access Output_Stream'Class;
No_Flush : Boolean := False;
end record;
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 : access Input_Stream'Class;
-- 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;
|
Fix the stream documentation
|
Fix the stream documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b86bba36bbab184190d46b66370fdc52782a1e2e
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
-- === Wiki Parsers ===
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt>
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- <tt>Set_Syntax</tt> procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki <tt>Document</tt> is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream
-- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure
-- completes, the <tt>Document</tt> instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wiki.Strings.WChar);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access constant Parser_Table;
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Previous_Syntax : Wiki_Syntax;
Table : Parser_Table_Access;
Document : Wiki.Documents.Document;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser'Class;
Token : out Wiki.Strings.WChar);
pragma Inline (Peek);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
-- Extract a list of parameters separated by the given separator (ex: '|').
procedure Parse_Parameters (P : in out Parser;
Separator : in Wiki.Strings.WChar;
Terminator : in Wiki.Strings.WChar;
Names : in String_Array;
Max : in Positive := 200);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Parse_Token (P : in out Parser);
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
-- === Wiki Parsers ===
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt>
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- <tt>Set_Syntax</tt> procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki <tt>Document</tt> is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream
-- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure
-- completes, the <tt>Document</tt> instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wiki.Strings.WChar);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access constant Parser_Table;
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Previous_Syntax : Wiki_Syntax;
Table : Parser_Table_Access;
Document : Wiki.Documents.Document;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser'Class;
Token : out Wiki.Strings.WChar);
pragma Inline (Peek);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
-- Extract a list of parameters separated by the given separator (ex: '|').
procedure Parse_Parameters (P : in out Parser;
Separator : in Wiki.Strings.WChar;
Terminator : in Wiki.Strings.WChar;
Names : in String_Array;
Max : in Positive := 200);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Parse_Token (P : in out Parser);
end Wiki.Parsers;
|
Declare the Is_Included function
|
Declare the Is_Included function
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
7846f05e9ca02e505c79228d6113f1c3f59401ec
|
regtests/security-permissions-tests.adb
|
regtests/security-permissions-tests.adb
|
-----------------------------------------------------------------------
-- Security-permissions-tests - Unit tests for Security.Permissions
-- 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.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
package body Security.Permissions.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Permissions");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission",
Test_Add_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index",
Test_Add_Permission'Access);
end Add_Tests;
-- ------------------------------
-- Test Add_Permission and Get_Permission_Index
-- ------------------------------
procedure Test_Add_Permission (T : in out Test) is
Index1, Index2 : Permission_Index;
begin
Add_Permission ("test-create-permission", Index1);
T.Assert (Index1 = Get_Permission_Index ("test-create-permission"),
"Get_Permission_Index failed");
Add_Permission ("test-create-permission", Index2);
T.Assert (Index2 = Index1,
"Add_Permission failed");
end Test_Add_Permission;
end Security.Permissions.Tests;
|
-----------------------------------------------------------------------
-- Security-permissions-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
package body Security.Permissions.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Permissions");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission",
Test_Add_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index",
Test_Add_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Definition",
Test_Define_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index (invalid name)",
Test_Get_Invalid_Permission'Access);
end Add_Tests;
-- ------------------------------
-- Test Add_Permission and Get_Permission_Index
-- ------------------------------
procedure Test_Add_Permission (T : in out Test) is
Index1, Index2 : Permission_Index;
begin
Add_Permission ("test-create-permission", Index1);
T.Assert (Index1 = Get_Permission_Index ("test-create-permission"),
"Get_Permission_Index failed");
Add_Permission ("test-create-permission", Index2);
T.Assert (Index2 = Index1,
"Add_Permission failed");
end Test_Add_Permission;
-- ------------------------------
-- Test the permission created by the Definition package.
-- ------------------------------
procedure Test_Define_Permission (T : in out Test) is
Index : Permission_Index;
begin
Index := Get_Permission_Index ("admin");
T.Assert (P_Admin.Permission = Index, "Invalid permission for admin");
Index := Get_Permission_Index ("create");
T.Assert (P_Create.Permission = Index, "Invalid permission for create");
Index := Get_Permission_Index ("update");
T.Assert (P_Update.Permission = Index, "Invalid permission for update");
Index := Get_Permission_Index ("delete");
T.Assert (P_Delete.Permission = Index, "Invalid permission for delete");
T.Assert (P_Admin.Permission /= P_Create.Permission, "Admin or create permission invalid");
T.Assert (P_Admin.Permission /= P_Update.Permission, "Admin or update permission invalid");
T.Assert (P_Admin.Permission /= P_Delete.Permission, "Admin or delete permission invalid");
T.Assert (P_Create.Permission /= P_Update.Permission, "Create or update permission invalid");
T.Assert (P_Create.Permission /= P_Delete.Permission, "Create or delete permission invalid");
T.Assert (P_Update.Permission /= P_Delete.Permission, "Create or delete permission invalid");
end Test_Define_Permission;
-- ------------------------------
-- Test Get_Permission on invalid permission name.
-- ------------------------------
procedure Test_Get_Invalid_Permission (T : in out Test) is
Index : Permission_Index;
begin
Index := Get_Permission_Index ("invalid");
T.Assert (Index = Index - 1,
"No exception raised by Get_Permission_Index for an invalid name");
exception
when Invalid_Name =>
null;
end Test_Get_Invalid_Permission;
end Security.Permissions.Tests;
|
Implement the new unit tests for Permissions.Definition package
|
Implement the new unit tests for Permissions.Definition package
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
3bf90a8224584fa18334eeed56a4bceb0e72fab4
|
testutil/ahven/ahven-tap_runner.adb
|
testutil/ahven/ahven-tap_runner.adb
|
--
-- Copyright (c) 2008-2009 Tero Koskinen <[email protected]>
--
-- 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.Text_IO;
with Ada.Strings.Fixed;
with Ada.Characters.Latin_1;
with Ahven.Parameters;
with Ahven.AStrings;
with Ahven.Long_AStrings;
package body Ahven.Tap_Runner is
use Ada.Text_IO;
use Ahven.Framework;
use Ahven.AStrings;
function Count_Image (Count : Test_Count_Type) return String is
use Ada.Strings;
begin
return Fixed.Trim (Test_Count_Type'Image (Count), Both);
end Count_Image;
procedure Print_Data (Message : String; Prefix : String) is
Start_Of_Line : Boolean := True;
begin
for I in Message'Range loop
if Start_Of_Line then
Put (Prefix);
Start_Of_Line := False;
end if;
if Message (I) = Ada.Characters.Latin_1.LF then
New_Line;
Start_Of_Line := True;
elsif Message (I) /= Ada.Characters.Latin_1.CR then
Put (Message (I));
end if;
end loop;
if not Start_Of_Line then
New_Line;
end if;
end Print_Data;
procedure Run (Suite : in out Framework.Test'Class) is
Listener : Tap_Listener;
Params : Parameters.Parameter_Info;
begin
Parameters.Parse_Parameters (Parameters.TAP_PARAMETERS, Params);
Listener.Verbose := Parameters.Verbose (Params);
Listener.Capture_Output := Parameters.Capture (Params);
if Parameters.Single_Test (Params) then
Put_Line ("1.." & Count_Image (Test_Count
(Suite, Parameters.Test_Name (Params))));
Framework.Execute
(T => Suite,
Test_Name => Parameters.Test_Name (Params),
Listener => Listener,
Timeout => Parameters.Timeout (Params));
else
Put_Line ("1.." & Count_Image (Test_Count (Suite)));
Framework.Execute (Suite, Listener, Parameters.Timeout (Params));
end if;
exception
when Parameters.Invalid_Parameter =>
Parameters.Usage (Parameters.TAP_PARAMETERS);
end Run;
procedure Print_Info (Info : Context) is
begin
if Length (Info.Message) > 0 then
Print_Data (Message => To_String (Info.Message), Prefix => "# ");
end if;
if Long_AStrings.Length (Info.Long_Message) > 0 then
Print_Data
(Message => Long_AStrings.To_String (Info.Long_Message),
Prefix => "# ");
end if;
end Print_Info;
procedure Print_Log_File (Filename : String; Prefix : String) is
Handle : File_Type;
Char : Character := ' ';
First : Boolean := True;
Start_Of_Line : Boolean := True;
begin
Open (Handle, In_File, Filename);
loop
exit when End_Of_File (Handle);
Get (Handle, Char);
if First then
Put_Line (Prefix & "===== Output =======");
First := False;
end if;
if Start_Of_Line then
Put (Prefix);
Start_Of_Line := False;
end if;
Put (Char);
if End_Of_Line (Handle) then
New_Line;
Start_Of_Line := True;
end if;
end loop;
Close (Handle);
if not First then
Put_Line (Prefix & "====================");
end if;
exception
when Name_Error =>
-- Missing output file is ok.
Put_Line (Prefix & "no output");
end Print_Log_File;
procedure Add_Pass (Listener : in out Tap_Listener;
Info : Context) is
use Ada.Strings;
use Ada.Strings.Fixed;
begin
if Listener.Capture_Output then
Temporary_Output.Restore_Output;
Temporary_Output.Close_Temp (Listener.Output_File);
end if;
Put ("ok ");
Put (Count_Image (Listener.Current_Test) & " ");
Put (To_String (Info.Test_Name) & ": " & To_String (Info.Routine_Name));
New_Line;
end Add_Pass;
procedure Report_Not_Ok (Listener : in out Tap_Listener;
Info : Context;
Severity : String) is
pragma Unreferenced (Severity);
use Ada.Strings;
use Ada.Strings.Fixed;
begin
if Listener.Capture_Output then
Temporary_Output.Restore_Output;
Temporary_Output.Close_Temp (Listener.Output_File);
end if;
Put ("not ok ");
Put (Count_Image (Listener.Current_Test) & " ");
Put (To_String (Info.Test_Name) & ": " & To_String (Info.Routine_Name));
New_Line;
if Listener.Verbose then
Print_Info (Info);
if Listener.Capture_Output then
Print_Log_File
(Filename => Temporary_Output.Get_Name (Listener.Output_File),
Prefix => "# ");
end if;
end if;
end Report_Not_Ok;
procedure Add_Failure (Listener : in out Tap_Listener;
Info : Context) is
begin
Report_Not_Ok (Listener, Info, "fail");
end Add_Failure;
procedure Add_Error (Listener : in out Tap_Listener;
Info : Context) is
begin
Report_Not_Ok (Listener, Info, "error");
end Add_Error;
procedure Add_Skipped (Listener : in out Tap_Listener;
Info : Context) is
use Ada.Strings;
use Ada.Strings.Fixed;
begin
if Listener.Capture_Output then
Temporary_Output.Restore_Output;
Temporary_Output.Close_Temp (Listener.Output_File);
end if;
Put ("ok ");
Put (Count_Image (Listener.Current_Test) & " ");
Put (To_String (Info.Test_Name) & ": " & To_String (Info.Routine_Name));
Put (" # SKIP " & To_String (Info.Message));
New_Line;
end Add_Skipped;
procedure Start_Test (Listener : in out Tap_Listener;
Info : Context) is
begin
if Info.Test_Kind = ROUTINE then
Listener.Current_Test := Listener.Current_Test + 1;
if Listener.Capture_Output then
Temporary_Output.Create_Temp (Listener.Output_File);
Temporary_Output.Redirect_Output (Listener.Output_File);
end if;
end if;
end Start_Test;
procedure End_Test (Listener : in out Tap_Listener;
Info : Context) is
pragma Unreferenced (Info);
Handle : Ada.Text_IO.File_Type;
begin
if Listener.Capture_Output then
Ada.Text_IO.Open (Handle, Ada.Text_IO.Out_File,
Temporary_Output.Get_Name (Listener.Output_File));
Ada.Text_IO.Delete (Handle);
end if;
exception
when Name_Error =>
-- Missing file is safe to ignore, we are going to delete it anyway
null;
end End_Test;
end Ahven.Tap_Runner;
|
--
-- Copyright (c) 2008-2009 Tero Koskinen <[email protected]>
--
-- 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.Text_IO;
with Ada.Strings.Fixed;
with Ada.Characters.Latin_1;
with Ahven.Parameters;
with Ahven.AStrings;
with Ahven.Long_AStrings;
package body Ahven.Tap_Runner is
use Ada.Text_IO;
use Ahven.Framework;
use Ahven.AStrings;
function Count_Image (Count : Test_Count_Type) return String is
use Ada.Strings;
begin
return Fixed.Trim (Test_Count_Type'Image (Count), Both);
end Count_Image;
procedure Print_Data (Message : String; Prefix : String) is
Start_Of_Line : Boolean := True;
begin
for I in Message'Range loop
if Start_Of_Line then
Put (Prefix);
Start_Of_Line := False;
end if;
if Message (I) = Ada.Characters.Latin_1.LF then
New_Line;
Start_Of_Line := True;
elsif Message (I) /= Ada.Characters.Latin_1.CR then
Put (Message (I));
end if;
end loop;
if not Start_Of_Line then
New_Line;
end if;
end Print_Data;
procedure Run (Suite : in out Framework.Test'Class) is
Listener : Tap_Listener;
Params : Parameters.Parameter_Info;
begin
Parameters.Parse_Parameters (Parameters.TAP_PARAMETERS, Params);
Listener.Verbose := Parameters.Verbose (Params);
Listener.Capture_Output := Parameters.Capture (Params);
if Parameters.Single_Test (Params) then
Put_Line ("1.." & Count_Image (Test_Count
(Suite, Parameters.Test_Name (Params))));
Framework.Execute
(T => Suite,
Test_Name => Parameters.Test_Name (Params),
Listener => Listener,
Timeout => Parameters.Timeout (Params));
else
Put_Line ("1.." & Count_Image (Test_Count (Suite)));
Framework.Execute (Suite, Listener, Parameters.Timeout (Params));
end if;
exception
when Parameters.Invalid_Parameter =>
Parameters.Usage (Parameters.TAP_PARAMETERS);
end Run;
procedure Print_Info (Info : Context) is
begin
if Length (Info.Message) > 0 then
Print_Data (Message => To_String (Info.Message), Prefix => "# ");
end if;
if Long_AStrings.Length (Info.Long_Message) > 0 then
Print_Data
(Message => Long_AStrings.To_String (Info.Long_Message),
Prefix => "# ");
end if;
end Print_Info;
procedure Print_Log_File (Filename : String; Prefix : String) is
Handle : File_Type;
Char : Character := ' ';
First : Boolean := True;
Start_Of_Line : Boolean := True;
begin
Open (Handle, In_File, Filename);
loop
exit when End_Of_File (Handle);
Get (Handle, Char);
if First then
Put_Line (Prefix & "===== Output =======");
First := False;
end if;
if Start_Of_Line then
Put (Prefix);
Start_Of_Line := False;
end if;
Put (Char);
if End_Of_Line (Handle) then
New_Line;
Start_Of_Line := True;
end if;
end loop;
Close (Handle);
if not First then
Put_Line (Prefix & "====================");
end if;
exception
when Name_Error =>
-- Missing output file is ok.
Put_Line (Prefix & "no output");
end Print_Log_File;
procedure Add_Pass (Listener : in out Tap_Listener;
Info : Context) is
begin
if Listener.Capture_Output then
Temporary_Output.Restore_Output;
Temporary_Output.Close_Temp (Listener.Output_File);
end if;
Put ("ok ");
Put (Count_Image (Listener.Current_Test) & " ");
Put (To_String (Info.Test_Name) & ": " & To_String (Info.Routine_Name));
New_Line;
end Add_Pass;
procedure Report_Not_Ok (Listener : in out Tap_Listener;
Info : Context;
Severity : String) is
pragma Unreferenced (Severity);
begin
if Listener.Capture_Output then
Temporary_Output.Restore_Output;
Temporary_Output.Close_Temp (Listener.Output_File);
end if;
Put ("not ok ");
Put (Count_Image (Listener.Current_Test) & " ");
Put (To_String (Info.Test_Name) & ": " & To_String (Info.Routine_Name));
New_Line;
if Listener.Verbose then
Print_Info (Info);
if Listener.Capture_Output then
Print_Log_File
(Filename => Temporary_Output.Get_Name (Listener.Output_File),
Prefix => "# ");
end if;
end if;
end Report_Not_Ok;
procedure Add_Failure (Listener : in out Tap_Listener;
Info : Context) is
begin
Report_Not_Ok (Listener, Info, "fail");
end Add_Failure;
procedure Add_Error (Listener : in out Tap_Listener;
Info : Context) is
begin
Report_Not_Ok (Listener, Info, "error");
end Add_Error;
procedure Add_Skipped (Listener : in out Tap_Listener;
Info : Context) is
begin
if Listener.Capture_Output then
Temporary_Output.Restore_Output;
Temporary_Output.Close_Temp (Listener.Output_File);
end if;
Put ("ok ");
Put (Count_Image (Listener.Current_Test) & " ");
Put (To_String (Info.Test_Name) & ": " & To_String (Info.Routine_Name));
Put (" # SKIP " & To_String (Info.Message));
New_Line;
end Add_Skipped;
procedure Start_Test (Listener : in out Tap_Listener;
Info : Context) is
begin
if Info.Test_Kind = ROUTINE then
Listener.Current_Test := Listener.Current_Test + 1;
if Listener.Capture_Output then
Temporary_Output.Create_Temp (Listener.Output_File);
Temporary_Output.Redirect_Output (Listener.Output_File);
end if;
end if;
end Start_Test;
procedure End_Test (Listener : in out Tap_Listener;
Info : Context) is
pragma Unreferenced (Info);
Handle : Ada.Text_IO.File_Type;
begin
if Listener.Capture_Output then
Ada.Text_IO.Open (Handle, Ada.Text_IO.Out_File,
Temporary_Output.Get_Name (Listener.Output_File));
Ada.Text_IO.Delete (Handle);
end if;
exception
when Name_Error =>
-- Missing file is safe to ignore, we are going to delete it anyway
null;
end End_Test;
end Ahven.Tap_Runner;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
182625b0a0db69a40a9f8da6943646f8989769f0
|
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_Encoded < Buffer'Last then
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Write_Pos := Stream.Buffer'First;
else
Stream.Write_Pos := Last_Pos + 1;
end if;
First_Encoded := Last_Encoded + 1;
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out 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
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 the test to write the output buffer when it becomes full
|
Fix the test to write the output buffer when it becomes full
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a87075e6b04fae31208e43e71354da376d7716ab
|
regtests/util-http-clients-tests.adb
|
regtests/util-http-clients-tests.adb
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put",
Test_Http_Put'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete",
Test_Http_Delete'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Test_Server'Class,
Name => Test_Server_Access);
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
Free (T.Server);
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
elsif L (L'First .. Pos - 1) = "PUT" then
Into.Method := PUT;
elsif L (L'First .. Pos - 1) = "DELETE" then
Into.Method := DELETE;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
elsif L'Length = 2 then
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302,
"Get status is invalid: " & Natural'Image (Reply.Get_Status));
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
-- ------------------------------
-- Test the http PUT operation.
-- ------------------------------
procedure Test_Http_Put (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Put on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
Request.Put (Uri & "/put",
"p1=1", Reply);
T.Assert (T.Server.Method = PUT, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_put.txt"), Reply, True);
end Test_Http_Put;
-- ------------------------------
-- Test the http DELETE operation.
-- ------------------------------
procedure Test_Http_Delete (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Delete on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
-- Request.Set_Timeout (2.0);
Request.Delete (Uri & "/delete", Reply);
T.Assert (T.Server.Method = DELETE, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response");
Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response");
end Test_Http_Delete;
end Util.Http.Clients.Tests;
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put",
Test_Http_Put'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete",
Test_Http_Delete'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get (timeout)",
Test_Http_Timeout'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Test_Server'Class,
Name => Test_Server_Access);
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
Free (T.Server);
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
elsif L (L'First .. Pos - 1) = "PUT" then
Into.Method := PUT;
elsif L (L'First .. Pos - 1) = "DELETE" then
Into.Method := DELETE;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
-- Don't answer if we check the timeout.
if Into.Test_Timeout then
return;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
elsif L'Length = 2 then
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302,
"Get status is invalid: " & Natural'Image (Reply.Get_Status));
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found");
T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"),
"Some invalid header found");
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
-- ------------------------------
-- Test the http PUT operation.
-- ------------------------------
procedure Test_Http_Put (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Put on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type");
Request.Put (Uri & "/put",
"p1=1", Reply);
T.Assert (T.Server.Method = PUT, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_put.txt"), Reply, True);
end Test_Http_Put;
-- ------------------------------
-- Test the http DELETE operation.
-- ------------------------------
procedure Test_Http_Delete (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Delete on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type");
Request.Delete (Uri & "/delete", Reply);
T.Assert (T.Server.Method = DELETE, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response");
Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response");
end Test_Http_Delete;
-- ------------------------------
-- Test the http timeout.
-- ------------------------------
procedure Test_Http_Timeout (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Timeout on " & Uri);
T.Server.Test_Timeout := True;
T.Server.Method := UNKNOWN;
Request.Set_Timeout (0.5);
begin
Request.Get (Uri & "/timeout", Reply);
T.Fail ("No Connection_Error exception raised");
exception
when Connection_Error =>
null;
end;
end Test_Http_Timeout;
end Util.Http.Clients.Tests;
|
Add Test_Http_Timeout and register the test for execution
|
Add Test_Http_Timeout and register the test for execution
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
28f70a25c77656d795a8c9333dd1c3b02bd56787
|
awa/plugins/awa-images/src/awa-images-services.adb
|
awa/plugins/awa-images/src/awa-images-services.adb
|
-----------------------------------------------------------------------
-- awa-images-services -- Image service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Processes;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Streams.Pipes;
with Util.Streams.Texts;
with ADO.Sessions;
with AWA.Images.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
with AWA.Storages.Modules;
with Ada.Strings.Unbounded;
with EL.Variables.Default;
with EL.Contexts.Default;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
package body AWA.Images.Services is
package ASC renames Awa.Services.Contexts;
-- ------------------------------
-- Image Service
-- ------------------------------
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services");
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Image_Service;
Module : in AWA.Modules.Module'Class) is
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
declare
Ctx : EL.Contexts.Default.Default_Context;
Command : constant String := Module.Get_Config (PARAM_THUMBNAIL_COMMAND);
begin
Service.Thumbnail_Command := EL.Expressions.Create_Expression (Command, Ctx);
exception
when E : others =>
Log.Error ("Invalid thumbnail command: ", E, True);
end;
end Initialize;
procedure Create_Thumbnail (Service : in Image_Service;
Source : in String;
Into : in String;
Width : out Natural;
Height : out Natural) is
Ctx : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
Proc : Util.Processes.Process;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
begin
Variables.Bind ("src", Util.Beans.Objects.To_Object (Source));
Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into));
Ctx.Set_Variable_Mapper (Variables'Unchecked_Access);
declare
Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx);
Command : constant String := Util.Beans.Objects.To_String (Cmd);
Input : Util.Streams.Texts.Reader_Stream;
begin
Width := 0;
Height := 0;
Pipe.Open (Command, Util.Processes.READ);
Input.Initialize (null, Pipe'Unchecked_Access, 1024);
while not Input.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
Pos : Natural;
Sep : Natural;
Last : Natural;
begin
Input.Read_Line (Into => Line, Strip => False);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Log.Info ("Received: {0}", Line);
-- The '-verbose' option of ImageMagick reports information about the original
-- image. Extract the picture width and height.
-- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018
Pos := Ada.Strings.Unbounded.Index (Line, " ");
if Pos > 0 and Width = 0 then
Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1);
if Pos > 0 then
Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1);
Last := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1);
if Sep > 0 and Sep < Last then
Width := Natural'Value (Ada.Strings.Unbounded.Slice (Line, Pos + 1, Sep - 1));
Height := Natural'Value (Ada.Strings.Unbounded.Slice (Line, Sep + 1, Last - 1));
end if;
end if;
end if;
end;
end loop;
Pipe.Close;
Util.Processes.Wait (Proc);
if Pipe.Get_Exit_Status /= 0 then
Log.Error ("Command {0} exited with status {1}", Command,
Integer'Image (Pipe.Get_Exit_Status));
end if;
end;
end Create_Thumbnail;
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Build_Thumbnail (Service : in Image_Service;
Id : in ADO.Identifier;
File : in AWA.Storages.Models.Storage_Ref'Class) is
Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
Local_Path : Ada.Strings.Unbounded.Unbounded_String;
Target_File : AWA.Storages.Storage_File;
Local_File : AWA.Storages.Storage_File;
Width : Natural;
Height : Natural;
begin
Img.Load (DB, Id);
Storage_Service.Get_Local_File (From => Img.Get_Storage.Get_Id, Into => Local_File);
Storage_Service.Create_Local_File (Target_File);
Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File),
AWA.Storages.Get_Path (Target_File), Width, Height);
Img.Set_Width (Width);
Img.Set_Height (Height);
Img.Set_Thumb_Width (64);
Img.Set_Thumb_Height (64);
Ctx.Start;
Img.Save (DB);
-- Storage_Service.Save (Target_File);
Ctx.Commit;
end Build_Thumbnail;
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Create_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
begin
Ctx.Start;
Img.Set_Width (0);
Img.Set_Height (0);
Img.Set_Thumb_Height (0);
Img.Set_Thumb_Width (0);
Img.Set_Storage (File);
Img.Save (DB);
Ctx.Commit;
end Create_Image;
-- Deletes the storage instance.
procedure Delete_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
begin
null;
end Delete_Image;
end AWA.Images.Services;
|
-----------------------------------------------------------------------
-- awa-images-services -- Image service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Processes;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Streams.Pipes;
with Util.Streams.Texts;
with ADO.Sessions;
with AWA.Images.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
with AWA.Storages.Modules;
with Ada.Strings.Unbounded;
with EL.Variables.Default;
with EL.Contexts.Default;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
package body AWA.Images.Services is
package ASC renames Awa.Services.Contexts;
-- ------------------------------
-- Image Service
-- ------------------------------
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services");
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Image_Service;
Module : in AWA.Modules.Module'Class) is
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
declare
Ctx : EL.Contexts.Default.Default_Context;
Command : constant String := Module.Get_Config (PARAM_THUMBNAIL_COMMAND);
begin
Service.Thumbnail_Command := EL.Expressions.Create_Expression (Command, Ctx);
exception
when E : others =>
Log.Error ("Invalid thumbnail command: ", E, True);
end;
end Initialize;
procedure Create_Thumbnail (Service : in Image_Service;
Source : in String;
Into : in String;
Width : out Natural;
Height : out Natural) is
Ctx : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
Proc : Util.Processes.Process;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
begin
Variables.Bind ("src", Util.Beans.Objects.To_Object (Source));
Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into));
Ctx.Set_Variable_Mapper (Variables'Unchecked_Access);
declare
Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx);
Command : constant String := Util.Beans.Objects.To_String (Cmd);
Input : Util.Streams.Texts.Reader_Stream;
begin
Width := 0;
Height := 0;
Pipe.Open (Command, Util.Processes.READ);
Input.Initialize (null, Pipe'Unchecked_Access, 1024);
while not Input.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
Pos : Natural;
Sep : Natural;
Last : Natural;
begin
Input.Read_Line (Into => Line, Strip => False);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Log.Info ("Received: {0}", Line);
-- The '-verbose' option of ImageMagick reports information about the original
-- image. Extract the picture width and height.
-- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018
Pos := Ada.Strings.Unbounded.Index (Line, " ");
if Pos > 0 and Width = 0 then
Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1);
if Pos > 0 then
Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1);
Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1);
if Sep > 0 and Sep < Last then
Log.Info ("Dimension {0} - {1}..{2}",
Ada.Strings.Unbounded.Slice (Line, Pos, Last),
Natural'Image (Pos), Natural'Image (Last));
Width := Natural'Value (Ada.Strings.Unbounded.Slice (Line, Pos + 1, Sep - 1));
Height := Natural'Value (Ada.Strings.Unbounded.Slice (Line, Sep + 1, Last - 1));
end if;
end if;
end if;
end;
end loop;
Pipe.Close;
Util.Processes.Wait (Proc);
if Pipe.Get_Exit_Status /= 0 then
Log.Error ("Command {0} exited with status {1}", Command,
Integer'Image (Pipe.Get_Exit_Status));
end if;
end;
end Create_Thumbnail;
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Build_Thumbnail (Service : in Image_Service;
Id : in ADO.Identifier;
File : in AWA.Storages.Models.Storage_Ref'Class) is
Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
Local_Path : Ada.Strings.Unbounded.Unbounded_String;
Target_File : AWA.Storages.Storage_File;
Local_File : AWA.Storages.Storage_File;
Width : Natural;
Height : Natural;
begin
Img.Load (DB, Id);
Storage_Service.Get_Local_File (From => Img.Get_Storage.Get_Id, Into => Local_File);
Storage_Service.Create_Local_File (Target_File);
Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File),
AWA.Storages.Get_Path (Target_File), Width, Height);
Img.Set_Width (Width);
Img.Set_Height (Height);
Img.Set_Thumb_Width (64);
Img.Set_Thumb_Height (64);
Ctx.Start;
Img.Save (DB);
-- Storage_Service.Save (Target_File);
Ctx.Commit;
end Build_Thumbnail;
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Create_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
begin
Ctx.Start;
Img.Set_Width (0);
Img.Set_Height (0);
Img.Set_Thumb_Height (0);
Img.Set_Thumb_Width (0);
Img.Set_Storage (File);
Img.Save (DB);
Ctx.Commit;
end Create_Image;
-- Deletes the storage instance.
procedure Delete_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
begin
null;
end Delete_Image;
end AWA.Images.Services;
|
Fix extraction of image dimension
|
Fix extraction of image dimension
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3e6342e2bbab531216c3932d80b69e78f7fc4b1e
|
tools/druss-commands-devices.adb
|
tools/druss-commands-devices.adb
|
-----------------------------------------------------------------------
-- druss-commands-devices -- Print information about the devices
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
with Bbox.API;
with Druss.Gateways;
package body Druss.Commands.Devices is
-- ------------------------------
-- Execute the wifi 'status' command to print the Wifi current status.
-- ------------------------------
procedure Do_List (Command : in Command_Type;
Args : in Argument_List'Class;
Selector : in Device_Selector_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command, Args);
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String);
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String) is
Link : constant String := Manager.Get (Name & ".link", "");
Kind : constant String := Manager.Get (Name & ".devicetype", "");
begin
case Selector is
when DEVICE_ALL =>
null;
when DEVICE_ACTIVE =>
if Manager.Get (Name & ".active", "") = "0" then
return;
end if;
when DEVICE_INACTIVE =>
if Manager.Get (Name & ".active", "") = "1" then
return;
end if;
end case;
Console.Start_Row;
Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip);
Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", ""));
Console.Print_Field (F_ETHERNET, Manager.Get (Name & ".macaddress", ""));
Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", ""));
Console.Print_Field (F_ACTIVE, Manager.Get (Name & ".active", ""));
Console.Print_Field (F_DEVTYPE, (if Kind = "STB" then "STB" else ""));
if Link = "Ethernet" then
Console.Print_Field (F_LINK, Link & " port "
& Manager.Get (Name & ".ethernet.logicalport", ""));
else
Console.Print_Field (F_LINK, Link & " RSSI "
& Manager.Get (Name & ".wireless.rssi0", ""));
end if;
Console.End_Row;
end Print_Device;
begin
Gateway.Refresh;
Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access);
end Box_Status;
begin
Console.Start_Title;
Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16);
Console.Print_Title (F_IP_ADDR, "Device IP", 16);
Console.Print_Title (F_ETHERNET, "Ethernet", 20);
Console.Print_Title (F_HOSTNAME, "Hostname", 28);
Console.Print_Title (F_DEVTYPE, "Type", 6);
-- Console.Print_Title (F_ACTIVE, "Active", 8);
Console.Print_Title (F_LINK, "Link", 18);
Console.End_Title;
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access);
end Do_List;
-- ------------------------------
-- Execute a status command to report information about the Bbox.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
if Args.Get_Count > 1 then
Context.Console.Notice (N_USAGE, "Too many arguments to the command");
Druss.Commands.Driver.Usage (Args);
elsif Args.Get_Count = 0 then
Command.Do_List (Args, DEVICE_ACTIVE, Context);
elsif Args.Get_Argument (1) = "all" then
Command.Do_List (Args, DEVICE_ALL, Context);
elsif Args.Get_Argument (1) = "active" then
Command.Do_List (Args, DEVICE_ACTIVE, Context);
elsif Args.Get_Argument (1) = "inactive" then
Command.Do_List (Args, DEVICE_INACTIVE, Context);
else
Context.Console.Notice (N_USAGE, "Invalid argument: " & Args.Get_Argument (1));
Druss.Commands.Driver.Usage (Args);
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP, "devices: Print information about the devices");
Console.Notice (N_HELP, "Usage: devices [all | active | inactive]");
Console.Notice (N_HELP, "");
Console.Notice (N_HELP, " List the devices that are known by the Bbox.");
Console.Notice (N_HELP, "");
Console.Notice (N_HELP, " all List all the devices");
Console.Notice (N_HELP, " active List the active devices (the default)");
Console.Notice (N_HELP, " inative List the inactive devices");
end Help;
end Druss.Commands.Devices;
|
-----------------------------------------------------------------------
-- druss-commands-devices -- Print information about the devices
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
with Bbox.API;
with Druss.Gateways;
package body Druss.Commands.Devices is
-- ------------------------------
-- Execute the wifi 'status' command to print the Wifi current status.
-- ------------------------------
procedure Do_List (Command : in Command_Type;
Args : in Argument_List'Class;
Selector : in Device_Selector_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command, Args);
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String);
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String) is
Link : constant String := Manager.Get (Name & ".link", "");
Kind : constant String := Manager.Get (Name & ".devicetype", "");
begin
case Selector is
when DEVICE_ALL =>
null;
when DEVICE_ACTIVE =>
if Manager.Get (Name & ".active", "") = "0" then
return;
end if;
when DEVICE_INACTIVE =>
if Manager.Get (Name & ".active", "") = "1" then
return;
end if;
end case;
Console.Start_Row;
Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip);
Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", ""));
Console.Print_Field (F_ETHERNET, Manager.Get (Name & ".macaddress", ""));
Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", ""));
Console.Print_Field (F_ACTIVE, Manager.Get (Name & ".active", ""));
Console.Print_Field (F_DEVTYPE, (if Kind = "STB" then "STB" else ""));
if Link = "Ethernet" then
Console.Print_Field (F_LINK, Link & " port "
& Manager.Get (Name & ".ethernet.logicalport", ""));
else
Console.Print_Field (F_LINK, Link & " RSSI "
& Manager.Get (Name & ".wireless.rssi0", ""));
end if;
Console.End_Row;
end Print_Device;
begin
Gateway.Refresh;
Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access);
end Box_Status;
begin
Console.Start_Title;
Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16);
Console.Print_Title (F_IP_ADDR, "Device IP", 16);
Console.Print_Title (F_ETHERNET, "Ethernet", 20);
Console.Print_Title (F_HOSTNAME, "Hostname", 28);
Console.Print_Title (F_DEVTYPE, "Type", 6);
-- Console.Print_Title (F_ACTIVE, "Active", 8);
Console.Print_Title (F_LINK, "Link", 18);
Console.End_Title;
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access);
end Do_List;
-- ------------------------------
-- Execute a status command to report information about the Bbox.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
if Args.Get_Count > 1 then
Context.Console.Notice (N_USAGE, "Too many arguments to the command");
Druss.Commands.Driver.Usage (Args, Context);
elsif Args.Get_Count = 0 then
Command.Do_List (Args, DEVICE_ACTIVE, Context);
elsif Args.Get_Argument (1) = "all" then
Command.Do_List (Args, DEVICE_ALL, Context);
elsif Args.Get_Argument (1) = "active" then
Command.Do_List (Args, DEVICE_ACTIVE, Context);
elsif Args.Get_Argument (1) = "inactive" then
Command.Do_List (Args, DEVICE_INACTIVE, Context);
else
Context.Console.Notice (N_USAGE, "Invalid argument: " & Args.Get_Argument (1));
Druss.Commands.Driver.Usage (Args, Context);
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP, "devices: Print information about the devices");
Console.Notice (N_HELP, "Usage: devices [all | active | inactive]");
Console.Notice (N_HELP, "");
Console.Notice (N_HELP, " List the devices that are known by the Bbox.");
Console.Notice (N_HELP, "");
Console.Notice (N_HELP, " all List all the devices");
Console.Notice (N_HELP, " active List the active devices (the default)");
Console.Notice (N_HELP, " inative List the inactive devices");
end Help;
end Druss.Commands.Devices;
|
Change Help command to accept in out command
|
Change Help command to accept in out command
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
69354165a1264ebaaddf59f54cf5adf1f51072b7
|
src/asf-components-html-messages.adb
|
src/asf-components-html-messages.adb
|
-----------------------------------------------------------------------
-- html.messages -- Faces messages
-- 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.Utils;
with ASF.Applications.Messages;
with ASF.Components.Base;
-- The <b>ASF.Components.Html.Messages</b> package implements the <b>h:message</b>
-- and <b>h:messages</b> components.
package body ASF.Components.Html.Messages is
use ASF.Components.Base;
use ASF.Applications.Messages;
MSG_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FATAL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
ERROR_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
WARN_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
INFO_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Check whether the UI component whose name is given in <b>Name</b> has some messages
-- associated with it.
-- ------------------------------
function Has_Message (Name : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Context = null then
return Util.Beans.Objects.To_Object (False);
end if;
declare
Id : constant String := Util.Beans.Objects.To_String (Name);
Msgs : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
return Util.Beans.Objects.To_Object (Applications.Messages.Vectors.Has_Element (Msgs));
end;
end Has_Message;
-- ------------------------------
-- Write a single message enclosed by the tag represented by <b>Tag</b>.
-- ------------------------------
procedure Write_Message (UI : in UIHtmlComponent'Class;
Message : in ASF.Applications.Messages.Message;
Mode : in Message_Mode;
Show_Detail : in Boolean;
Show_Summary : in Boolean;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
case Mode is
when SPAN_NO_STYLE =>
Writer.Start_Element ("span");
when SPAN =>
Writer.Start_Element ("span");
UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer);
when LIST =>
Writer.Start_Element ("li");
when TABLE =>
Writer.Start_Element ("tr");
end case;
case Get_Severity (Message) is
when FATAL =>
UI.Render_Attributes (Context, FATAL_ATTRIBUTE_NAMES, Writer);
when ERROR =>
UI.Render_Attributes (Context, ERROR_ATTRIBUTE_NAMES, Writer);
when WARN =>
UI.Render_Attributes (Context, WARN_ATTRIBUTE_NAMES, Writer);
when INFO | NONE =>
UI.Render_Attributes (Context, INFO_ATTRIBUTE_NAMES, Writer);
end case;
if Mode = TABLE then
Writer.Start_Element ("td");
end if;
if Show_Summary then
Writer.Write_Text (Get_Summary (Message));
end if;
if Show_Detail then
Writer.Write_Text (Get_Detail (Message));
end if;
case Mode is
when SPAN | SPAN_NO_STYLE =>
Writer.End_Element ("span");
when LIST =>
Writer.End_Element ("li");
when TABLE =>
Writer.End_Element ("td");
Writer.End_Element ("tr");
end case;
end Write_Message;
-- ------------------------------
-- Render a list of messages each of them being enclosed by the <b>Tag</b> element.
-- ------------------------------
procedure Write_Messages (UI : in UIHtmlComponent'Class;
Mode : in Message_Mode;
Context : in out Faces_Context'Class;
Messages : in out ASF.Applications.Messages.Vectors.Cursor) is
procedure Process_Message (Message : in ASF.Applications.Messages.Message);
Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True);
Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False);
procedure Process_Message (Message : in ASF.Applications.Messages.Message) is
begin
Write_Message (UI, Message, Mode, Show_Detail, Show_Summary, Context);
end Process_Message;
begin
while ASF.Applications.Messages.Vectors.Has_Element (Messages) loop
Vectors.Query_Element (Messages, Process_Message'Access);
Vectors.Next (Messages);
end loop;
end Write_Messages;
-- ------------------------------
-- Encode the begining of the <b>h:message</b> component.
-- ------------------------------
procedure Encode_Begin (UI : in UIMessage;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for");
Messages : ASF.Applications.Messages.Vectors.Cursor;
begin
-- No specification of 'for' attribute, render the global messages.
if Util.Beans.Objects.Is_Null (Name) then
Messages := Context.Get_Messages ("");
else
declare
Id : constant String := Util.Beans.Objects.To_String (Name);
Target : constant UIComponent_Access := UI.Find (Id => Id);
begin
-- If the component does not exist, report an error in the logs.
if Target = null then
UI.Log_Error ("Cannot find component {0}", Id);
else
Messages := Context.Get_Messages (Id);
end if;
end;
end if;
-- If we have some message, render the first one (as specified by <h:message>).
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
declare
Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True);
Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False);
begin
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN, Show_Detail, Show_Summary, Context);
end;
end if;
end;
end Encode_Begin;
-- Encode the end of the <b>h:message</b> component.
procedure Encode_End (UI : in UIMessage;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_End;
-- ------------------------------
-- Encode the begining of the <b>h:message</b> component.
-- ------------------------------
procedure Encode_Begin (UI : in UIMessages;
Context : in out Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for");
Messages : ASF.Applications.Messages.Vectors.Cursor;
begin
-- No specification of 'for' attribute, render the global messages.
if Util.Beans.Objects.Is_Null (Name) then
if UI.Get_Attribute ("globalOnly", Context) then
Messages := Context.Get_Messages ("");
end if;
else
declare
Id : constant String := Util.Beans.Objects.To_String (Name);
Target : constant UIComponent_Access := UI.Find (Id => Id);
begin
-- If the component does not exist, report an error in the logs.
if Target = null then
UI.Log_Error ("Cannot find component {0}", Id);
else
Messages := Context.Get_Messages (Id);
end if;
end;
end if;
-- If we have some message, render them.
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Layout : constant String
:= Util.Beans.Objects.To_String (UI.Get_Attribute (Context, "layout"));
begin
if Layout = "table" then
Writer.Start_Element ("table");
UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer);
Write_Messages (UI, TABLE, Context, Messages);
Writer.End_Element ("table");
else
Writer.Start_Element ("ul");
UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer);
Write_Messages (UI, LIST, Context, Messages);
Writer.End_Element ("ul");
end if;
end;
end if;
end;
end if;
end Encode_Begin;
-- Encode the end of the <b>h:message</b> component.
procedure Encode_End (UI : in UIMessages;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_End;
FATAL_CLASS_ATTR : aliased constant String := "fatalClass";
FATAL_STYLE_CLASS_ATTR : aliased constant String := "fatalStyle";
ERROR_CLASS_ATTR : aliased constant String := "errorClass";
ERROR_STYLE_CLASS_ATTR : aliased constant String := "errorStyle";
WARN_CLASS_ATTR : aliased constant String := "warnClass";
WARN_STYLE_CLASS_ATTR : aliased constant String := "warnStyle";
INFO_CLASS_ATTR : aliased constant String := "infoClass";
INFO_STYLE_CLASS_ATTR : aliased constant String := "infoStyle";
begin
ASF.Utils.Set_Text_Attributes (MSG_ATTRIBUTE_NAMES);
-- ASF.Utils.Set_Text_Attributes (WARN_ATTRIBUTE_NAMES);
-- ASF.Utils.Set_Text_Attributes (INFO_ATTRIBUTE_NAMES);
--
-- ASF.Utils.Set_Text_Attributes (FATAL_ATTRIBUTE_NAMES);
FATAL_ATTRIBUTE_NAMES.Insert (FATAL_CLASS_ATTR'Access);
FATAL_ATTRIBUTE_NAMES.Insert (FATAL_STYLE_CLASS_ATTR'Access);
ERROR_ATTRIBUTE_NAMES.Insert (ERROR_CLASS_ATTR'Access);
ERROR_ATTRIBUTE_NAMES.Insert (ERROR_STYLE_CLASS_ATTR'Access);
WARN_ATTRIBUTE_NAMES.Insert (WARN_CLASS_ATTR'Access);
WARN_ATTRIBUTE_NAMES.Insert (WARN_STYLE_CLASS_ATTR'Access);
INFO_ATTRIBUTE_NAMES.Insert (INFO_CLASS_ATTR'Access);
INFO_ATTRIBUTE_NAMES.Insert (INFO_STYLE_CLASS_ATTR'Access);
end ASF.Components.Html.Messages;
|
-----------------------------------------------------------------------
-- html.messages -- Faces messages
-- 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 ASF.Utils;
with ASF.Applications.Messages;
with ASF.Components.Base;
-- The <b>ASF.Components.Html.Messages</b> package implements the <b>h:message</b>
-- and <b>h:messages</b> components.
package body ASF.Components.Html.Messages is
use ASF.Components.Base;
use ASF.Applications.Messages;
MSG_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FATAL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
ERROR_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
WARN_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
INFO_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Check whether the UI component whose name is given in <b>Name</b> has some messages
-- associated with it.
-- ------------------------------
function Has_Message (Name : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Context = null then
return Util.Beans.Objects.To_Object (False);
end if;
declare
Id : constant String := Util.Beans.Objects.To_String (Name);
Msgs : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
return Util.Beans.Objects.To_Object (Applications.Messages.Vectors.Has_Element (Msgs));
end;
end Has_Message;
-- ------------------------------
-- Write a single message enclosed by the tag represented by <b>Tag</b>.
-- ------------------------------
procedure Write_Message (UI : in UIHtmlComponent'Class;
Message : in ASF.Applications.Messages.Message;
Mode : in Message_Mode;
Show_Detail : in Boolean;
Show_Summary : in Boolean;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
case Mode is
when SPAN_NO_STYLE =>
Writer.Start_Element ("span");
when SPAN =>
Writer.Start_Element ("span");
UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer);
when LIST =>
Writer.Start_Element ("li");
when TABLE =>
Writer.Start_Element ("tr");
end case;
case Get_Severity (Message) is
when FATAL =>
UI.Render_Attributes (Context, FATAL_ATTRIBUTE_NAMES, Writer,
Write_Id => Mode /= SPAN_NO_STYLE);
when ERROR =>
UI.Render_Attributes (Context, ERROR_ATTRIBUTE_NAMES, Writer,
Write_Id => Mode /= SPAN_NO_STYLE);
when WARN =>
UI.Render_Attributes (Context, WARN_ATTRIBUTE_NAMES, Writer,
Write_Id => Mode /= SPAN_NO_STYLE);
when INFO | NONE =>
UI.Render_Attributes (Context, INFO_ATTRIBUTE_NAMES, Writer,
Write_Id => Mode /= SPAN_NO_STYLE);
end case;
if Mode = TABLE then
Writer.Start_Element ("td");
end if;
if Show_Summary then
Writer.Write_Text (Get_Summary (Message));
end if;
if Show_Detail then
Writer.Write_Text (Get_Detail (Message));
end if;
case Mode is
when SPAN | SPAN_NO_STYLE =>
Writer.End_Element ("span");
when LIST =>
Writer.End_Element ("li");
when TABLE =>
Writer.End_Element ("td");
Writer.End_Element ("tr");
end case;
end Write_Message;
-- ------------------------------
-- Render a list of messages each of them being enclosed by the <b>Tag</b> element.
-- ------------------------------
procedure Write_Messages (UI : in UIHtmlComponent'Class;
Mode : in Message_Mode;
Context : in out Faces_Context'Class;
Messages : in out ASF.Applications.Messages.Vectors.Cursor) is
procedure Process_Message (Message : in ASF.Applications.Messages.Message);
Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True);
Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False);
procedure Process_Message (Message : in ASF.Applications.Messages.Message) is
begin
Write_Message (UI, Message, Mode, Show_Detail, Show_Summary, Context);
end Process_Message;
begin
while ASF.Applications.Messages.Vectors.Has_Element (Messages) loop
Vectors.Query_Element (Messages, Process_Message'Access);
Vectors.Next (Messages);
end loop;
end Write_Messages;
-- ------------------------------
-- Encode the begining of the <b>h:message</b> component.
-- ------------------------------
procedure Encode_Begin (UI : in UIMessage;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for");
Messages : ASF.Applications.Messages.Vectors.Cursor;
begin
-- No specification of 'for' attribute, render the global messages.
if Util.Beans.Objects.Is_Null (Name) then
Messages := Context.Get_Messages ("");
else
declare
Id : constant String := Util.Beans.Objects.To_String (Name);
Target : constant UIComponent_Access := UI.Find (Id => Id);
begin
-- If the component does not exist, report an error in the logs.
if Target = null then
UI.Log_Error ("Cannot find component {0}", Id);
else
Messages := Context.Get_Messages (Id);
end if;
end;
end if;
-- If we have some message, render the first one (as specified by <h:message>).
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
declare
Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True);
Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False);
begin
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN, Show_Detail, Show_Summary, Context);
end;
end if;
end;
end Encode_Begin;
-- Encode the end of the <b>h:message</b> component.
procedure Encode_End (UI : in UIMessage;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_End;
-- ------------------------------
-- Encode the begining of the <b>h:message</b> component.
-- ------------------------------
procedure Encode_Begin (UI : in UIMessages;
Context : in out Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for");
Messages : ASF.Applications.Messages.Vectors.Cursor;
begin
-- No specification of 'for' attribute, render the global messages.
if Util.Beans.Objects.Is_Null (Name) then
if UI.Get_Attribute ("globalOnly", Context) then
Messages := Context.Get_Messages ("");
end if;
else
declare
Id : constant String := Util.Beans.Objects.To_String (Name);
Target : constant UIComponent_Access := UI.Find (Id => Id);
begin
-- If the component does not exist, report an error in the logs.
if Target = null then
UI.Log_Error ("Cannot find component {0}", Id);
else
Messages := Context.Get_Messages (Id);
end if;
end;
end if;
-- If we have some message, render them.
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Layout : constant String
:= Util.Beans.Objects.To_String (UI.Get_Attribute (Context, "layout"));
begin
if Layout = "table" then
Writer.Start_Element ("table");
UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer);
Write_Messages (UI, TABLE, Context, Messages);
Writer.End_Element ("table");
else
Writer.Start_Element ("ul");
UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer);
Write_Messages (UI, LIST, Context, Messages);
Writer.End_Element ("ul");
end if;
end;
end if;
end;
end if;
end Encode_Begin;
-- Encode the end of the <b>h:message</b> component.
procedure Encode_End (UI : in UIMessages;
Context : in out Faces_Context'Class) is
begin
null;
end Encode_End;
FATAL_CLASS_ATTR : aliased constant String := "fatalClass";
FATAL_STYLE_CLASS_ATTR : aliased constant String := "fatalStyle";
ERROR_CLASS_ATTR : aliased constant String := "errorClass";
ERROR_STYLE_CLASS_ATTR : aliased constant String := "errorStyle";
WARN_CLASS_ATTR : aliased constant String := "warnClass";
WARN_STYLE_CLASS_ATTR : aliased constant String := "warnStyle";
INFO_CLASS_ATTR : aliased constant String := "infoClass";
INFO_STYLE_CLASS_ATTR : aliased constant String := "infoStyle";
begin
ASF.Utils.Set_Text_Attributes (MSG_ATTRIBUTE_NAMES);
-- ASF.Utils.Set_Text_Attributes (WARN_ATTRIBUTE_NAMES);
-- ASF.Utils.Set_Text_Attributes (INFO_ATTRIBUTE_NAMES);
--
-- ASF.Utils.Set_Text_Attributes (FATAL_ATTRIBUTE_NAMES);
FATAL_ATTRIBUTE_NAMES.Insert (FATAL_CLASS_ATTR'Access);
FATAL_ATTRIBUTE_NAMES.Insert (FATAL_STYLE_CLASS_ATTR'Access);
ERROR_ATTRIBUTE_NAMES.Insert (ERROR_CLASS_ATTR'Access);
ERROR_ATTRIBUTE_NAMES.Insert (ERROR_STYLE_CLASS_ATTR'Access);
WARN_ATTRIBUTE_NAMES.Insert (WARN_CLASS_ATTR'Access);
WARN_ATTRIBUTE_NAMES.Insert (WARN_STYLE_CLASS_ATTR'Access);
INFO_ATTRIBUTE_NAMES.Insert (INFO_CLASS_ATTR'Access);
INFO_ATTRIBUTE_NAMES.Insert (INFO_STYLE_CLASS_ATTR'Access);
end ASF.Components.Html.Messages;
|
Disable the rendering of the component id for the SPAN_NO_STYLE mode
|
Disable the rendering of the component id for the SPAN_NO_STYLE mode
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
00b6a99191fd73c2ccc4d3a0550ef68fd37fd798
|
regtests/util-http-clients-tests.ads
|
regtests/util-http-clients-tests.ads
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Tests;
with Util.Tests.Servers;
with Util.Streams.Texts;
with Util.Streams.Sockets;
package Util.Http.Clients.Tests is
type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, UNKNOWN);
type Test_Server is new Util.Tests.Servers.Server with record
Method : Method_Type := UNKNOWN;
Result : Ada.Strings.Unbounded.Unbounded_String;
Content_Type : Ada.Strings.Unbounded.Unbounded_String;
Length : Natural := 0;
end record;
type Test_Server_Access is access all Test_Server'Class;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class);
type Test is new Util.Tests.Test with record
Server : Test_Server_Access := null;
end record;
-- Test the http Get operation.
procedure Test_Http_Get (T : in out Test);
-- Test the http POST operation.
procedure Test_Http_Post (T : in out Test);
-- Test the http PUT operation.
procedure Test_Http_Put (T : in out Test);
-- Test the http DELETE operation.
procedure Test_Http_Delete (T : in out Test);
overriding
procedure Set_Up (T : in out Test);
overriding
procedure Tear_Down (T : in out Test);
-- Get the test server base URI.
function Get_Uri (T : in Test) return String;
-- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation.
-- The <b>Register</b> procedure configures the Http.Client to use the given HTTP
-- implementation before running the test.
generic
with procedure Register;
NAME : in String;
package Http_Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Http_Test is new Test with null record;
overriding
procedure Set_Up (T : in out Http_Test);
end Http_Tests;
end Util.Http.Clients.Tests;
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Tests;
with Util.Tests.Servers;
with Util.Streams.Texts;
with Util.Streams.Sockets;
package Util.Http.Clients.Tests is
type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, UNKNOWN);
type Test_Server is new Util.Tests.Servers.Server with record
Method : Method_Type := UNKNOWN;
Result : Ada.Strings.Unbounded.Unbounded_String;
Content_Type : Ada.Strings.Unbounded.Unbounded_String;
Length : Natural := 0;
Test_Timeout : Boolean := False;
end record;
type Test_Server_Access is access all Test_Server'Class;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class);
type Test is new Util.Tests.Test with record
Server : Test_Server_Access := null;
end record;
-- Test the http Get operation.
procedure Test_Http_Get (T : in out Test);
-- Test the http POST operation.
procedure Test_Http_Post (T : in out Test);
-- Test the http PUT operation.
procedure Test_Http_Put (T : in out Test);
-- Test the http DELETE operation.
procedure Test_Http_Delete (T : in out Test);
-- Test the http timeout.
procedure Test_Http_Timeout (T : in out Test);
overriding
procedure Set_Up (T : in out Test);
overriding
procedure Tear_Down (T : in out Test);
-- Get the test server base URI.
function Get_Uri (T : in Test) return String;
-- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation.
-- The <b>Register</b> procedure configures the Http.Client to use the given HTTP
-- implementation before running the test.
generic
with procedure Register;
NAME : in String;
package Http_Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Http_Test is new Test with null record;
overriding
procedure Set_Up (T : in out Http_Test);
end Http_Tests;
end Util.Http.Clients.Tests;
|
Declare Test_Http_Timeout procedure
|
Declare Test_Http_Timeout procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a09d708aa742676acf5c5f7eeaa5590ab1dc3a79
|
matp/src/memory/mat-memory.ads
|
matp/src/memory/mat-memory.ads
|
-----------------------------------------------------------------------
-- Memory - Memory slot
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded;
with ELF;
with MAT.Types;
with MAT.Frames;
with MAT.Events.Targets;
package MAT.Memory is
type Allocation is record
Size : MAT.Types.Target_Size;
Frame : Frames.Frame_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Event : MAT.Events.Event_Id_Type;
end record;
-- Statistics about memory allocation.
type Memory_Info is record
Total_Size : MAT.Types.Target_Size := 0;
Alloc_Count : Natural := 0;
Min_Slot_Size : MAT.Types.Target_Size := 0;
Max_Slot_Size : MAT.Types.Target_Size := 0;
Min_Addr : MAT.Types.Target_Addr := 0;
Max_Addr : MAT.Types.Target_Addr := 0;
end record;
-- Description of a memory region.
type Region_Info is record
Start_Addr : MAT.Types.Target_Addr := 0;
End_Addr : MAT.Types.Target_Addr := 0;
Size : MAT.Types.Target_Size := 0;
Flags : ELF.Elf32_Word := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
end record;
use type MAT.Types.Target_Addr;
package Allocation_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Allocation);
subtype Allocation_Map is Allocation_Maps.Map;
subtype Allocation_Cursor is Allocation_Maps.Cursor;
-- Define a map of <tt>Memory_Info</tt> keyed by the thread Id.
-- Such map allows to give the list of threads and a summary of their allocation.
use type MAT.Types.Target_Thread_Ref;
package Memory_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref,
Element_Type => Memory_Info);
subtype Memory_Info_Map is Memory_Info_Maps.Map;
subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor;
type Frame_Info is record
Thread : MAT.Types.Target_Thread_Ref;
Memory : Memory_Info;
end record;
-- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address
-- that performed the memory allocation directly or indirectly.
package Frame_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Frame_Info);
subtype Frame_Info_Map is Frame_Info_Maps.Map;
subtype Frame_Info_Cursor is Frame_Info_Maps.Cursor;
package Region_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Info);
subtype Region_Info_Map is Region_Info_Maps.Map;
subtype Region_Info_Cursor is Region_Info_Maps.Cursor;
end MAT.Memory;
|
-----------------------------------------------------------------------
-- Memory - Memory slot
-- Copyright (C) 2014, 2015, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded;
with ELF;
with MAT.Types;
with MAT.Frames;
with MAT.Events;
package MAT.Memory is
type Allocation is record
Size : MAT.Types.Target_Size;
Frame : Frames.Frame_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Event : MAT.Events.Event_Id_Type;
end record;
-- Statistics about memory allocation.
type Memory_Info is record
Total_Size : MAT.Types.Target_Size := 0;
Alloc_Count : Natural := 0;
Min_Slot_Size : MAT.Types.Target_Size := 0;
Max_Slot_Size : MAT.Types.Target_Size := 0;
Min_Addr : MAT.Types.Target_Addr := 0;
Max_Addr : MAT.Types.Target_Addr := 0;
end record;
-- Description of a memory region.
type Region_Info is record
Start_Addr : MAT.Types.Target_Addr := 0;
End_Addr : MAT.Types.Target_Addr := 0;
Size : MAT.Types.Target_Size := 0;
Flags : ELF.Elf32_Word := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
end record;
use type MAT.Types.Target_Addr;
package Allocation_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Allocation);
subtype Allocation_Map is Allocation_Maps.Map;
subtype Allocation_Cursor is Allocation_Maps.Cursor;
-- Define a map of <tt>Memory_Info</tt> keyed by the thread Id.
-- Such map allows to give the list of threads and a summary of their allocation.
use type MAT.Types.Target_Thread_Ref;
package Memory_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref,
Element_Type => Memory_Info);
subtype Memory_Info_Map is Memory_Info_Maps.Map;
subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor;
type Frame_Info is record
Thread : MAT.Types.Target_Thread_Ref;
Memory : Memory_Info;
end record;
-- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address
-- that performed the memory allocation directly or indirectly.
package Frame_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Frame_Info);
subtype Frame_Info_Map is Frame_Info_Maps.Map;
subtype Frame_Info_Cursor is Frame_Info_Maps.Cursor;
package Region_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Info);
subtype Region_Info_Map is Region_Info_Maps.Map;
subtype Region_Info_Cursor is Region_Info_Maps.Cursor;
end MAT.Memory;
|
Fix compilation warning with GNAT 2018
|
Fix compilation warning with GNAT 2018
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
4f6e39bc87381d5cd062f5fc711386f0a5d729a1
|
matp/src/events/mat-events-probes.ads
|
matp/src/events/mat-events-probes.ads
|
-----------------------------------------------------------------------
-- mat-events-probes -- Event probes
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Finalization;
with MAT.Types;
with MAT.Events;
with MAT.Events.Targets;
with MAT.Readers;
with MAT.Frames;
package MAT.Events.Probes is
-----------------
-- Abstract probe definition
-----------------
type Probe_Type is abstract tagged limited private;
type Probe_Type_Access is access all Probe_Type'Class;
-- Extract the probe information from the message.
procedure Extract (Probe : in Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out Target_Event_Type) is abstract;
procedure Execute (Probe : in Probe_Type;
Event : in out Target_Event_Type) is abstract;
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
procedure Update_Event (Probe : in Probe_Type;
Id : in MAT.Events.Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in MAT.Events.Event_Id_Type);
-----------------
-- Probe Manager
-----------------
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private;
type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class;
-- Initialize the probe manager instance.
overriding
procedure Initialize (Manager : in out Probe_Manager_Type);
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Read a list of event definitions from the stream and configure the reader.
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Get the target events.
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access;
-- Read a message from the stream.
procedure Read_Message (Reader : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is abstract;
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;
Manager : in out Probe_Manager_Type'Class) is abstract;
private
type Probe_Type is abstract tagged limited record
Owner : Probe_Manager_Type_Access := null;
end record;
-- Record a probe
type Probe_Handler is record
Probe : Probe_Type_Access;
Id : MAT.Events.Probe_Index_Type;
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;
package Probe_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Probe_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 => Probe_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record
Probes : Probe_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;
Event : Target_Event_Type;
Frames : MAT.Frames.Frame_Type;
end record;
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message);
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-events-probes -- Event probes
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Finalization;
with MAT.Types;
with MAT.Events;
with MAT.Events.Targets;
with MAT.Readers;
with MAT.Frames;
package MAT.Events.Probes is
-----------------
-- Abstract probe definition
-----------------
type Probe_Type is abstract tagged limited private;
type Probe_Type_Access is access all Probe_Type'Class;
-- Extract the probe information from the message.
procedure Extract (Probe : in Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out Target_Event_Type) is abstract;
procedure Execute (Probe : in Probe_Type;
Event : in out Target_Event_Type) is abstract;
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
procedure Update_Event (Probe : in Probe_Type;
Id : in MAT.Events.Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in MAT.Events.Event_Id_Type);
-----------------
-- Probe Manager
-----------------
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private;
type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class;
-- Initialize the probe manager instance.
overriding
procedure Initialize (Manager : in out Probe_Manager_Type);
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Read a list of event definitions from the stream and configure the reader.
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Get the target events.
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access;
-- Read a message from the stream.
procedure Read_Message (Reader : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is abstract;
-- Get the size of a target address (4 or 8 bytes).
function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Types.Target_Size;
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;
Manager : in out Probe_Manager_Type'Class) is abstract;
private
type Probe_Type is abstract tagged limited record
Owner : Probe_Manager_Type_Access := null;
end record;
-- Record a probe
type Probe_Handler is record
Probe : Probe_Type_Access;
Id : MAT.Events.Probe_Index_Type;
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;
package Probe_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Probe_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 => Probe_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record
Probes : Probe_Maps.Map;
Handlers : Handler_Maps.Map;
Version : MAT.Types.Uint16;
Flags : MAT.Types.Uint16;
Addr_Size : MAT.Types.Target_Size;
Probe : MAT.Events.Attribute_Table_Ptr;
Frame : access MAT.Events.Frame_Info;
Events : MAT.Events.Targets.Target_Events_Access;
Event : Target_Event_Type;
Frames : MAT.Frames.Frame_Type;
end record;
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message);
end MAT.Events.Probes;
|
Declare the Get_Address_Size function and record the target address size
|
Declare the Get_Address_Size function and record the target address size
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
158299074f9fee83740121b7661e31d5e2ea189b
|
src/asf-components-utils-escapes.adb
|
src/asf-components-utils-escapes.adb
|
-----------------------------------------------------------------------
-- components-utils-escape -- Escape generated content produced by component children
-- Copyright (C) 2011, 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 Util.Strings.Transforms;
package body ASF.Components.Utils.Escapes is
-- ------------------------------
-- Write the content that was collected by rendering the inner children.
-- Escape the content using Javascript escape rules.
-- ------------------------------
procedure Write_Content (UI : in UIEscape;
Writer : in out Contexts.Writer.Response_Writer'Class;
Content : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (UI, Context);
Result : Ada.Strings.Unbounded.Unbounded_String;
Mode : constant String := UI.Get_Attribute (ESCAPE_MODE_NAME, Context);
begin
if Mode = "xml" then
Util.Strings.Transforms.Escape_Xml (Content => Content,
Into => Result);
else
Util.Strings.Transforms.Escape_Java (Content => Content,
Into => Result);
end if;
Writer.Write (Result);
end Write_Content;
-- ------------------------------
-- Encode the children components in the javascript queue.
-- ------------------------------
overriding
procedure Encode_Children (UI : in UIEscape;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
procedure Process (Content : in String);
procedure Process (Content : in String) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
UIEscape'Class (UI).Write_Content (Writer.all, Content, Context);
end Process;
begin
UI.Wrap_Encode_Children (Context, Process'Access);
end Encode_Children;
end ASF.Components.Utils.Escapes;
|
-----------------------------------------------------------------------
-- components-utils-escape -- Escape generated content produced by component children
-- Copyright (C) 2011, 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 Util.Strings.Transforms;
package body ASF.Components.Utils.Escapes is
-- ------------------------------
-- Write the content that was collected by rendering the inner children.
-- Escape the content using Javascript escape rules.
-- ------------------------------
procedure Write_Content (UI : in UIEscape;
Writer : in out Contexts.Writer.Response_Writer'Class;
Content : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Result : Ada.Strings.Unbounded.Unbounded_String;
Mode : constant String := UI.Get_Attribute (ESCAPE_MODE_NAME, Context);
begin
if Mode = "xml" then
Util.Strings.Transforms.Escape_Xml (Content => Content,
Into => Result);
else
Util.Strings.Transforms.Escape_Java (Content => Content,
Into => Result);
end if;
Writer.Write (Result);
end Write_Content;
-- ------------------------------
-- Encode the children components in the javascript queue.
-- ------------------------------
overriding
procedure Encode_Children (UI : in UIEscape;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
procedure Process (Content : in String);
procedure Process (Content : in String) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
begin
UIEscape'Class (UI).Write_Content (Writer.all, Content, Context);
end Process;
begin
UI.Wrap_Encode_Children (Context, Process'Access);
end Encode_Children;
end ASF.Components.Utils.Escapes;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
eed97fdb2b440223033155e4d5182dbbe816dc75
|
arch/ARM/Nordic/drivers/nrf51-twi.adb
|
arch/ARM/Nordic/drivers/nrf51-twi.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with NRF51_SVD.TWI; use NRF51_SVD.TWI;
package body nRF51.TWI is
------------
-- Enable --
------------
procedure Enable (This : in out TWI_Master) is
begin
This.Periph.ENABLE.ENABLE := Enabled;
end Enable;
-------------
-- Disable --
-------------
procedure Disable (This : in out TWI_Master) is
begin
This.Periph.ENABLE.ENABLE := Disabled;
end Disable;
-------------
-- Enabled --
-------------
function Enabled (This : TWI_Master) return Boolean is
begin
return This.Periph.ENABLE.ENABLE = Enabled;
end Enabled;
---------------
-- Configure --
---------------
procedure Configure
(This : in out TWI_Master;
SCL, SDA : GPIO_Pin_Index;
Speed : TWI_Speed)
is
begin
This.Periph.PSELSCL := UInt32 (SCL);
This.Periph.PSELSDA := UInt32 (SDA);
This.Periph.FREQUENCY := (case Speed is
when TWI_100kbps => 16#0198_0000#,
when TWI_250kbps => 16#0400_0000#,
when TWI_400kbps => 16#0668_0000#);
end Configure;
----------------
-- Disconnect --
----------------
procedure Disconnect (This : in out TWI_Master) is
begin
This.Periph.PSELSCL := 16#FFFF_FFFF#;
This.Periph.PSELSDA := 16#FFFF_FFFF#;
end Disconnect;
---------------------
-- Master_Transmit --
---------------------
overriding procedure Master_Transmit
(This : in out TWI_Master;
Addr : I2C_Address;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
pragma Unreferenced (Timeout);
Index : Integer := Data'First + 1;
begin
if Data'Length = 0 then
Status := Ok;
return;
end if;
-- Clear errors
This.Periph.ERRORSRC.OVERRUN := Errorsrc_Overrun_Field_Reset;
This.Periph.ERRORSRC.ANACK := Errorsrc_Anack_Field_Reset;
This.Periph.ERRORSRC.DNACK := Errorsrc_Dnack_Field_Reset;
-- Set Address
This.Periph.ADDRESS.ADDRESS := UInt7 (Addr);
-- Prepare first byte
This.Periph.TXD.TXD := Data (Data'First);
-- Start TX sequence
This.Periph.TASKS_STARTTX := 1;
loop
loop
if This.Periph.EVENTS_ERROR /= 0 then
Status := Err_Error;
-- Clear the error
This.Periph.EVENTS_ERROR := 0;
-- Stop sequence
This.Periph.TASKS_STOP := 1;
return;
end if;
exit when This.Periph.EVENTS_TXDSENT /= 0;
end loop;
-- Clear the event
This.Periph.EVENTS_TXDSENT := 0;
exit when Index > Data'Last;
This.Periph.TXD.TXD := Data (Index);
Index := Index + 1;
end loop;
if This.Do_Stop_Sequence then
-- Stop sequence
This.Periph.EVENTS_STOPPED := 0;
This.Periph.TASKS_STOP := 1;
while This.Periph.EVENTS_STOPPED = 0 loop
null;
end loop;
end if;
Status := Ok;
end Master_Transmit;
--------------------
-- Master_Receive --
--------------------
overriding procedure Master_Receive
(This : in out TWI_Master;
Addr : I2C_Address;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
pragma Unreferenced (Timeout);
begin
if Data'Length = 0 then
Status := Ok;
return;
end if;
-- Clear errors
This.Periph.ERRORSRC.OVERRUN := Clear;
This.Periph.ERRORSRC.ANACK := Clear;
This.Periph.ERRORSRC.DNACK := Clear;
-- Set Address
This.Periph.ADDRESS.ADDRESS := UInt7 (Addr);
-- Start RX sequence
This.Periph.TASKS_STARTRX := 1;
for Elt of Data loop
loop
if This.Periph.EVENTS_ERROR /= 0 then
Status := Err_Error;
-- Clear the error
This.Periph.EVENTS_ERROR := 0;
-- Stop sequence
This.Periph.TASKS_STOP := 1;
return;
end if;
exit when This.Periph.EVENTS_RXDREADY /= 0;
end loop;
-- Clear the event
This.Periph.EVENTS_RXDREADY := 0;
Elt := This.Periph.RXD.RXD;
end loop;
if This.Do_Stop_Sequence then
-- Stop sequence
This.Periph.EVENTS_STOPPED := 0;
This.Periph.TASKS_STOP := 1;
while This.Periph.EVENTS_STOPPED = 0 loop
null;
end loop;
end if;
Status := Ok;
end Master_Receive;
---------------
-- Mem_Write --
---------------
overriding procedure Mem_Write
(This : in out TWI_Master;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
begin
This.Do_Stop_Sequence := False;
case Mem_Addr_Size is
when Memory_Size_8b =>
This.Master_Transmit (Addr => Addr,
Data => (0 => UInt8 (Mem_Addr)),
Status => Status,
Timeout => Timeout);
when Memory_Size_16b =>
This.Master_Transmit (Addr => Addr,
Data => (UInt8 (Shift_Right (Mem_Addr, 8)),
UInt8 (Mem_Addr and 16#FF#)),
Status => Status,
Timeout => Timeout);
end case;
This.Do_Stop_Sequence := True;
if Status /= Ok then
return;
end if;
This.Master_Transmit (Addr => Addr,
Data => Data,
Status => Status,
Timeout => Timeout);
end Mem_Write;
--------------
-- Mem_Read --
--------------
overriding procedure Mem_Read
(This : in out TWI_Master;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
begin
This.Do_Stop_Sequence := False;
case Mem_Addr_Size is
when Memory_Size_8b =>
This.Master_Transmit (Addr => Addr,
Data => (0 => UInt8 (Mem_Addr)),
Status => Status,
Timeout => Timeout);
when Memory_Size_16b =>
This.Master_Transmit (Addr => Addr,
Data => (UInt8 (Shift_Right (Mem_Addr, 8)),
UInt8 (Mem_Addr and 16#FF#)),
Status => Status,
Timeout => Timeout);
end case;
This.Do_Stop_Sequence := True;
if Status /= Ok then
return;
end if;
This.Master_Receive (Addr => Addr,
Data => Data,
Status => Status,
Timeout => Timeout);
end Mem_Read;
end nRF51.TWI;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with NRF51_SVD.TWI; use NRF51_SVD.TWI;
package body nRF51.TWI is
procedure Stop_Sequence (This : in out TWI_Master'Class);
-------------------
-- Stop_Sequence --
-------------------
procedure Stop_Sequence (This : in out TWI_Master'Class) is
begin
-- Stop sequence
This.Periph.EVENTS_STOPPED := 0;
This.Periph.TASKS_STOP := 1;
while This.Periph.EVENTS_STOPPED = 0 loop
null;
end loop;
end Stop_Sequence;
------------
-- Enable --
------------
procedure Enable (This : in out TWI_Master) is
begin
This.Periph.ENABLE.ENABLE := Enabled;
end Enable;
-------------
-- Disable --
-------------
procedure Disable (This : in out TWI_Master) is
begin
This.Periph.ENABLE.ENABLE := Disabled;
end Disable;
-------------
-- Enabled --
-------------
function Enabled (This : TWI_Master) return Boolean is
begin
return This.Periph.ENABLE.ENABLE = Enabled;
end Enabled;
---------------
-- Configure --
---------------
procedure Configure
(This : in out TWI_Master;
SCL, SDA : GPIO_Pin_Index;
Speed : TWI_Speed)
is
begin
This.Periph.PSELSCL := UInt32 (SCL);
This.Periph.PSELSDA := UInt32 (SDA);
This.Periph.FREQUENCY := (case Speed is
when TWI_100kbps => 16#0198_0000#,
when TWI_250kbps => 16#0400_0000#,
when TWI_400kbps => 16#0668_0000#);
end Configure;
----------------
-- Disconnect --
----------------
procedure Disconnect (This : in out TWI_Master) is
begin
This.Periph.PSELSCL := 16#FFFF_FFFF#;
This.Periph.PSELSDA := 16#FFFF_FFFF#;
end Disconnect;
---------------------
-- Master_Transmit --
---------------------
overriding procedure Master_Transmit
(This : in out TWI_Master;
Addr : I2C_Address;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
pragma Unreferenced (Timeout);
Index : Integer := Data'First + 1;
begin
if Data'Length = 0 then
Status := Ok;
return;
end if;
-- Clear errors
This.Periph.ERRORSRC.OVERRUN := Errorsrc_Overrun_Field_Reset;
This.Periph.ERRORSRC.ANACK := Errorsrc_Anack_Field_Reset;
This.Periph.ERRORSRC.DNACK := Errorsrc_Dnack_Field_Reset;
-- Set Address
This.Periph.ADDRESS.ADDRESS := UInt7 (Addr);
-- Prepare first byte
This.Periph.TXD.TXD := Data (Data'First);
-- Start TX sequence
This.Periph.TASKS_STARTTX := 1;
loop
loop
if This.Periph.EVENTS_ERROR /= 0 then
Status := Err_Error;
-- Clear the error
This.Periph.EVENTS_ERROR := 0;
-- Stop sequence
This.Periph.TASKS_STOP := 1;
return;
end if;
exit when This.Periph.EVENTS_TXDSENT /= 0;
end loop;
-- Clear the event
This.Periph.EVENTS_TXDSENT := 0;
exit when Index > Data'Last;
This.Periph.TXD.TXD := Data (Index);
Index := Index + 1;
end loop;
if This.Do_Stop_Sequence then
Stop_Sequence (This);
end if;
Status := Ok;
end Master_Transmit;
--------------------
-- Master_Receive --
--------------------
overriding procedure Master_Receive
(This : in out TWI_Master;
Addr : I2C_Address;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
pragma Unreferenced (Timeout);
begin
if Data'Length = 0 then
Status := Ok;
return;
end if;
-- Clear errors
This.Periph.ERRORSRC.OVERRUN := Clear;
This.Periph.ERRORSRC.ANACK := Clear;
This.Periph.ERRORSRC.DNACK := Clear;
-- Set Address
This.Periph.ADDRESS.ADDRESS := UInt7 (Addr);
-- Configure SHORTS to automatically suspend TWI port when receiving a
-- byte.
This.Periph.SHORTS.BB_SUSPEND := Enabled;
This.Periph.SHORTS.BB_STOP := Disabled;
-- Start RX sequence
This.Periph.TASKS_STARTRX := 1;
for Index in Data'Range loop
loop
if This.Periph.EVENTS_ERROR /= 0 then
Status := Err_Error;
-- Clear the error
This.Periph.EVENTS_ERROR := 0;
Stop_Sequence (This);
return;
end if;
exit when This.Periph.EVENTS_RXDREADY /= 0;
end loop;
if Index = Data'Last and then This.Do_Stop_Sequence then
-- Configure SHORTS to automatically stop the TWI port and produce
-- a STOP event on the bus when receiving a byte.
This.Periph.SHORTS.BB_SUSPEND := Disabled;
This.Periph.SHORTS.BB_STOP := Enabled;
end if;
-- Clear the event
This.Periph.EVENTS_RXDREADY := 0;
Data (Index) := This.Periph.RXD.RXD;
end loop;
Status := Ok;
end Master_Receive;
---------------
-- Mem_Write --
---------------
overriding procedure Mem_Write
(This : in out TWI_Master;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
begin
This.Do_Stop_Sequence := False;
case Mem_Addr_Size is
when Memory_Size_8b =>
This.Master_Transmit (Addr => Addr,
Data => (0 => UInt8 (Mem_Addr)),
Status => Status,
Timeout => Timeout);
when Memory_Size_16b =>
This.Master_Transmit (Addr => Addr,
Data => (UInt8 (Shift_Right (Mem_Addr, 8)),
UInt8 (Mem_Addr and 16#FF#)),
Status => Status,
Timeout => Timeout);
end case;
This.Do_Stop_Sequence := True;
if Status /= Ok then
return;
end if;
This.Master_Transmit (Addr => Addr,
Data => Data,
Status => Status,
Timeout => Timeout);
end Mem_Write;
--------------
-- Mem_Read --
--------------
overriding procedure Mem_Read
(This : in out TWI_Master;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
begin
This.Do_Stop_Sequence := False;
case Mem_Addr_Size is
when Memory_Size_8b =>
This.Master_Transmit (Addr => Addr,
Data => (0 => UInt8 (Mem_Addr)),
Status => Status,
Timeout => Timeout);
when Memory_Size_16b =>
This.Master_Transmit (Addr => Addr,
Data => (UInt8 (Shift_Right (Mem_Addr, 8)),
UInt8 (Mem_Addr and 16#FF#)),
Status => Status,
Timeout => Timeout);
end case;
This.Do_Stop_Sequence := True;
if Status /= Ok then
return;
end if;
This.Master_Receive (Addr => Addr,
Data => Data,
Status => Status,
Timeout => Timeout);
end Mem_Read;
end nRF51.TWI;
|
Fix Master_Receive
|
nRF51.TWI: Fix Master_Receive
The stop sequence was generated one byte too late.
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
|
9f495ae3b2648a42df6f12f3a3f8e0a33984d052
|
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);
Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema",
Test_Load_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table",
Test_Table_Iterator'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)",
Test_Empty_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;
declare
C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist");
begin
T.Assert (C = null, "Find_Column must return null for an unknown column");
end;
end Test_Load_Schema;
-- ------------------------------
-- Test the Table_Cursor operations and check the result schema.
-- ------------------------------
procedure Test_Table_Iterator (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
Driver : constant String := S.Get_Connection.Get_Driver.Get_Driver_Name;
begin
S.Load_Schema (Schema);
declare
Iter : Table_Cursor := Schema.Get_Tables;
Count : Natural := 0;
begin
T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator");
while Has_Element (Iter) loop
Table := Element (Iter);
T.Assert (Table /= null, "Element function must not return null");
declare
Col_Iter : Column_Cursor := Get_Columns (Table);
begin
-- T.Assert (Has_Element (Col_Iter), "Table has a column");
while Has_Element (Col_Iter) loop
T.Assert (Element (Col_Iter) /= null, "Element function must not return null");
Next (Col_Iter);
end loop;
end;
Count := Count + 1;
Next (Iter);
end loop;
if Driver = "sqlite" then
Util.Tests.Assert_Equals (T, 15, Count,
"Invalid number of tables found in the schema");
elsif Driver = "mysql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
end if;
end;
end Test_Table_Iterator;
-- ------------------------------
-- Test the Table_Cursor operations on an empty schema.
-- ------------------------------
procedure Test_Empty_Schema (T : in out Test) is
Schema : Schema_Definition;
Iter : constant Table_Cursor := Schema.Get_Tables;
begin
T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator");
T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null");
end Test_Empty_Schema;
end ADO.Schemas.Tests;
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- 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 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);
Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema",
Test_Load_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table",
Test_Table_Iterator'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)",
Test_Empty_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;
declare
C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist");
begin
T.Assert (C = null, "Find_Column must return null for an unknown column");
end;
end Test_Load_Schema;
-- ------------------------------
-- Test the Table_Cursor operations and check the result schema.
-- ------------------------------
procedure Test_Table_Iterator (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
Driver : constant String := S.Get_Driver.Get_Driver_Name;
begin
S.Load_Schema (Schema);
declare
Iter : Table_Cursor := Schema.Get_Tables;
Count : Natural := 0;
begin
T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator");
while Has_Element (Iter) loop
Table := Element (Iter);
T.Assert (Table /= null, "Element function must not return null");
declare
Col_Iter : Column_Cursor := Get_Columns (Table);
begin
-- T.Assert (Has_Element (Col_Iter), "Table has a column");
while Has_Element (Col_Iter) loop
T.Assert (Element (Col_Iter) /= null, "Element function must not return null");
Next (Col_Iter);
end loop;
end;
Count := Count + 1;
Next (Iter);
end loop;
if Driver = "sqlite" then
Util.Tests.Assert_Equals (T, 15, Count,
"Invalid number of tables found in the schema");
elsif Driver = "mysql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
end if;
end;
end Test_Table_Iterator;
-- ------------------------------
-- Test the Table_Cursor operations on an empty schema.
-- ------------------------------
procedure Test_Empty_Schema (T : in out Test) is
Schema : Schema_Definition;
Iter : constant Table_Cursor := Schema.Get_Tables;
begin
T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator");
T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null");
end Test_Empty_Schema;
end ADO.Schemas.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
c903831b8f3b68a1ecef60a52d6b28095538efed
|
src/util-streams-texts.ads
|
src/util-streams-texts.ads
|
-----------------------------------------------------------------------
-- util-streams-texts -- Text stream utilities
-- Copyright (C) 2010, 2011, 2012, 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.Strings.Wide_Wide_Unbounded;
with Util.Streams.Buffered;
with Util.Texts.Transforms;
with Ada.Characters.Handling;
with Ada.Wide_Wide_Characters.Handling;
with Ada.Calendar;
with GNAT.Calendar.Time_IO;
package Util.Streams.Texts is
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is new Buffered.Buffered_Stream with private;
type Print_Stream_Access is access all Print_Stream'Class;
procedure Initialize (Stream : in out Print_Stream;
To : in Output_Stream_Access);
-- Write a raw character on the stream.
procedure Write (Stream : in out Print_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Print_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer);
-- Write a string on the stream.
-- procedure Write (Stream : in out Print_Stream;
-- Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a date on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date);
-- Get the output stream content as a string.
function To_String (Stream : in Buffered.Buffered_Stream'Class) return String;
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Character);
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Wide_Wide_Character);
-- -----------------------
-- Reader stream
-- -----------------------
-- The <b>Reader_Stream</b> is an input stream which provides helper methods
-- for reading text streams.
type Reader_Stream is new Buffered.Buffered_Stream with private;
type Reader_Stream_Access is access all Reader_Stream'Class;
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
procedure Initialize (Stream : in out Reader_Stream;
From : in Input_Stream_Access);
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False);
private
type Print_Stream is new Buffered.Buffered_Stream with null record;
type Reader_Stream is new Buffered.Buffered_Stream with null record;
end Util.Streams.Texts;
|
-----------------------------------------------------------------------
-- util-streams-texts -- Text stream utilities
-- Copyright (C) 2010, 2011, 2012, 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.Strings.Wide_Wide_Unbounded;
with Util.Streams.Buffered;
with Ada.Calendar;
with GNAT.Calendar.Time_IO;
package Util.Streams.Texts is
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is new Buffered.Output_Buffer_Stream with private;
type Print_Stream_Access is access all Print_Stream'Class;
procedure Initialize (Stream : in out Print_Stream;
To : in Output_Stream_Access);
-- Write a raw character on the stream.
procedure Write (Stream : in out Print_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Print_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer);
-- Write a string on the stream.
-- procedure Write (Stream : in out Print_Stream;
-- Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a date on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date);
-- Get the output stream content as a string.
function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String;
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Character);
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Wide_Wide_Character);
-- -----------------------
-- Reader stream
-- -----------------------
-- The <b>Reader_Stream</b> is an input stream which provides helper methods
-- for reading text streams.
type Reader_Stream is new Buffered.Input_Buffer_Stream with private;
type Reader_Stream_Access is access all Reader_Stream'Class;
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
procedure Initialize (Stream : in out Reader_Stream;
From : in Input_Stream_Access);
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False);
private
type Print_Stream is new Buffered.Output_Buffer_Stream with null record;
type Reader_Stream is new Buffered.Input_Buffer_Stream with null record;
end Util.Streams.Texts;
|
Refactor the Buffered_Stream - use Output_Buffer_Stream for the Print_Stream - use Input_Buffer_Stream for the Reader_Stream
|
Refactor the Buffered_Stream
- use Output_Buffer_Stream for the Print_Stream
- use Input_Buffer_Stream for the Reader_Stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e545efd3c9b47e6dcfcb87c49d948463b76d0a91
|
src/util-files.adb
|
src/util-files.adb
|
-----------------------------------------------------------------------
-- util-files -- Various File Utility Packages
-- Copyright (C) 2001, 2002, 2003, 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.Directories;
with Ada.Strings.Fixed;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
with Util.Strings.Tokenizers;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and append each line to
-- the <b>Into</b> vector.
-- ------------------------------
procedure Read_File (Path : in String;
Into : in out Util.Strings.Vectors.Vector) is
procedure Append (Line : in String);
procedure Append (Line : in String) is
begin
Into.Append (Line);
end Append;
begin
Read_File (Path, Append'Access);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
begin
Util.Strings.Tokenizers.Iterate_Tokens (Content => Path,
Pattern => ";",
Process => Process,
Going => Going);
end Iterate_Path;
-- ------------------------------
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : String;
Paths : String) return String is
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Index (Paths, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
use Ada.Directories;
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String) return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Unbounded_String;
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Length (Result) > 0 then
Append (Result, ';');
end if;
Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return To_String (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 then
return Name;
elsif Directory = "." or else Directory = "./" then
if Name (Name'First) = '/' then
return Compose (Directory, Name (Name'First + 1 .. Name'Last));
else
return Name;
end if;
elsif Directory (Directory'Last) = '/' and then Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or else Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\'))
then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
end Util.Files;
|
-----------------------------------------------------------------------
-- util-files -- Various File Utility Packages
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with Ada.Directories;
with Ada.IO_Exceptions;
with Ada.Strings.Fixed;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
with Util.Strings.Tokenizers;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and append each line to
-- the <b>Into</b> vector.
-- ------------------------------
procedure Read_File (Path : in String;
Into : in out Util.Strings.Vectors.Vector) is
procedure Append (Line : in String);
procedure Append (Line : in String) is
begin
Into.Append (Line);
end Append;
begin
Read_File (Path, Append'Access);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
begin
Util.Strings.Tokenizers.Iterate_Tokens (Content => Path,
Pattern => ";",
Process => Process,
Going => Going);
end Iterate_Path;
-- ------------------------------
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : String;
Paths : String) return String is
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Index (Paths, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
use Ada.Directories;
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String) return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Unbounded_String;
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Length (Result) > 0 then
Append (Result, ';');
end if;
Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return To_String (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 then
return Name;
elsif Directory = "." or else Directory = "./" then
if Name (Name'First) = '/' then
return Compose (Directory, Name (Name'First + 1 .. Name'Last));
else
return Name;
end if;
elsif Directory (Directory'Last) = '/' and then Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or else Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\'))
then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
-- ------------------------------
-- Rename the old name into a new name.
-- ------------------------------
procedure Rename (Old_Name, New_Name : in String) is
-- Rename a file (the Ada.Directories.Rename does not allow to use the
-- Unix atomic file rename!)
function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr;
Newpath : in Interfaces.C.Strings.chars_ptr) return Integer;
pragma Import (C, Sys_Rename, "rename");
Old_Path : Interfaces.C.Strings.chars_ptr;
New_Path : Interfaces.C.Strings.chars_ptr;
Result : Integer;
begin
-- Do a system atomic rename of old file in the new file.
-- Ada.Directories.Rename does not allow this.
Old_Path := Interfaces.C.Strings.New_String (Old_Name);
New_Path := Interfaces.C.Strings.New_String (New_Name);
Result := Sys_Rename (Old_Path, New_Path);
Interfaces.C.Strings.Free (Old_Path);
Interfaces.C.Strings.Free (New_Path);
if Result /= 0 then
raise Ada.IO_Exceptions.Use_Error with "Cannot rename file";
end if;
end Rename;
end Util.Files;
|
Implement the Rename procedure using rename(2) (taken from the Save_Properties procedure)
|
Implement the Rename procedure using rename(2) (taken from the Save_Properties procedure)
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
24305394500295c9b7819d681212ab4b011941ff
|
src/asf-server.adb
|
src/asf-server.adb
|
-----------------------------------------------------------------------
-- asf.server -- ASF Server
-- Copyright (C) 2009, 2010, 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 Util.Strings;
with Ada.Unchecked_Deallocation;
with Ada.Task_Attributes;
package body ASF.Server is
Null_Context : constant Request_Context := Request_Context'(null, null, null);
package Task_Context is new Ada.Task_Attributes
(Request_Context, Null_Context);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Binding_Array,
Name => Binding_Array_Access);
-- ------------------------------
-- Get the current registry associated with the current request being processed
-- by the current thread. Returns null if there is no current request.
-- ------------------------------
function Current return ASF.Servlets.Servlet_Registry_Access is
begin
return Task_Context.Value.Application;
end Current;
-- ------------------------------
-- Set the current registry. This is called by <b>Service</b> once the
-- registry is identified from the URI.
-- ------------------------------
procedure Set_Context (Context : in Request_Context) is
begin
Task_Context.Set_Value (Context);
end Set_Context;
-- ------------------------------
-- Give access to the current request and response object to the <b>Process</b>
-- procedure. If there is no current request for the thread, do nothing.
-- ------------------------------
procedure Update_Context (Process : not null access
procedure (Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class)) is
Ctx : constant Request_Context := Task_Context.Value;
begin
Process (Ctx.Request.all, Ctx.Response.all);
end Update_Context;
-- ------------------------------
-- Register the application to serve requests
-- ------------------------------
procedure Register_Application (Server : in out Container;
URI : in String;
Context : in ASF.Servlets.Servlet_Registry_Access) is
Count : constant Natural := Server.Nb_Bindings;
Apps : constant Binding_Array_Access := new Binding_Array (1 .. Count + 1);
Old : Binding_Array_Access := Server.Applications;
begin
if Old /= null then
Apps (1 .. Count) := Server.Applications (1 .. Count);
end if;
Apps (Count + 1).Context := Context;
Apps (Count + 1).Base_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
-- Inform the servlet registry about the base URI.
Context.Register_Application (URI);
-- Start the application if the container is started.
if Server.Is_Started then
Context.Start;
end if;
-- Update the binding.
Server.Applications := Apps;
Server.Nb_Bindings := Count + 1;
if Old /= null then
Free (Old);
end if;
end Register_Application;
-- ------------------------------
-- Remove the application
-- ------------------------------
procedure Remove_Application (Server : in out Container;
Context : in ASF.Servlets.Servlet_Registry_Access) is
use type ASF.Servlets.Servlet_Registry_Access;
Count : constant Natural := Server.Nb_Bindings;
Apps : constant Binding_Array_Access := Server.Applications;
begin
for I in 1 .. Count loop
if Apps (I).Context = Context then
Server.Nb_Bindings := Count - 1;
if I < Count then
Apps (I) := Apps (Count);
end if;
return;
end if;
end loop;
end Remove_Application;
-- ------------------------------
-- Start the applications that have been registered.
-- ------------------------------
procedure Start (Server : in out Container) is
begin
if not Server.Is_Started then
Server.Is_Started := True;
if Server.Applications /= null then
for I in Server.Applications'Range loop
Server.Applications (I).Context.Start;
end loop;
end if;
end if;
end Start;
-- ------------------------------
-- Receives standard HTTP requests from the public service method and dispatches
-- them to the Do_XXX methods defined in this class. This method is an HTTP-specific
-- version of the Servlet.service(Request, Response) method. There's no need
-- to override this method.
-- ------------------------------
procedure Service (Server : in Container;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use Servlets;
use Util.Strings;
use type Ada.Strings.Unbounded.Unbounded_String;
URI : constant String := Request.Get_Request_URI;
Slash_Pos : constant Natural := Index (URI, '/', URI'First + 1);
Apps : constant Binding_Array_Access := Server.Applications;
Prefix_End : Natural;
begin
if Apps = null then
Response.Set_Status (Responses.SC_NOT_FOUND);
Server.Default.Send_Error_Page (Request, Response);
return;
end if;
-- Find the module and action to invoke
if Slash_Pos > 1 then
Prefix_End := Slash_Pos - 1;
else
Prefix_End := URI'Last;
end if;
for I in Apps.all'Range loop
if Apps (I).Base_URI = URI (URI'First .. Prefix_End) then
declare
Req : Request_Context;
Context : constant Servlet_Registry_Access := Apps (I).Context;
Page : constant String := URI (Prefix_End + 1 .. URI'Last);
Dispatcher : constant Request_Dispatcher := Context.Get_Request_Dispatcher (Page);
begin
Req.Request := Request'Unchecked_Access;
Req.Response := Response'Unchecked_Access;
Req.Application := Context;
Set_Context (Req);
Forward (Dispatcher, Request, Response);
case Response.Get_Status / 100 is
when 2 | 3 =>
null;
when others =>
Context.Send_Error_Page (Request, Response);
end case;
Set_Context (Null_Context);
return;
exception
when E : others =>
Context.Error (Request, Response, E);
Set_Context (Null_Context);
return;
end;
end if;
end loop;
Response.Set_Status (Responses.SC_NOT_FOUND);
Server.Default.Send_Error_Page (Request, Response);
exception
when E : others =>
Server.Default.Error (Request, Response, E);
end Service;
-- ------------------------------
-- Release the storage.
-- ------------------------------
overriding
procedure Finalize (Server : in out Container) is
begin
Free (Server.Applications);
end Finalize;
end ASF.Server;
|
-----------------------------------------------------------------------
-- asf.server -- ASF Server
-- Copyright (C) 2009, 2010, 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 Util.Strings;
with Ada.Unchecked_Deallocation;
with Ada.Task_Attributes;
package body ASF.Server is
Null_Context : constant Request_Context := Request_Context'(null, null, null);
package Task_Context is new Ada.Task_Attributes
(Request_Context, Null_Context);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Binding_Array,
Name => Binding_Array_Access);
-- ------------------------------
-- Get the current registry associated with the current request being processed
-- by the current thread. Returns null if there is no current request.
-- ------------------------------
function Current return ASF.Servlets.Servlet_Registry_Access is
begin
return Task_Context.Value.Application;
end Current;
-- ------------------------------
-- Set the current registry. This is called by <b>Service</b> once the
-- registry is identified from the URI.
-- ------------------------------
procedure Set_Context (Context : in Request_Context) is
begin
Task_Context.Set_Value (Context);
end Set_Context;
-- ------------------------------
-- Give access to the current request and response object to the <b>Process</b>
-- procedure. If there is no current request for the thread, do nothing.
-- ------------------------------
procedure Update_Context (Process : not null access
procedure (Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class)) is
Ctx : constant Request_Context := Task_Context.Value;
begin
Process (Ctx.Request.all, Ctx.Response.all);
end Update_Context;
-- ------------------------------
-- Register the application to serve requests
-- ------------------------------
procedure Register_Application (Server : in out Container;
URI : in String;
Context : in ASF.Servlets.Servlet_Registry_Access) is
Count : constant Natural := Server.Nb_Bindings;
Apps : constant Binding_Array_Access := new Binding_Array (1 .. Count + 1);
Old : Binding_Array_Access := Server.Applications;
begin
if Old /= null then
Apps (1 .. Count) := Server.Applications (1 .. Count);
end if;
Apps (Count + 1).Context := Context;
Apps (Count + 1).Base_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
-- Inform the servlet registry about the base URI.
Context.Register_Application (URI);
-- Start the application if the container is started.
if Server.Is_Started then
Context.Start;
end if;
-- Update the binding.
Server.Applications := Apps;
Server.Nb_Bindings := Count + 1;
if Old /= null then
Free (Old);
end if;
end Register_Application;
-- ------------------------------
-- Remove the application
-- ------------------------------
procedure Remove_Application (Server : in out Container;
Context : in ASF.Servlets.Servlet_Registry_Access) is
use type ASF.Servlets.Servlet_Registry_Access;
Count : constant Natural := Server.Nb_Bindings;
Old : Binding_Array_Access := Server.Applications;
Apps : Binding_Array_Access;
begin
for I in 1 .. Count loop
if Old (I).Context = Context then
if I < Count then
Old (I) := Old (Count);
end if;
if Count > 1 then
Apps := new Binding_Array (1 .. Count - 1);
Apps.all := Old (1 .. Count - 1);
else
Apps := null;
end if;
Server.Applications := Apps;
Server.Nb_Bindings := Count - 1;
Free (Old);
return;
end if;
end loop;
end Remove_Application;
-- ------------------------------
-- Start the applications that have been registered.
-- ------------------------------
procedure Start (Server : in out Container) is
begin
if not Server.Is_Started then
Server.Is_Started := True;
if Server.Applications /= null then
for I in Server.Applications'Range loop
Server.Applications (I).Context.Start;
end loop;
end if;
end if;
end Start;
-- ------------------------------
-- Receives standard HTTP requests from the public service method and dispatches
-- them to the Do_XXX methods defined in this class. This method is an HTTP-specific
-- version of the Servlet.service(Request, Response) method. There's no need
-- to override this method.
-- ------------------------------
procedure Service (Server : in Container;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use Servlets;
use Util.Strings;
use type Ada.Strings.Unbounded.Unbounded_String;
URI : constant String := Request.Get_Request_URI;
Slash_Pos : constant Natural := Index (URI, '/', URI'First + 1);
Apps : constant Binding_Array_Access := Server.Applications;
Prefix_End : Natural;
begin
if Apps = null then
Response.Set_Status (Responses.SC_NOT_FOUND);
Server.Default.Send_Error_Page (Request, Response);
return;
end if;
-- Find the module and action to invoke
if Slash_Pos > 1 then
Prefix_End := Slash_Pos - 1;
else
Prefix_End := URI'Last;
end if;
for I in Apps.all'Range loop
if Apps (I).Base_URI = URI (URI'First .. Prefix_End) then
declare
Req : Request_Context;
Context : constant Servlet_Registry_Access := Apps (I).Context;
Page : constant String := URI (Prefix_End + 1 .. URI'Last);
Dispatcher : constant Request_Dispatcher := Context.Get_Request_Dispatcher (Page);
begin
Req.Request := Request'Unchecked_Access;
Req.Response := Response'Unchecked_Access;
Req.Application := Context;
Set_Context (Req);
Forward (Dispatcher, Request, Response);
case Response.Get_Status / 100 is
when 2 | 3 =>
null;
when others =>
Context.Send_Error_Page (Request, Response);
end case;
Set_Context (Null_Context);
return;
exception
when E : others =>
Context.Error (Request, Response, E);
Set_Context (Null_Context);
return;
end;
end if;
end loop;
Response.Set_Status (Responses.SC_NOT_FOUND);
Server.Default.Send_Error_Page (Request, Response);
exception
when E : others =>
Server.Default.Error (Request, Response, E);
end Service;
-- ------------------------------
-- Release the storage.
-- ------------------------------
overriding
procedure Finalize (Server : in out Container) is
begin
Free (Server.Applications);
end Finalize;
end ASF.Server;
|
Fix Remove_Application to avoid null entries in the binding array when an application is removed.
|
Fix Remove_Application to avoid null entries in the binding array when an application is removed.
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
2c43ddd696fa7ee7df1ce1a7c48caf107cbb77fa
|
src/asf-components-widgets-inputs.adb
|
src/asf-components-widgets-inputs.adb
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input widget components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Conversions;
with ASF.Models.Selects;
with ASF.Components.Base;
with ASF.Components.Utils;
with ASF.Components.Html.Messages;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Vectors;
with Util.Strings.Transforms;
with Util.Beans.Objects;
package body ASF.Components.Widgets.Inputs is
-- ------------------------------
-- Render the input field title.
-- ------------------------------
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class) is
Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title");
begin
Writer.Start_Element ("dt");
Writer.Start_Element ("label");
Writer.Write_Attribute ("for", Name);
Writer.Write_Text (Title);
Writer.End_Element ("label");
Writer.End_Element ("dt");
end Render_Title;
-- ------------------------------
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
Style : constant String := UI.Get_Attribute ("styleClass", Context);
begin
Writer.Start_Element ("dl");
Writer.Write_Attribute ("id", Id);
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Writer.Write_Attribute ("class", Style & " asf-error");
elsif Style'Length > 0 then
Writer.Write_Attribute ("class", Style);
end if;
UI.Render_Title (Id, Writer, Context);
Writer.Start_Element ("dd");
UI.Render_Input (Context, Write_Id => False);
end;
end Encode_Begin;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the error message associated with the input field.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN_NO_STYLE, False, True, Context);
end if;
Writer.End_Element ("dd");
Writer.End_Element ("dl");
end;
end Encode_End;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the autocomplete script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').complete({");
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Val : constant String := Context.Get_Parameter (Id & ".match");
begin
if Val'Length > 0 then
UI.Match_Value := Util.Beans.Objects.To_Object (Val);
else
ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context);
end if;
end;
end Process_Decodes;
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class) is
use type Util.Beans.Basic.List_Bean_Access;
List : constant Util.Beans.Basic.List_Bean_Access
:= ASF.Components.Utils.Get_List_Bean (UI, "autocompleteList", Context);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Need_Comma : Boolean := False;
Count : Natural;
procedure Render_Item (Label : in String) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if Match'Length = 0 or else
(Match'Length <= Label'Length
and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then
if Need_Comma then
Writer.Write (",");
end if;
Writer.Write ('"');
Util.Strings.Transforms.Escape_Java (Content => Label,
Into => Result);
Writer.Write (Result);
Writer.Write ('"');
Need_Comma := True;
end if;
end Render_Item;
begin
Writer.Write ('[');
if List /= null then
Count := List.Get_Count;
if List.all in ASF.Models.Selects.Select_Item_List'Class then
declare
S : constant access ASF.Models.Selects.Select_Item_List'Class
:= ASF.Models.Selects.Select_Item_List'Class (List.all)'Access;
begin
for I in 1 .. Count loop
Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label));
end loop;
end;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
declare
Value : constant Util.Beans.Objects.Object := List.Get_Row;
Label : constant String := Util.Beans.Objects.To_String (Value);
begin
Render_Item (Label);
end;
end loop;
end if;
end if;
Writer.Write (']');
end Render_List;
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then
declare
Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match");
ME : EL.Expressions.Method_Expression;
begin
if Value /= null then
declare
VE : constant EL.Expressions.Value_Expression
:= ASF.Views.Nodes.Get_Value_Expression (Value.all);
begin
VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all);
end;
end if;
-- Post an event on this component to trigger the rendering of the completion
-- list as part of an application/json output. The rendering is made by Broadcast.
ASF.Events.Faces.Actions.Post_Event (UI => UI,
Method => ME);
end;
else
ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context);
end if;
-- exception
-- when E : others =>
-- UI.Is_Valid := False;
-- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context);
-- Log.Info (Utils.Get_Line_Info (UI)
-- & ": Exception raised when updating value {0} for component {1}: {2}",
-- EL.Objects.To_String (UI.Submitted_Value),
-- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E));
end Process_Updates;
-- ------------------------------
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
-- ------------------------------
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Event);
Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value);
begin
Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8");
UI.Render_List (Match, Context);
Context.Response_Completed;
end Broadcast;
end ASF.Components.Widgets.Inputs;
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input widget components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Conversions;
with ASF.Models.Selects;
with ASF.Components.Utils;
with ASF.Components.Html.Messages;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Vectors;
with Util.Beans.Basic;
with Util.Strings.Transforms;
package body ASF.Components.Widgets.Inputs is
-- ------------------------------
-- Render the input field title.
-- ------------------------------
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class) is
Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title");
begin
Writer.Start_Element ("dt");
Writer.Start_Element ("label");
Writer.Write_Attribute ("for", Name);
Writer.Write_Text (Title);
Writer.End_Element ("label");
Writer.End_Element ("dt");
end Render_Title;
-- ------------------------------
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
Style : constant String := UI.Get_Attribute ("styleClass", Context);
begin
Writer.Start_Element ("dl");
Writer.Write_Attribute ("id", Id);
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Writer.Write_Attribute ("class", Style & " asf-error");
elsif Style'Length > 0 then
Writer.Write_Attribute ("class", Style);
end if;
UI.Render_Title (Id, Writer, Context);
Writer.Start_Element ("dd");
UI.Render_Input (Context, Write_Id => False);
end;
end Encode_Begin;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the error message associated with the input field.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN_NO_STYLE, False, True, Context);
end if;
Writer.End_Element ("dd");
Writer.End_Element ("dl");
end;
end Encode_End;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the autocomplete script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').complete({");
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Val : constant String := Context.Get_Parameter (Id & ".match");
begin
if Val'Length > 0 then
UI.Match_Value := Util.Beans.Objects.To_Object (Val);
else
ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context);
end if;
end;
end Process_Decodes;
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class) is
use type Util.Beans.Basic.List_Bean_Access;
procedure Render_Item (Label : in String);
List : constant Util.Beans.Basic.List_Bean_Access
:= ASF.Components.Utils.Get_List_Bean (UI, "autocompleteList", Context);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Need_Comma : Boolean := False;
Count : Natural;
procedure Render_Item (Label : in String) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if Match'Length = 0 or else
(Match'Length <= Label'Length
and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then
if Need_Comma then
Writer.Write (",");
end if;
Writer.Write ('"');
Util.Strings.Transforms.Escape_Java (Content => Label,
Into => Result);
Writer.Write (Result);
Writer.Write ('"');
Need_Comma := True;
end if;
end Render_Item;
begin
Writer.Write ('[');
if List /= null then
Count := List.Get_Count;
if List.all in ASF.Models.Selects.Select_Item_List'Class then
declare
S : constant access ASF.Models.Selects.Select_Item_List'Class
:= ASF.Models.Selects.Select_Item_List'Class (List.all)'Access;
begin
for I in 1 .. Count loop
Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label));
end loop;
end;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
declare
Value : constant Util.Beans.Objects.Object := List.Get_Row;
Label : constant String := Util.Beans.Objects.To_String (Value);
begin
Render_Item (Label);
end;
end loop;
end if;
end if;
Writer.Write (']');
end Render_List;
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then
declare
Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match");
ME : EL.Expressions.Method_Expression;
begin
if Value /= null then
declare
VE : constant EL.Expressions.Value_Expression
:= ASF.Views.Nodes.Get_Value_Expression (Value.all);
begin
VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all);
end;
end if;
-- Post an event on this component to trigger the rendering of the completion
-- list as part of an application/json output. The rendering is made by Broadcast.
ASF.Events.Faces.Actions.Post_Event (UI => UI,
Method => ME);
end;
else
ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context);
end if;
-- exception
-- when E : others =>
-- UI.Is_Valid := False;
-- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context);
-- Log.Info (Utils.Get_Line_Info (UI)
-- & ": Exception raised when updating value {0} for component {1}: {2}",
-- EL.Objects.To_String (UI.Submitted_Value),
-- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E));
end Process_Updates;
-- ------------------------------
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
-- ------------------------------
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Event);
Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value);
begin
Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8");
UI.Render_List (Match, Context);
Context.Response_Completed;
end Broadcast;
-- ------------------------------
-- Render the end of the input date component.
-- Generate the javascript code to activate the input date selector
-- and closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInputDate;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the input date script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Format : constant String := UI.Get_Attribute ("dateFormat", Context);
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').datepicker({");
if Format'Length > 0 then
Writer.Queue_Script ("dateFormat: """);
Writer.Queue_Script (Format);
Writer.Queue_Script ("""");
end if;
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
end ASF.Components.Widgets.Inputs;
|
Implement the inputDate component. Render the input field and write the javascript code to activate the jQuery date picker.
|
Implement the inputDate component.
Render the input field and write the javascript code to activate the jQuery date picker.
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
22409274a7d9a8756999f523b21daa719776ba60
|
regtests/util-http-clients-tests.adb
|
regtests/util-http-clients-tests.adb
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put",
Test_Http_Put'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete",
Test_Http_Delete'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Options",
Test_Http_Options'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get (timeout)",
Test_Http_Timeout'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Test_Server'Class,
Name => Test_Server_Access);
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
Free (T.Server);
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
elsif L (L'First .. Pos - 1) = "PUT" then
Into.Method := PUT;
elsif L (L'First .. Pos - 1) = "DELETE" then
Into.Method := DELETE;
elsif L (L'First .. Pos - 1) = "OPTIONS" then
Into.Method := OPTIONS;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
-- Don't answer if we check the timeout.
if Into.Test_Timeout then
return;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
elsif L'Length = 2 then
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
Request.Set_Timeout (5.0);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302,
"Get status is invalid: " & Natural'Image (Reply.Get_Status));
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found");
T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"),
"Some invalid header found");
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
-- ------------------------------
-- Test the http PUT operation.
-- ------------------------------
procedure Test_Http_Put (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Put on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
Request.Set_Timeout (1.0);
T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type");
Request.Put (Uri & "/put",
"p1=1", Reply);
T.Assert (T.Server.Method = PUT, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_put.txt"), Reply, True);
end Test_Http_Put;
-- ------------------------------
-- Test the http DELETE operation.
-- ------------------------------
procedure Test_Http_Delete (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Delete on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
Request.Set_Timeout (1.0);
T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type");
Request.Delete (Uri & "/delete", Reply);
T.Assert (T.Server.Method = DELETE, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response");
Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response");
end Test_Http_Delete;
-- ------------------------------
-- Test the http OPTIONS operation.
-- ------------------------------
procedure Test_Http_Options (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Delete on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
Request.Set_Timeout (1.0);
T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type");
Request.Options (Uri & "/options", Reply);
T.Assert (T.Server.Method = OPTIONS, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response");
Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response");
end Test_Http_Options;
-- ------------------------------
-- Test the http timeout.
-- ------------------------------
procedure Test_Http_Timeout (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Timeout on " & Uri);
T.Server.Test_Timeout := True;
T.Server.Method := UNKNOWN;
Request.Set_Timeout (0.5);
begin
Request.Get (Uri & "/timeout", Reply);
T.Fail ("No Connection_Error exception raised");
exception
when Connection_Error =>
null;
end;
end Test_Http_Timeout;
end Util.Http.Clients.Tests;
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put",
Test_Http_Put'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete",
Test_Http_Delete'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Options",
Test_Http_Options'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Patch",
Test_Http_Patch'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get (timeout)",
Test_Http_Timeout'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Test_Server'Class,
Name => Test_Server_Access);
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
Free (T.Server);
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
elsif L (L'First .. Pos - 1) = "PUT" then
Into.Method := PUT;
elsif L (L'First .. Pos - 1) = "DELETE" then
Into.Method := DELETE;
elsif L (L'First .. Pos - 1) = "OPTIONS" then
Into.Method := OPTIONS;
elsif L (L'First .. Pos - 1) = "PATCH" then
Into.Method := PATCH;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
-- Don't answer if we check the timeout.
if Into.Test_Timeout then
return;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
elsif L'Length = 2 then
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
Request.Set_Timeout (5.0);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302,
"Get status is invalid: " & Natural'Image (Reply.Get_Status));
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found");
T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"),
"Some invalid header found");
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
-- ------------------------------
-- Test the http PUT operation.
-- ------------------------------
procedure Test_Http_Put (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Put on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
Request.Set_Timeout (1.0);
T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type");
Request.Put (Uri & "/put",
"p1=1", Reply);
T.Assert (T.Server.Method = PUT, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_put.txt"), Reply, True);
end Test_Http_Put;
-- ------------------------------
-- Test the http DELETE operation.
-- ------------------------------
procedure Test_Http_Delete (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Delete on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
Request.Set_Timeout (1.0);
T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type");
Request.Delete (Uri & "/delete", Reply);
T.Assert (T.Server.Method = DELETE, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response");
Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response");
end Test_Http_Delete;
-- ------------------------------
-- Test the http OPTIONS operation.
-- ------------------------------
procedure Test_Http_Options (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Delete on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
Request.Set_Timeout (1.0);
T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type");
Request.Options (Uri & "/options", Reply);
T.Assert (T.Server.Method = OPTIONS, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response");
Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response");
end Test_Http_Options;
-- ------------------------------
-- Test the http PATCH operation.
-- ------------------------------
procedure Test_Http_Patch (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Patch on " & Uri);
T.Server.Method := UNKNOWN;
Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded");
Request.Set_Timeout (1.0);
T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type");
Request.Patch (Uri & "/patch", "patch-content", Reply);
T.Assert (T.Server.Method = PATCH, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, 200, Reply.Get_Status, "Invalid status response");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
end Test_Http_Patch;
-- ------------------------------
-- Test the http timeout.
-- ------------------------------
procedure Test_Http_Timeout (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Timeout on " & Uri);
T.Server.Test_Timeout := True;
T.Server.Method := UNKNOWN;
Request.Set_Timeout (0.5);
begin
Request.Get (Uri & "/timeout", Reply);
T.Fail ("No Connection_Error exception raised");
exception
when Connection_Error =>
null;
end;
end Test_Http_Timeout;
end Util.Http.Clients.Tests;
|
Implement the Test_Http_Patch and register the test for execution
|
Implement the Test_Http_Patch and register the test for execution
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
019bc1f51e0aff686ba9fc06f24c225186157b72
|
src/asf-components-widgets-likes.ads
|
src/asf-components-widgets-likes.ads
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with ASF.Applications;
with ASF.Components.Html;
with ASF.Contexts.Faces;
package ASF.Components.Widgets.Likes is
-- ------------------------------
-- UILike
-- ------------------------------
-- The <b>UILike</b> component displays a social like button to recommend a page.
type UILike is new ASF.Components.Html.UIHtmlComponent with null record;
-- Get the link to submit in the like action.
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String;
-- Render the like button for Facebook or Google+.
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Like Generator
-- ------------------------------
-- The <tt>Like_Generator</tt> represents the specific method for the generation of
-- a social like generator. A generator is registered under a given name with the
-- <tt>Register_Like</tt> operation. The current implementation provides a Facebook
-- like generator.
type Like_Generator is limited interface;
type Like_Generator_Access is access all Like_Generator'Class;
-- Render the like button according to the generator and the component attributes.
procedure Render_Like (Generator : in Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract;
-- Maximum number of generators that can be registered.
MAX_LIKE_GENERATOR : constant Positive := 5;
-- Register the like generator under the given name.
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access);
-- ------------------------------
-- Facebook like generator
-- ------------------------------
type Facebook_Like_Generator is new Like_Generator with null record;
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- The application configuration parameter that defines which Facebook client ID must be used.
package P_Facebook_App_Id is
new ASF.Applications.Parameter ("facebook.client_id", "");
-- ------------------------------
-- Google like generator
-- ------------------------------
type Google_Like_Generator is new Like_Generator with null record;
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Twitter like generator
-- ------------------------------
type Twitter_Like_Generator is new Like_Generator with null record;
overriding
procedure Render_Like (Generator : in Twitter_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end ASF.Components.Widgets.Likes;
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes Components
-- Copyright (C) 2013, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with ASF.Applications;
with ASF.Components.Html;
with ASF.Contexts.Faces;
package ASF.Components.Widgets.Likes is
-- ------------------------------
-- UILike
-- ------------------------------
-- The <b>UILike</b> component displays a social like button to recommend a page.
type UILike is new ASF.Components.Html.UIHtmlComponent with null record;
-- Get the link to submit in the like action.
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String;
-- Render the like button for Facebook or Google+.
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Like Generator
-- ------------------------------
-- The <tt>Like_Generator</tt> represents the specific method for the generation of
-- a social like generator. A generator is registered under a given name with the
-- <tt>Register_Like</tt> operation. The current implementation provides a Facebook
-- like generator.
type Like_Generator is limited interface;
type Like_Generator_Access is access all Like_Generator'Class;
-- Render the like button according to the generator and the component attributes.
procedure Render_Like (Generator : in Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract;
-- Maximum number of generators that can be registered.
MAX_LIKE_GENERATOR : constant Positive := 5;
-- Register the like generator under the given name.
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access);
-- ------------------------------
-- Facebook like generator
-- ------------------------------
type Facebook_Like_Generator is new Like_Generator with null record;
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- The application configuration parameter that defines which Facebook client ID must be used.
package P_Facebook_App_Id is
new ASF.Applications.Parameter ("facebook.client_id", "");
-- ------------------------------
-- Twitter like generator
-- ------------------------------
type Twitter_Like_Generator is new Like_Generator with null record;
overriding
procedure Render_Like (Generator : in Twitter_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end ASF.Components.Widgets.Likes;
|
Remove Google+ like because it does not exist anymore
|
Remove Google+ like because it does not exist anymore
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
da0e37d74b44e8b4b6cdbf991809b6628b739d43
|
mat/src/events/mat-events-targets.ads
|
mat/src/events/mat-events-targets.ads
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
type Event_Type is mod 16;
type Probe_Index_Type is mod 16;
type Probe_Event_Type is record
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Time;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
private
EVENT_BLOCK_SIZE : constant Positive := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Natural := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
private
Current : Event_Block_Access := null;
Events : Event_Map;
end Event_Collector;
type Target_Events is tagged limited record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
type Event_Type is mod 16;
type Probe_Index_Type is mod 16;
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Time;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
private
EVENT_BLOCK_SIZE : constant Positive := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Natural := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
private
Current : Event_Block_Access := null;
Events : Event_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is tagged limited record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
end MAT.Events.Targets;
|
Add a unique event id generated when the event is inserted
|
Add a unique event id generated when the event is inserted
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
1d2aa5863c06f5eb7275243260d17c2a160008ca
|
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 MAT.Types; use MAT.Types;
package body MAT.Memory.Targets is
procedure Create_Instance (Refs : in ClientInfo_Ref_Map) is
-- Adapter : Manager := Get_Manager (Refs);
-- Client : Client_Memory := new Client_Memory;
begin
-- Register_Client (Refs, "memory", Client.all'Access);
-- Register_Servant (Adapter, Proxy);
null;
end Create_Instance;
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 MAT.Types; use MAT.Types;
package body MAT.Memory.Targets is
--
-- procedure Create_Instance (Refs : in ClientInfo_Ref_Map) is
-- -- Adapter : Manager := Get_Manager (Refs);
-- -- Client : Client_Memory := new Client_Memory;
-- begin
-- -- Register_Client (Refs, "memory", Client.all'Access);
-- -- Register_Servant (Adapter, Proxy);
-- null;
-- end Create_Instance;
procedure Init is
begin
null;
end Init;
end MAT.Memory.Targets;
|
Comment old operation
|
Comment old operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f8fa5db0a18518ab75a62daa8d6bc789b1e26cb8
|
src/security-policies-roles.adb
|
src/security-policies-roles.adb
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based 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 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;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return "role";
end Get_Name;
-- ------------------------------
-- 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.
-- ------------------------------
procedure Prepare_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 Prepare_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-policies-roles -- Role based 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 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;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return "role";
end Get_Name;
-- ------------------------------
-- 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.
-- ------------------------------
procedure Prepare_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 Prepare_Config;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Policy : in out Role_Policy) is
use type Ada.Strings.Unbounded.String_Access;
begin
for I in Policy.Names'Range loop
exit when Policy.Names (I) = null;
Ada.Strings.Unbounded.Free (Policy.Names (I));
end loop;
end Finalize;
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;
|
Implement Finalize to cleanup the security policy
|
Implement Finalize to cleanup the security policy
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
f32189f652e38b7e872a75fe2a25cf75b2cefe22
|
src/security-policies-roles.ads
|
src/security-policies-roles.ads
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
-- In this policy, users are assigned one or several roles and permissions are
-- associated with roles. A permission is granted if the user has one of the roles required
-- by the permission.
--
-- === Policy creation ===
-- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Roles.Role_Policy_Access;
--
-- Create the role policy and register it in the policy manager as follows:
--
-- Policy := new Role_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- A role is represented by a name in security configuration files. A role based permission
-- is associated with a list of roles. The permission is granted if the user has one of these
-- roles. When the role based policy is registered in the policy manager, the following
-- XML configuration is used:
--
-- <policy-rules>
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <security-role>
-- <role-name>manager</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
-- ...
-- </policy-rules>
--
-- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt>
-- It 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.
--
-- Each role is identified by a name in the configuration file. It is represented by
-- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt>
-- is represented as an integer with a limit of 64 different roles.
--
-- === Assigning roles to users ===
-- A <tt>Security_Context</tt> must be associated with a set of roles before checking the
-- permission. This is done by using the <tt>Set_Role_Context</tt> operation:
--
-- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin");
--
package Security.Policies.Roles is
NAME : constant String := "Role-Policy";
-- 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;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
type Role_Name_Array is array (Positive range <>) of Ada.Strings.Unbounded.String_Access;
-- 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);
-- Get the number of roles set in the map.
function Get_Count (Map : in Role_Map) return Natural;
-- Return the list of role names separated by ','.
function To_String (List : in Role_Name_Array) return String;
-- ------------------------------
-- Role principal context
-- ------------------------------
-- The <tt>Role_Principal_Context</tt> interface must be implemented by the user
-- <tt>Principal</tt> to be able to use the role based policy. The role based policy
-- controller will first check that the <tt>Principal</tt> implements that interface.
-- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user.
type Role_Principal_Context is limited interface;
function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract;
-- ------------------------------
-- Policy context
-- ------------------------------
-- The <b>Role_Policy_Context</b> gives security context information that the role
-- based policy can use to verify the permission.
type Role_Policy_Context is new Policy_Context with record
Roles : Role_Map;
end record;
type Role_Policy_Context_Access is access all Role_Policy_Context'Class;
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map);
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in Role_Policy) return String;
-- 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;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Get the roles that grant the given permission.
function Get_Grants (Manager : in Role_Policy;
Permission : in Permissions.Permission_Index) return Role_Map;
-- Get the list of role names that are defined by the role map.
function Get_Role_Names (Manager : in Role_Policy;
Map : in Role_Map) return Role_Name_Array;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map);
-- Setup the XML parser to read the <b>role-permission</b> description.
overriding
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finalize the policy manager.
overriding
procedure Finalize (Policy : in out Role_Policy);
-- Get the role policy associated with the given policy manager.
-- Returns the role policy instance or null if it was not registered in the policy manager.
function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return Role_Policy_Access;
private
-- Array to map a permission index to a list of roles that are granted the permission.
type Permission_Role_Array is array (Permission_Index) of Role_Map;
type Role_Map_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Map_Name_Array := (others => null);
Next_Role : Role_Type := Role_Type'First;
Name : Util.Beans.Objects.Object;
Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0);
Count : Natural := 0;
-- The Grants array indicates for each permission the list of roles
-- that are granted the permission. This array allows a O(1) lookup.
-- The implementation is limited to 256 permissions and 64 roles so this array uses 2K.
-- The default is that no role is assigned to the permission.
Grants : Permission_Role_Array := (others => (others => False));
end record;
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
-- In this policy, users are assigned one or several roles and permissions are
-- associated with roles. A permission is granted if the user has one of the roles required
-- by the permission.
--
-- === Policy creation ===
-- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Roles.Role_Policy_Access;
--
-- Create the role policy and register it in the policy manager as follows:
--
-- Policy := new Role_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- A role is represented by a name in security configuration files. A role based permission
-- is associated with a list of roles. The permission is granted if the user has one of these
-- roles. When the role based policy is registered in the policy manager, the following
-- XML configuration is used:
--
-- <policy-rules>
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <security-role>
-- <role-name>manager</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
-- ...
-- </policy-rules>
--
-- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt>
-- It 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.
--
-- Each role is identified by a name in the configuration file. It is represented by
-- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt>
-- is represented as an integer with a limit of 64 different roles.
--
-- === Assigning roles to users ===
-- A <tt>Security_Context</tt> must be associated with a set of roles before checking the
-- permission. This is done by using the <tt>Set_Role_Context</tt> operation:
--
-- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin");
--
package Security.Policies.Roles is
NAME : constant String := "Role-Policy";
-- 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;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
type Role_Name_Array is array (Positive range <>) of Ada.Strings.Unbounded.String_Access;
-- 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);
-- Get the number of roles set in the map.
function Get_Count (Map : in Role_Map) return Natural;
-- Return the list of role names separated by ','.
function To_String (List : in Role_Name_Array) return String;
-- ------------------------------
-- Role principal context
-- ------------------------------
-- The <tt>Role_Principal_Context</tt> interface must be implemented by the user
-- <tt>Principal</tt> to be able to use the role based policy. The role based policy
-- controller will first check that the <tt>Principal</tt> implements that interface.
-- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user.
type Role_Principal_Context is limited interface;
function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract;
-- ------------------------------
-- Policy context
-- ------------------------------
-- The <b>Role_Policy_Context</b> gives security context information that the role
-- based policy can use to verify the permission.
type Role_Policy_Context is new Policy_Context with record
Roles : Role_Map;
end record;
type Role_Policy_Context_Access is access all Role_Policy_Context'Class;
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map);
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in Role_Policy) return String;
-- 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;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Get the roles that grant the given permission.
function Get_Grants (Manager : in Role_Policy;
Permission : in Permissions.Permission_Index) return Role_Map;
-- Get the list of role names that are defined by the role map.
function Get_Role_Names (Manager : in Role_Policy;
Map : in Role_Map) return Role_Name_Array;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map);
-- Setup the XML parser to read the <b>role-permission</b> description.
overriding
procedure Prepare_Config (Policy : in out Role_Policy;
Mapper : in out Util.Serialize.Mappers.Processing);
-- Finalize the policy manager.
overriding
procedure Finalize (Policy : in out Role_Policy);
-- Get the role policy associated with the given policy manager.
-- Returns the role policy instance or null if it was not registered in the policy manager.
function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return Role_Policy_Access;
private
-- Array to map a permission index to a list of roles that are granted the permission.
type Permission_Role_Array is array (Permission_Index) of Role_Map;
type Role_Map_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Map_Name_Array := (others => null);
Next_Role : Role_Type := Role_Type'First;
Name : Util.Beans.Objects.Object;
Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0);
Count : Natural := 0;
-- The Grants array indicates for each permission the list of roles
-- that are granted the permission. This array allows a O(1) lookup.
-- The implementation is limited to 256 permissions and 64 roles so this array uses 2K.
-- The default is that no role is assigned to the permission.
Grants : Permission_Role_Array := (others => (others => False));
end record;
end Security.Policies.Roles;
|
Change the Mapper parameter to use the Mappers.Processing type
|
Change the Mapper parameter to use the Mappers.Processing type
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
415623e838ed98fc2ce187a17134c2eacfe1019c
|
awa/plugins/awa-storages/src/awa-storages-servlets.adb
|
awa/plugins/awa-storages/src/awa-storages-servlets.adb
|
-----------------------------------------------------------------------
-- awa-storages-servlets -- Serve files saved in the storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ADO.Objects;
with ASF.Streams;
with AWA.Storages.Services;
with AWA.Storages.Modules;
package body AWA.Storages.Servlets is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Servlets");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
overriding
procedure Initialize (Server : in out Storage_Servlet;
Context : in Servlet.Core.Servlet_Registry'Class) is
begin
null;
end Initialize;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
overriding
procedure Do_Get (Server : in Storage_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
Data : ADO.Blob_Ref;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
begin
Storage_Servlet'Class (Server).Load (Request, Name, Mime, Date, Data);
if Data.Is_Null then
Log.Info ("Storage file {0} not found", Request.Get_Request_URI);
Response.Send_Error (ASF.Responses.SC_NOT_FOUND);
return;
end if;
-- Send the file.
Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime));
if Ada.Strings.Unbounded.Length (Name) > 0 then
Response.Add_Header ("Content-Disposition",
"attachment; filename=" & Ada.Strings.Unbounded.To_String (Name));
end if;
declare
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write (Data.Value.Data);
end;
exception
when ADO.Objects.NOT_FOUND | Constraint_Error =>
Log.Info ("Storage file {0} not found", Request.Get_Request_URI);
Response.Send_Error (ASF.Responses.SC_NOT_FOUND);
return;
end Do_Get;
-- ------------------------------
-- Load the data content that correspond to the GET request and get the name as well
-- as mime-type and date.
-- ------------------------------
procedure Load (Server : in Storage_Servlet;
Request : in out ASF.Requests.Request'Class;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Data : out ADO.Blob_Ref) is
pragma Unreferenced (Server);
Store : constant String := Request.Get_Path_Parameter (1);
Manager : constant Services.Storage_Service_Access := Storages.Modules.Get_Storage_Manager;
Id : ADO.Identifier;
begin
if Store'Length = 0 then
Log.Info ("Invalid storage URI: {0}", Store);
return;
end if;
-- Extract the storage identifier from the URI.
Id := ADO.Identifier'Value (Store);
Log.Info ("GET storage file {0}", Store);
Manager.Load (From => Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
end Load;
end AWA.Storages.Servlets;
|
-----------------------------------------------------------------------
-- awa-storages-servlets -- Serve files saved in the storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ADO.Objects;
with ASF.Streams;
with AWA.Storages.Services;
with AWA.Storages.Modules;
package body AWA.Storages.Servlets is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Servlets");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
overriding
procedure Initialize (Server : in out Storage_Servlet;
Context : in Servlet.Core.Servlet_Registry'Class) is
begin
null;
end Initialize;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
-- ------------------------------
overriding
procedure Do_Get (Server : in Storage_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
URI : constant String := Request.Get_Request_URI;
Data : ADO.Blob_Ref;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
begin
Storage_Servlet'Class (Server).Load (Request, Name, Mime, Date, Data);
if Data.Is_Null then
Log.Info ("GET: {0}: storage file not found", URI);
Response.Send_Error (ASF.Responses.SC_NOT_FOUND);
return;
end if;
Log.Info ("GET: {0}", URI);
-- Send the file.
Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime));
if Ada.Strings.Unbounded.Length (Name) > 0 then
Response.Add_Header ("Content-Disposition",
"attachment; filename=" & Ada.Strings.Unbounded.To_String (Name));
end if;
declare
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write (Data.Value.Data);
end;
exception
when ADO.Objects.NOT_FOUND | Constraint_Error =>
Log.Info ("GET: {0}: Storage file not found", URI);
Response.Send_Error (ASF.Responses.SC_NOT_FOUND);
return;
end Do_Get;
-- ------------------------------
-- Load the data content that correspond to the GET request and get the name as well
-- as mime-type and date.
-- ------------------------------
procedure Load (Server : in Storage_Servlet;
Request : in out ASF.Requests.Request'Class;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Data : out ADO.Blob_Ref) is
pragma Unreferenced (Server);
Store : constant String := Request.Get_Path_Parameter (1);
Manager : constant Services.Storage_Service_Access := Storages.Modules.Get_Storage_Manager;
Id : ADO.Identifier;
begin
if Store'Length = 0 then
Log.Info ("Invalid storage URI: {0}", Store);
return;
end if;
-- Extract the storage identifier from the URI.
Id := ADO.Identifier'Value (Store);
Log.Info ("GET storage file {0}", Store);
Manager.Load (From => Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
end Load;
end AWA.Storages.Servlets;
|
Add some log message to help in debugging
|
Add some log message to help in debugging
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
9d0370993de41c12a6749469e2dd6dabb19210f5
|
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
|
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Helpers.Requests;
with AWA.Helpers.Selectors;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
package body AWA.Blogs.Beans is
use type ADO.Identifier;
use Ada.Strings.Unbounded;
BLOG_ID_PARAMETER : constant String := "blog_id";
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if not From.Is_Null then
return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create a new blog.
-- ------------------------------
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
Bean.Module.Create_Blog (Workspace_Id => 0,
Title => Bean.Get_Name,
Result => Result);
end Create;
-- ------------------------------
-- Create the Blog_Bean bean instance.
-- ------------------------------
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER);
Object : constant Blog_Bean_Access := new Blog_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Object.Load (Session, Blog_Id);
end if;
Object.Module := Module;
return Object.all'Access;
end Create_Blog_Bean;
-- ------------------------------
-- Create or save the post.
-- ------------------------------
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
if not Bean.Is_Inserted then
Bean.Module.Create_Post (Blog_Id => Bean.Blog_Id,
Title => Bean.Get_Title,
URI => Bean.Get_Uri,
Text => Bean.Get_Text,
Status => Bean.Get_Status,
Result => Result);
else
Bean.Module.Update_Post (Post_Id => Bean.Get_Id,
Title => Bean.Get_Title,
Text => Bean.Get_Text,
Status => Bean.Get_Status);
Result := Bean.Get_Id;
end if;
Bean.Tags.Update_Tags (Result);
end Save;
-- ------------------------------
-- Delete a post.
-- ------------------------------
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Post (Post_Id => Bean.Get_Id);
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = BLOG_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
elsif Name = POST_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Get_Id));
elsif Name = POST_USERNAME_ATTR then
return Util.Beans.Objects.To_Object (String '(From.Get_Author.Get_Name));
elsif Name = POST_TAG_ATTR then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
else
return AWA.Blogs.Models.Post_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = BLOG_ID_ATTR then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then
From.Load_Post (ADO.Utils.To_Identifier (Value));
elsif Name = POST_TEXT_ATTR then
From.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_TITLE_ATTR then
From.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_URI_ATTR then
From.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_STATUS_ATTR then
From.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value));
end if;
end Set_Value;
-- ------------------------------
-- Load the post.
-- ------------------------------
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Post.Module.Get_Session;
begin
Post.Load (Session, Id);
Post.Tags.Load_Tags (Session, Id);
-- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of
-- objects does not work yet. Force loading the user here while the above
-- session is still open.
declare
A : constant String := String '(Post.Get_Author.Get_Name);
pragma Unreferenced (A);
begin
null;
end;
end Load_Post;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Post_Bean_Access := new Post_Bean;
begin
Object.Module := Module;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Blogs.Models.POST_TABLE);
Object.Tags.Set_Permission ("blog-update-post");
return Object.all'Access;
end Create_Post_Bean;
-- ------------------------------
-- Create the Post_List_Bean bean instance.
-- ------------------------------
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Blogs.Models;
Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List);
AWA.Blogs.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Post_List_Bean;
-- ------------------------------
-- Create the Blog_List_Bean bean instance.
-- ------------------------------
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Blog_Admin_Bean_Access := new Blog_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Post_List_Bean := Object.Post_List'Access;
Object.Blog_List_Bean := Object.Blog_List'Access;
return Object.all'Access;
end Create_Blog_Admin_Bean;
function Create_From_Status is
new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type,
"blog_status_");
-- ------------------------------
-- Get a select item list which contains a list of post status.
-- ------------------------------
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
pragma Unreferenced (Module);
use AWA.Helpers;
begin
return Selectors.Create_Selector_Bean (Bundle => "blogs",
Context => null,
Create => Create_From_Status'Access).all'Access;
end Create_Status_List;
-- ------------------------------
-- Load the list of blogs.
-- ------------------------------
procedure Load_Blogs (List : in Blog_Admin_Bean) is
use AWA.Blogs.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Blogs.Models.Query_Blog_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Blog_List_Bean.all, Session, Query);
List.Flags (INIT_BLOG_LIST) := True;
end Load_Blogs;
-- ------------------------------
-- Get the blog identifier.
-- ------------------------------
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier is
begin
if List.Blog_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
if not List.Blog_List.List.Is_Empty then
return List.Blog_List.List.Element (0).Id;
end if;
end if;
return List.Blog_Id;
end Get_Blog_Id;
-- ------------------------------
-- Load the posts associated with the current blog.
-- ------------------------------
procedure Load_Posts (List : in Blog_Admin_Bean) is
use AWA.Blogs.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
Blog_Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List);
Query.Bind_Param ("blog_id", Blog_Id);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Post_List_Bean.all, Session, Query);
List.Flags (INIT_POST_LIST) := True;
end if;
end Load_Posts;
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "blogs" then
if not List.Init_Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Blog_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "posts" then
if not List.Init_Flags (INIT_POST_LIST) then
Load_Posts (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Post_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Helpers.Requests;
with AWA.Helpers.Selectors;
with AWA.Tags.Modules;
with ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
package body AWA.Blogs.Beans is
use type ADO.Identifier;
use Ada.Strings.Unbounded;
BLOG_ID_PARAMETER : constant String := "blog_id";
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if not From.Is_Null then
return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create a new blog.
-- ------------------------------
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
Bean.Module.Create_Blog (Workspace_Id => 0,
Title => Bean.Get_Name,
Result => Result);
end Create;
-- ------------------------------
-- Create the Blog_Bean bean instance.
-- ------------------------------
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER);
Object : constant Blog_Bean_Access := new Blog_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Object.Load (Session, Blog_Id);
end if;
Object.Module := Module;
return Object.all'Access;
end Create_Blog_Bean;
-- ------------------------------
-- Create or save the post.
-- ------------------------------
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Result : ADO.Identifier;
begin
if not Bean.Is_Inserted then
Bean.Module.Create_Post (Blog_Id => Bean.Blog_Id,
Title => Bean.Get_Title,
URI => Bean.Get_Uri,
Text => Bean.Get_Text,
Status => Bean.Get_Status,
Result => Result);
else
Bean.Module.Update_Post (Post_Id => Bean.Get_Id,
Title => Bean.Get_Title,
Text => Bean.Get_Text,
Status => Bean.Get_Status);
Result := Bean.Get_Id;
end if;
Bean.Tags.Update_Tags (Result);
end Save;
-- ------------------------------
-- Delete a post.
-- ------------------------------
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Post (Post_Id => Bean.Get_Id);
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = BLOG_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
elsif Name = POST_ID_ATTR then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Get_Id));
elsif Name = POST_USERNAME_ATTR then
return Util.Beans.Objects.To_Object (String '(From.Get_Author.Get_Name));
elsif Name = POST_TAG_ATTR then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
else
return AWA.Blogs.Models.Post_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = BLOG_ID_ATTR then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then
From.Load_Post (ADO.Utils.To_Identifier (Value));
elsif Name = POST_TEXT_ATTR then
From.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_TITLE_ATTR then
From.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_URI_ATTR then
From.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value));
elsif Name = POST_STATUS_ATTR then
From.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value));
end if;
end Set_Value;
-- ------------------------------
-- Load the post.
-- ------------------------------
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Post.Module.Get_Session;
begin
Post.Load (Session, Id);
Post.Tags.Load_Tags (Session, Id);
-- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of
-- objects does not work yet. Force loading the user here while the above
-- session is still open.
declare
A : constant String := String '(Post.Get_Author.Get_Name);
pragma Unreferenced (A);
begin
null;
end;
end Load_Post;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Post_Bean_Access := new Post_Bean;
begin
Object.Module := Module;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Blogs.Models.POST_TABLE);
Object.Tags.Set_Permission ("blog-update-post");
return Object.all'Access;
end Create_Post_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
Pos : Natural;
begin
if Name = "tags" then
Pos := From.Posts.Get_Row_Index;
if Pos = 0 then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Models.Post_Info := From.Posts.List.Element (Pos - 1);
begin
return From.Tags.Get_Tags (Item.Id);
end;
elsif Name = "posts" then
return Util.Beans.Objects.To_Object (Value => From.Posts_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return From.Posts.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Post_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 posts. If a tag was set, filter the list of posts with the tag.
-- ------------------------------
procedure Load_List (Into : in out Post_List_Bean) is
use AWA.Blogs.Models;
use AWA.Services;
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.Blogs.Models.Query_Blog_Post_Tag_List);
Query.Bind_Param (Name => "tag", Value => Tag_Id);
else
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List);
end if;
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Blogs.Models.POST_TABLE,
Session => Session);
AWA.Blogs.Models.List (Into.Posts, Session, Query);
declare
List : ADO.Utils.Identifier_Vector;
Iter : Post_Info_Vectors.Cursor := Into.Posts.List.First;
begin
while Post_Info_Vectors.Has_Element (Iter) loop
List.Append (Post_Info_Vectors.Element (Iter).Id);
Post_Info_Vectors.Next (Iter);
end loop;
Into.Tags.Load_Tags (Session, AWA.Blogs.Models.POST_TABLE.Table.all,
List);
end;
end Load_List;
-- ------------------------------
-- Create the Post_List_Bean bean instance.
-- ------------------------------
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Post_List_Bean_Access := new Post_List_Bean;
begin
Object.Service := Module;
Object.Posts_Bean := Object.Posts'Access;
Object.Load_List;
return Object.all'Access;
end Create_Post_List_Bean;
-- ------------------------------
-- Create the Blog_List_Bean bean instance.
-- ------------------------------
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Blog_Admin_Bean_Access := new Blog_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Post_List_Bean := Object.Post_List'Access;
Object.Blog_List_Bean := Object.Blog_List'Access;
return Object.all'Access;
end Create_Blog_Admin_Bean;
function Create_From_Status is
new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type,
"blog_status_");
-- ------------------------------
-- Get a select item list which contains a list of post status.
-- ------------------------------
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
pragma Unreferenced (Module);
use AWA.Helpers;
begin
return Selectors.Create_Selector_Bean (Bundle => "blogs",
Context => null,
Create => Create_From_Status'Access).all'Access;
end Create_Status_List;
-- ------------------------------
-- Load the list of blogs.
-- ------------------------------
procedure Load_Blogs (List : in Blog_Admin_Bean) is
use AWA.Blogs.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Blogs.Models.Query_Blog_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Blog_List_Bean.all, Session, Query);
List.Flags (INIT_BLOG_LIST) := True;
end Load_Blogs;
-- ------------------------------
-- Get the blog identifier.
-- ------------------------------
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier is
begin
if List.Blog_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
if not List.Blog_List.List.Is_Empty then
return List.Blog_List.List.Element (0).Id;
end if;
end if;
return List.Blog_Id;
end Get_Blog_Id;
-- ------------------------------
-- Load the posts associated with the current blog.
-- ------------------------------
procedure Load_Posts (List : in Blog_Admin_Bean) is
use AWA.Blogs.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
Blog_Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Blog_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List);
Query.Bind_Param ("blog_id", Blog_Id);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Blogs.Models.BLOG_TABLE, Session);
AWA.Blogs.Models.List (List.Post_List_Bean.all, Session, Query);
List.Flags (INIT_POST_LIST) := True;
end if;
end Load_Posts;
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "blogs" then
if not List.Init_Flags (INIT_BLOG_LIST) then
Load_Blogs (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Blog_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "posts" then
if not List.Init_Flags (INIT_POST_LIST) then
Load_Posts (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Post_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
Id : constant ADO.Identifier := List.Get_Blog_Id;
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Blog_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
end AWA.Blogs.Beans;
|
Implement the Post_List_Bean operations
|
Implement the Post_List_Bean operations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5f6e6a3748416c37d7282e63f552ef7add345c62
|
matp/src/memory/mat-memory-probes.ads
|
matp/src/memory/mat-memory-probes.ads
|
-----------------------------------------------------------------------
-- mat-memory-probes - 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 MAT.Events;
with MAT.Readers;
with MAT.Events.Targets;
with MAT.Events.Probes;
with MAT.Memory.Targets;
package MAT.Memory.Probes is
type Memory_Probe_Type is new MAT.Events.Probes.Probe_Type with record
Data : access MAT.Memory.Targets.Target_Memory;
end record;
type Memory_Probe_Type_Access is access all Memory_Probe_Type'Class;
-- Extract the probe information from the message.
overriding
procedure Extract (Probe : in Memory_Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out MAT.Events.Targets.Probe_Event_Type);
procedure Execute (Probe : in Memory_Probe_Type;
Event : in MAT.Events.Targets.Probe_Event_Type);
-- Register the reader to extract and analyze memory events.
procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class;
Probe : in Memory_Probe_Type_Access);
end MAT.Memory.Probes;
|
-----------------------------------------------------------------------
-- mat-memory-probes - Definition and Analysis of memory events
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Events;
with MAT.Readers;
with MAT.Events.Targets;
with MAT.Events.Probes;
with MAT.Memory.Targets;
package MAT.Memory.Probes is
type Memory_Probe_Type is new MAT.Events.Probes.Probe_Type with record
Data : access MAT.Memory.Targets.Target_Memory;
end record;
type Memory_Probe_Type_Access is access all Memory_Probe_Type'Class;
-- Extract the probe information from the message.
overriding
procedure Extract (Probe : in Memory_Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out MAT.Events.Targets.Probe_Event_Type);
procedure Execute (Probe : in Memory_Probe_Type;
Event : in out MAT.Events.Targets.Probe_Event_Type);
-- Register the reader to extract and analyze memory events.
procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class;
Probe : in Memory_Probe_Type_Access);
end MAT.Memory.Probes;
|
Change the Event parameter of Execute to an in out parameter
|
Change the Event parameter of Execute to an in out parameter
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
6b6df516dd05ee711cbce3074f9bf207ff405425
|
regtests/util-log-tests.adb
|
regtests/util-log-tests.adb
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
use Util;
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
pragma Unreferenced (T);
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Log;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
end Test_Log_Perf;
-- ------------------------------
-- Test appending the log on several log files
-- ------------------------------
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_File_Appender_Modes (T : in out Test) is
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-append.log");
Props.Set ("log4j.appender.test.append", "true");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Error ("This is the error test message");
end;
Props.Set ("log4j.appender.test_append", "File");
Props.Set ("log4j.appender.test_append.File", "test-append.log");
Props.Set ("log4j.appender.test_append.append", "true");
Props.Set ("log4j.appender.test_append.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
declare
L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file");
begin
L1.Info ("Writing a info message");
L2.Info ("{0}: {1}", "Parameter", "Value");
L1.Info ("Done");
L2.Error ("This is the error test2 message");
end;
Props.Set ("log4j.appender.test_append.append", "plop");
Props.Set ("log4j.appender.test_append.immediateFlush", "falsex");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
end Test_File_Appender_Modes;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)",
Test_File_Appender_Modes'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
use Util;
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
pragma Unreferenced (T);
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Log;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
end Test_Log_Perf;
-- ------------------------------
-- Test appending the log on several log files
-- ------------------------------
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_File_Appender_Modes (T : in out Test) is
use Ada.Directories;
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-append.log");
Props.Set ("log4j.appender.test.append", "true");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.appender.test_global", "File");
Props.Set ("log4j.appender.test_global.File", "test-append-global.log");
Props.Set ("log4j.appender.test_global.append", "false");
Props.Set ("log4j.appender.test_global.immediateFlush", "false");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG");
Props.Set ("log4j.rootCategory", "DEBUG,test_global,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Error ("This is the error test message");
end;
Props.Set ("log4j.appender.test_append", "File");
Props.Set ("log4j.appender.test_append.File", "test-append2.log");
Props.Set ("log4j.appender.test_append.append", "true");
Props.Set ("log4j.appender.test_append.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global");
Util.Log.Loggers.Initialize (Props);
declare
L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file");
begin
L1.Info ("L1-1 Writing a info message");
L2.Info ("L2-2 {0}: {1}", "Parameter", "Value");
L1.Info ("L1-3 Done");
L2.Error ("L2-4 This is the error test2 message");
end;
Props.Set ("log4j.appender.test_append.append", "plop");
Props.Set ("log4j.appender.test_append.immediateFlush", "falsex");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
T.Assert (Ada.Directories.Size ("test-append.log") > 100,
"Log file test-append.log is empty");
T.Assert (Ada.Directories.Size ("test-append2.log") > 100,
"Log file test-append2.log is empty");
T.Assert (Ada.Directories.Size ("test-append-global.log") > 100,
"Log file test-append.log is empty");
end Test_File_Appender_Modes;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)",
Test_File_Appender_Modes'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
Update and add tests for the append log file test
|
Update and add tests for the append log file test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
693c58e907b29fcd8b50890fd8fc02b0dbc31ca6
|
awa/samples/src/atlas-applications.ads
|
awa/samples/src/atlas-applications.ads
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 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 Util.Beans.Objects;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Filters.Dump;
with ASF.Servlets.Measures;
with ASF.Security.Servlets;
with ASF.Converters.Sizes;
with AWA.Users.Servlets;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Applications;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Wikis.Modules;
with AWA.Wikis.Previews;
with AWA.Jobs.Modules;
with AWA.Counters.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Comments.Modules;
with AWA.Services.Filters;
with AWA.Converters.Dates;
with Atlas.Microblog.Modules;
with Atlas.Reviews.Modules;
package Atlas.Applications is
CONFIG_PATH : constant String := "/atlas";
CONTEXT_PATH : constant String := "/atlas";
ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas";
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
function Get_Gravatar_Link (Email : in String) return String;
-- EL function to convert an Email address to a Gravatar image.
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
type Application is new AWA.Applications.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application.
procedure Initialize (App : in Application_Access);
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
overriding
procedure Initialize_Components (App : in out Application);
-- 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 Application);
-- 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 Application);
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
overriding
procedure Initialize_Modules (App : in out Application);
private
type Application is new AWA.Applications.Application with record
Self : Application_Access;
-- Application servlets and filters (add new servlet and filter instances here).
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- Authentication servlet and filter.
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet;
-- Converters shared by web requests.
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Size_Converter : aliased ASF.Converters.Sizes.Size_Converter;
-- The application modules.
User_Module : aliased AWA.Users.Modules.User_Module;
Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module;
Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
Mail_Module : aliased AWA.Mail.Modules.Mail_Module;
Job_Module : aliased AWA.Jobs.Modules.Job_Module;
Storage_Module : aliased AWA.Storages.Modules.Storage_Module;
Image_Module : aliased AWA.Images.Modules.Image_Module;
Vote_Module : aliased AWA.Votes.Modules.Vote_Module;
Question_Module : aliased AWA.Questions.Modules.Question_Module;
Tag_Module : aliased AWA.Tags.Modules.Tag_Module;
Comment_Module : aliased AWA.Comments.Modules.Comment_Module;
Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module;
Preview_Module : aliased AWA.Wikis.Previews.Preview_Module;
Counter_Module : aliased AWA.Counters.Modules.Counter_Module;
Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module;
Review_Module : aliased Atlas.Reviews.Modules.Review_Module;
end record;
end Atlas.Applications;
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 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 Util.Beans.Objects;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Filters.Dump;
with ASF.Filters.Cache_Control;
with ASF.Servlets.Measures;
with ASF.Security.Servlets;
with ASF.Converters.Sizes;
with AWA.Users.Servlets;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Applications;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Wikis.Modules;
with AWA.Wikis.Previews;
with AWA.Jobs.Modules;
with AWA.Counters.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Comments.Modules;
with AWA.Services.Filters;
with AWA.Converters.Dates;
with Atlas.Microblog.Modules;
with Atlas.Reviews.Modules;
package Atlas.Applications is
CONFIG_PATH : constant String := "/atlas";
CONTEXT_PATH : constant String := "/atlas";
ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas";
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
function Get_Gravatar_Link (Email : in String) return String;
-- EL function to convert an Email address to a Gravatar image.
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
type Application is new AWA.Applications.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application.
procedure Initialize (App : in Application_Access);
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
overriding
procedure Initialize_Components (App : in out Application);
-- 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 Application);
-- 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 Application);
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
overriding
procedure Initialize_Modules (App : in out Application);
private
type Application is new AWA.Applications.Application with record
Self : Application_Access;
-- Application servlets and filters (add new servlet and filter instances here).
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
No_Cache : aliased ASF.Filters.Cache_Control.Cache_Control_Filter;
-- Authentication servlet and filter.
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet;
-- Converters shared by web requests.
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Size_Converter : aliased ASF.Converters.Sizes.Size_Converter;
-- The application modules.
User_Module : aliased AWA.Users.Modules.User_Module;
Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module;
Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
Mail_Module : aliased AWA.Mail.Modules.Mail_Module;
Job_Module : aliased AWA.Jobs.Modules.Job_Module;
Storage_Module : aliased AWA.Storages.Modules.Storage_Module;
Image_Module : aliased AWA.Images.Modules.Image_Module;
Vote_Module : aliased AWA.Votes.Modules.Vote_Module;
Question_Module : aliased AWA.Questions.Modules.Question_Module;
Tag_Module : aliased AWA.Tags.Modules.Tag_Module;
Comment_Module : aliased AWA.Comments.Modules.Comment_Module;
Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module;
Preview_Module : aliased AWA.Wikis.Previews.Preview_Module;
Counter_Module : aliased AWA.Counters.Modules.Counter_Module;
Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module;
Review_Module : aliased Atlas.Reviews.Modules.Review_Module;
end record;
end Atlas.Applications;
|
Add a cache control filter
|
Add a cache control filter
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
25f5108c02efa21af014c8321c8e6fbc26b3dec5
|
mat/src/memory/mat-memory-readers.adb
|
mat/src/memory/mat-memory-readers.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.Types;
with MAT.Readers.Marshaller;
with MAT.Memory;
package body MAT.Memory.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers");
MSG_MALLOC : constant MAT.Events.Internal_Reference := 0;
MSG_FREE : constant MAT.Events.Internal_Reference := 1;
MSG_REALLOC : constant MAT.Events.Internal_Reference := 2;
M_SIZE : constant MAT.Events.Internal_Reference := 1;
M_FRAME : constant MAT.Events.Internal_Reference := 2;
M_ADDR : constant MAT.Events.Internal_Reference := 3;
M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4;
M_THREAD : constant MAT.Events.Internal_Reference := 5;
M_UNKNOWN : constant MAT.Events.Internal_Reference := 6;
M_TIME : constant MAT.Events.Internal_Reference := 7;
-- Defines the possible data kinds which are recognized by
-- the memory unmarshaller. All others are ignored.
SIZE_NAME : aliased constant String := "size";
FRAME_NAME : aliased constant String := "frame";
ADDR_NAME : aliased constant String := "pointer";
OLD_NAME : aliased constant String := "old-pointer";
THREAD_NAME : aliased constant String := "thread";
TIME_NAME : aliased constant String := "time";
Memory_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => SIZE_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE),
2 => (Name => FRAME_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_FRAME),
3 => (Name => ADDR_NAME'Access, Size => 0,
Kind => MAT.Events.T_POINTER, Ref => M_ADDR),
4 => (Name => OLD_NAME'Access, Size => 0,
Kind => MAT.Events.T_POINTER, Ref => M_ADDR),
5 => (Name => THREAD_NAME'Access, Size => 0,
Kind => MAT.Events.T_THREAD, Ref => M_THREAD),
6 => (Name => TIME_NAME'Access, Size => 0,
Kind => MAT.Events.T_TIME, Ref => M_TIME));
procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message;
Slot : in out Allocation;
Addr : in out MAT.Types.Target_Addr;
Old_Addr : in out MAT.Types.Target_Addr;
Defs : in MAT.Events.Attribute_Table);
procedure Process_Malloc_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Slot : in out Allocation);
procedure Process_Free_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
procedure Process_Realloc_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
----------------------
-- Register the reader to extract and analyze memory events.
----------------------
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Memory_Reader_Access) is
begin
Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC,
Memory_Attributes'Access);
Into.Register_Reader (Reader.all'Access, "free", MSG_FREE,
Memory_Attributes'Access);
Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC,
Memory_Attributes'Access);
end Register;
----------------------
-- A memory allocation message is received. Register the memory
-- slot in the allocated memory list. An event is posted on the
-- event channel to notify the listeners that a new slot is allocated.
----------------------
procedure Process_Malloc_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Slot : in out Allocation) is
-- Ev : MAT.Memory.Events.Memory_Event := (Kind => EV_MALLOC, Addr => Addr);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Client.Data.Memory_Slots.Insert (Addr, Slot);
-- Post (Client.Event_Channel, Ev);
end Process_Malloc_Message;
----------------------
-- A memory deallocation message. Find the memory slot being freed
-- and remove it from the allocated list. Post an event on the event
-- channel to notify the listeners that the slot is removed.
----------------------
procedure Process_Free_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Addr);
-- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
if not MAT.Memory.Allocation_Maps.Has_Element (It) then
-- Address is not in the map. The application is freeing
-- an already freed memory or something wrong.
return;
end if;
-- Post (Client.Event_Channel, Ev);
declare
Old_Slot : constant Allocation := MAT.Memory.Allocation_Maps.Element (It);
begin
-- Remove the memory slot from our map.
Client.Data.Memory_Slots.Delete (It);
Frames.Release (Old_Slot.Frame);
end;
end Process_Free_Message;
----------------------
-- A memory deallocation message. Find the memory slot being freed
-- and remove it from the allocated list. Post an event on the event
-- channel to notify the listeners that the slot is removed.
----------------------
procedure Process_Realloc_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Old_Addr);
-- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
if MAT.Memory.Allocation_Maps.Has_Element (It) then
-- Address is not in the map. The application is freeing
-- an already freed memory or something wrong.
-- Post (Client.Event_Channel, Ev);
declare
Old_Slot : constant Allocation := MAT.Memory.Allocation_Maps.Element (It);
begin
-- Remove the memory slot from our map.
Client.Data.Memory_Slots.Delete (It);
Frames.Release (Old_Slot.Frame);
end;
end if;
Client.Data.Memory_Slots.Insert (Addr, Slot);
end Process_Realloc_Message;
----------------------
-- Unmarshall from the message the memory slot information.
-- The data is described by the Defs table.
----------------------
procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message;
Slot : in out Allocation;
Addr : in out MAT.Types.Target_Addr;
Old_Addr : in out MAT.Types.Target_Addr;
Defs : in MAT.Events.Attribute_Table) is
begin
for I in Defs'Range loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_SIZE =>
Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind);
when M_ADDR =>
Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when M_OLD_ADDR =>
Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when M_UNKNOWN =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
when others =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
end case;
end;
end loop;
end Unmarshall_Allocation;
overriding
procedure Dispatch (For_Servant : in out Memory_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message) is
Slot : Allocation;
Addr : MAT.Types.Target_Addr := 0;
Old_Addr : MAT.Types.Target_Addr := 0;
begin
case Id is
when MSG_MALLOC =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
Frames.Insert (Frame => For_Servant.Data.Frames,
Pc => Frame.Frame (1 .. Frame.Cur_Depth),
Result => Slot.Frame);
Process_Malloc_Message (For_Servant, Addr, Slot);
when MSG_FREE =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
Process_Free_Message (For_Servant, Addr, Slot);
when MSG_REALLOC =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
Frames.Insert (Frame => For_Servant.Data.Frames,
Pc => Frame.Frame (1 .. Frame.Cur_Depth),
Result => Slot.Frame);
Process_Realloc_Message (For_Servant, Addr, Old_Addr, Slot);
when others =>
raise Program_Error;
end case;
end Dispatch;
end MAT.Memory.Readers;
|
-----------------------------------------------------------------------
-- 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.Types;
with MAT.Readers.Marshaller;
with MAT.Memory;
package body MAT.Memory.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers");
MSG_MALLOC : constant MAT.Events.Internal_Reference := 0;
MSG_FREE : constant MAT.Events.Internal_Reference := 1;
MSG_REALLOC : constant MAT.Events.Internal_Reference := 2;
M_SIZE : constant MAT.Events.Internal_Reference := 1;
M_FRAME : constant MAT.Events.Internal_Reference := 2;
M_ADDR : constant MAT.Events.Internal_Reference := 3;
M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4;
M_THREAD : constant MAT.Events.Internal_Reference := 5;
M_UNKNOWN : constant MAT.Events.Internal_Reference := 6;
M_TIME : constant MAT.Events.Internal_Reference := 7;
-- Defines the possible data kinds which are recognized by
-- the memory unmarshaller. All others are ignored.
SIZE_NAME : aliased constant String := "size";
FRAME_NAME : aliased constant String := "frame";
ADDR_NAME : aliased constant String := "pointer";
OLD_NAME : aliased constant String := "old-pointer";
THREAD_NAME : aliased constant String := "thread";
TIME_NAME : aliased constant String := "time";
Memory_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => SIZE_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE),
2 => (Name => FRAME_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_FRAME),
3 => (Name => ADDR_NAME'Access, Size => 0,
Kind => MAT.Events.T_POINTER, Ref => M_ADDR),
4 => (Name => OLD_NAME'Access, Size => 0,
Kind => MAT.Events.T_POINTER, Ref => M_ADDR),
5 => (Name => THREAD_NAME'Access, Size => 0,
Kind => MAT.Events.T_THREAD, Ref => M_THREAD),
6 => (Name => TIME_NAME'Access, Size => 0,
Kind => MAT.Events.T_TIME, Ref => M_TIME));
procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message;
Slot : in out Allocation;
Addr : in out MAT.Types.Target_Addr;
Old_Addr : in out MAT.Types.Target_Addr;
Defs : in MAT.Events.Attribute_Table);
procedure Process_Malloc_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Slot : in out Allocation);
procedure Process_Free_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
procedure Process_Realloc_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation);
----------------------
-- Register the reader to extract and analyze memory events.
----------------------
procedure Register (Into : in out MAT.Readers.Manager_Base'Class;
Reader : in Memory_Reader_Access) is
begin
Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC,
Memory_Attributes'Access);
Into.Register_Reader (Reader.all'Access, "free", MSG_FREE,
Memory_Attributes'Access);
Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC,
Memory_Attributes'Access);
end Register;
----------------------
-- A memory allocation message is received. Register the memory
-- slot in the allocated memory list. An event is posted on the
-- event channel to notify the listeners that a new slot is allocated.
----------------------
procedure Process_Malloc_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Slot : in out Allocation) is
-- Ev : MAT.Memory.Events.Memory_Event := (Kind => EV_MALLOC, Addr => Addr);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Client.Data.Memory_Slots.Insert (Addr, Slot);
-- Post (Client.Event_Channel, Ev);
end Process_Malloc_Message;
----------------------
-- A memory deallocation message. Find the memory slot being freed
-- and remove it from the allocated list. Post an event on the event
-- channel to notify the listeners that the slot is removed.
----------------------
procedure Process_Free_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Addr);
-- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
if not MAT.Memory.Allocation_Maps.Has_Element (It) then
-- Address is not in the map. The application is freeing
-- an already freed memory or something wrong.
return;
end if;
-- Post (Client.Event_Channel, Ev);
declare
Old_Slot : constant Allocation := MAT.Memory.Allocation_Maps.Element (It);
begin
-- Remove the memory slot from our map.
Client.Data.Memory_Slots.Delete (It);
Frames.Release (Old_Slot.Frame);
end;
end Process_Free_Message;
----------------------
-- A memory deallocation message. Find the memory slot being freed
-- and remove it from the allocated list. Post an event on the event
-- channel to notify the listeners that the slot is removed.
----------------------
procedure Process_Realloc_Message (Client : in out Memory_Servant;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Old_Addr);
-- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
if MAT.Memory.Allocation_Maps.Has_Element (It) then
-- Address is not in the map. The application is freeing
-- an already freed memory or something wrong.
-- Post (Client.Event_Channel, Ev);
declare
Old_Slot : constant Allocation := MAT.Memory.Allocation_Maps.Element (It);
begin
-- Remove the memory slot from our map.
Client.Data.Memory_Slots.Delete (It);
Frames.Release (Old_Slot.Frame);
end;
end if;
Client.Data.Memory_Slots.Insert (Addr, Slot);
end Process_Realloc_Message;
----------------------
-- Unmarshall from the message the memory slot information.
-- The data is described by the Defs table.
----------------------
procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message;
Slot : in out Allocation;
Addr : in out MAT.Types.Target_Addr;
Old_Addr : in out MAT.Types.Target_Addr;
Defs : in MAT.Events.Attribute_Table) is
begin
for I in Defs'Range loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_SIZE =>
Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind);
when M_ADDR =>
Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when M_OLD_ADDR =>
Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind);
when M_UNKNOWN =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
when others =>
MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size);
end case;
end;
end loop;
end Unmarshall_Allocation;
overriding
procedure Dispatch (For_Servant : in out Memory_Servant;
Id : in MAT.Events.Internal_Reference;
Params : in MAT.Events.Const_Attribute_Table_Access;
Frame : in MAT.Events.Frame_Info;
Msg : in out MAT.Readers.Message) is
Slot : Allocation;
Addr : MAT.Types.Target_Addr := 0;
Old_Addr : MAT.Types.Target_Addr := 0;
begin
case Id is
when MSG_MALLOC =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
Frames.Insert (Frame => For_Servant.Data.Frames,
Pc => Frame.Frame (1 .. Frame.Cur_Depth),
Result => Slot.Frame);
For_Servant.Data.Probe_Malloc (Addr, Slot);
when MSG_FREE =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
For_Servant.Data.Probe_Free (Addr, Slot);
when MSG_REALLOC =>
Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all);
Frames.Insert (Frame => For_Servant.Data.Frames,
Pc => Frame.Frame (1 .. Frame.Cur_Depth),
Result => Slot.Frame);
For_Servant.Data.Probe_Realloc (Addr, Old_Addr, Slot);
when others =>
raise Program_Error;
end case;
end Dispatch;
end MAT.Memory.Readers;
|
Use the new Probe_Malloc, Probe_Realloc and Probe_Free operations
|
Use the new Probe_Malloc, Probe_Realloc and Probe_Free operations
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
b52b901f847bfa02e37cd1db6492f5f3e3e925dc
|
hal/src/hal-i2c.ads
|
hal/src/hal-i2c.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of 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. --
-- --
------------------------------------------------------------------------------
package HAL.I2C is
type I2C_Status is
(Ok,
Err_Error,
Err_Timeout,
Busy);
type I2C_Data is array (Natural range <>) of Byte;
type I2C_Memory_Address_Size is
(Memory_Size_8b,
Memory_Size_16b);
subtype I2C_Address is UInt10;
type I2C_Port is limited interface;
type I2C_Port_Ref is access all I2C_Port'Class;
procedure Master_Transmit
(This : in out I2C_Port;
Addr : I2C_Address;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000) is abstract;
procedure Master_Receive
(This : in out I2C_Port;
Addr : I2C_Address;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000) is abstract;
procedure Mem_Write
(This : in out I2C_Port;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000) is abstract;
procedure Mem_Read
(This : in out I2C_Port;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000) is abstract;
end HAL.I2C;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
package HAL.I2C is
type I2C_Status is
(Ok,
Err_Error,
Err_Timeout,
Busy);
subtype I2C_Data is Byte_Array;
type I2C_Memory_Address_Size is
(Memory_Size_8b,
Memory_Size_16b);
subtype I2C_Address is UInt10;
type I2C_Port is limited interface;
type I2C_Port_Ref is access all I2C_Port'Class;
procedure Master_Transmit
(This : in out I2C_Port;
Addr : I2C_Address;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000) is abstract;
procedure Master_Receive
(This : in out I2C_Port;
Addr : I2C_Address;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000) is abstract;
procedure Mem_Write
(This : in out I2C_Port;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000) is abstract;
procedure Mem_Read
(This : in out I2C_Port;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000) is abstract;
end HAL.I2C;
|
Use standard Byte_Array as HAL.I2C data.
|
Use standard Byte_Array as HAL.I2C data.
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library
|
467139dce140c5ba02e542f250595c11f5f559e5
|
mat/src/events/mat-events-probes.ads
|
mat/src/events/mat-events-probes.ads
|
-----------------------------------------------------------------------
-- mat-events-probes -- Event probes
-- 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 MAT.Types;
with MAT.Events;
with MAT.Events.Targets;
with MAT.Readers;
with MAT.Frames;
package MAT.Events.Probes is
subtype Probe_Event_Type is MAT.Events.Targets.Probe_Event_Type;
-----------------
-- Abstract probe definition
-----------------
type Probe_Type is abstract tagged limited private;
type Probe_Type_Access is access all Probe_Type'Class;
-- Extract the probe information from the message.
procedure Extract (Probe : in Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out Probe_Event_Type) is abstract;
procedure Execute (Probe : in Probe_Type;
Event : in Probe_Event_Type) is abstract;
-----------------
-- Probe Manager
-----------------
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private;
type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class;
-- Initialize the probe manager instance.
overriding
procedure Initialize (Manager : in out Probe_Manager_Type);
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Read a list of event definitions from the stream and configure the reader.
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Get the target events.
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access;
-- Read a message from the stream.
procedure Read_Message (Reader : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is abstract;
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;
Manager : in out Probe_Manager_Type'Class) is abstract;
private
type Probe_Type is abstract tagged limited record
Owner : Probe_Manager_Type_Access := null;
end record;
-- Record a probe
type Probe_Handler is record
Probe : Probe_Type_Access;
Id : MAT.Events.Targets.Probe_Index_Type;
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 Probe_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Probe_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 => Probe_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record
Probes : Probe_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;
Event : Probe_Event_Type;
Frames : MAT.Frames.Frame_Type;
end record;
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message);
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-events-probes -- Event probes
-- 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 MAT.Types;
with MAT.Events;
with MAT.Events.Targets;
with MAT.Readers;
with MAT.Frames;
package MAT.Events.Probes is
subtype Probe_Event_Type is MAT.Events.Targets.Probe_Event_Type;
-----------------
-- Abstract probe definition
-----------------
type Probe_Type is abstract tagged limited private;
type Probe_Type_Access is access all Probe_Type'Class;
-- Extract the probe information from the message.
procedure Extract (Probe : in Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out Probe_Event_Type) is abstract;
procedure Execute (Probe : in Probe_Type;
Event : in Probe_Event_Type) is abstract;
-----------------
-- Probe Manager
-----------------
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private;
type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class;
-- Initialize the probe manager instance.
overriding
procedure Initialize (Manager : in out Probe_Manager_Type);
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access);
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Read a list of event definitions from the stream and configure the reader.
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
-- Get the target events.
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access;
-- Read a message from the stream.
procedure Read_Message (Reader : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is abstract;
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;
Manager : in out Probe_Manager_Type'Class) is abstract;
private
type Probe_Type is abstract tagged limited record
Owner : Probe_Manager_Type_Access := null;
end record;
-- Record a probe
type Probe_Handler is record
Probe : Probe_Type_Access;
Id : MAT.Events.Targets.Probe_Index_Type;
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;
package Probe_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Probe_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 => Probe_Handler,
Hash => Hash,
Equivalent_Keys => "=");
type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record
Probes : Probe_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;
Event : Probe_Event_Type;
Frames : MAT.Frames.Frame_Type;
end record;
-- Read an event definition from the stream and configure the reader.
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message);
end MAT.Events.Probes;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f83e2820e9310d9ce6013f560a0e97a63025ef74
|
src/base/beans/util-beans-objects-vectors.adb
|
src/base/beans/util-beans-objects-vectors.adb
|
-----------------------------------------------------------------------
-- util-beans-vectors -- Object vectors
-- Copyright (C) 2011, 2017, 2019, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Vectors is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Vector_Bean;
Name : in String) return Object is
begin
if Name = "count" then
return To_Object (Natural (From.Length));
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Vector_Bean) return Natural is
begin
return Natural (From.Length);
end Get_Count;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
overriding
function Get_Row (From : in Vector_Bean;
Position : in Natural) return Util.Beans.Objects.Object is
begin
return From.Element (Position);
end Get_Row;
-- -----------------------
-- Create an object that contains a <tt>Vector_Bean</tt> instance.
-- -----------------------
function Create return Object is
M : constant Vector_Bean_Access := new Vector_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
-- -----------------------
-- Iterate over the vectors or array elements.
-- If the object is not a `Vector_Bean` or an array, the operation does nothing.
-- -----------------------
procedure Iterate (From : in Object;
Process : not null access procedure (Item : in Object)) is
procedure Process_One (Pos : in Vectors.Cursor);
procedure Process_One (Pos : in Vectors.Cursor) is
begin
Process (Vectors.Element (Pos));
end Process_One;
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From);
begin
if Bean /= null and then Bean.all in Vector_Bean'Class then
Vector_Bean'Class (Bean.all).Iterate (Process_One'Access);
elsif Is_Array (From) then
declare
Count : constant Natural := Get_Count (From);
begin
for Pos in 1 .. Count loop
Process (Get_Value (From, Pos));
end loop;
end;
end if;
end Iterate;
end Util.Beans.Objects.Vectors;
|
-----------------------------------------------------------------------
-- util-beans-vectors -- Object vectors
-- Copyright (C) 2011, 2017, 2019, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Vectors is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Vector_Bean;
Name : in String) return Object is
begin
if Name = "count" then
return To_Object (Natural (From.Length));
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Vector_Bean) return Natural is
begin
return Natural (From.Length);
end Get_Count;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
overriding
function Get_Row (From : in Vector_Bean;
Position : in Natural) return Util.Beans.Objects.Object is
begin
return From.Element (Position);
end Get_Row;
-- -----------------------
-- Create an object that contains a <tt>Vector_Bean</tt> instance.
-- -----------------------
function Create return Object is
M : constant Vector_Bean_Access := new Vector_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
-- -----------------------
-- Iterate over the vectors or array elements.
-- If the object is not a `Vector_Bean` or an array, the operation does nothing.
-- -----------------------
procedure Iterate (From : in Object;
Process : not null access procedure (Position : in Positive;
Item : in Object)) is
procedure Process_One (Pos : in Vectors.Cursor);
procedure Process_One (Pos : in Vectors.Cursor) is
begin
Process (Vectors.To_Index (Pos), Vectors.Element (Pos));
end Process_One;
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From);
begin
if Bean /= null and then Bean.all in Vector_Bean'Class then
Vector_Bean'Class (Bean.all).Iterate (Process_One'Access);
elsif Is_Array (From) then
declare
Count : constant Natural := Get_Count (From);
begin
for Pos in 1 .. Count loop
Process (Pos, Get_Value (From, Pos));
end loop;
end;
end if;
end Iterate;
-- -----------------------
-- Get an iterator to iterate starting with the first element.
-- -----------------------
overriding
function First (From : in Vector_Bean) return Iterators.Proxy_Iterator_Access is
Iter : constant Vector_Iterator_Access := new Vector_Iterator;
begin
Iter.Pos := From.First;
return Iter.all'Access;
end First;
-- -----------------------
-- Get an iterator to iterate starting with the last element.
-- -----------------------
overriding
function Last (From : in Vector_Bean) return Iterators.Proxy_Iterator_Access is
Iter : constant Vector_Iterator_Access := new Vector_Iterator;
begin
Iter.Pos := From.Last;
return Iter.all'Access;
end Last;
overriding
function Has_Element (Iter : in Vector_Iterator) return Boolean is
begin
return Vectors.Has_Element (Iter.Pos);
end Has_Element;
overriding
procedure Next (Iter : in out Vector_Iterator) is
begin
Vectors.Next (Iter.Pos);
end Next;
overriding
procedure Previous (Iter : in out Vector_Iterator) is
begin
Vectors.Previous (Iter.Pos);
end Previous;
overriding
function Element (Iter : in Vector_Iterator) return Object is
begin
return Vectors.Element (Iter.Pos);
end Element;
end Util.Beans.Objects.Vectors;
|
Implement the operations for the Vector_Iterator type
|
Implement the operations for the Vector_Iterator type
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b28dc91377bd7698501bf1922e19143f6693a834
|
regtests/asf-requests-tests.adb
|
regtests/asf-requests-tests.adb
|
-----------------------------------------------------------------------
-- asf-requests-tests - Unit tests for requests
-- 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 Util.Test_Caller;
with Util.Log.Loggers;
with ASF.Requests.Mockup;
package body ASF.Requests.Tests is
use Util.Tests;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Requests.Tests");
package Caller is new Util.Test_Caller (Test, "Requests");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Requests.Split_Header",
Test_Split_Header'Access);
Caller.Add_Test (Suite, "Test ASF.Requests.Accept_Locales",
Test_Accept_Locales'Access);
end Add_Tests;
-- ------------------------------
-- Test the Split_Header procedure.
-- ------------------------------
procedure Test_Split_Header (T : in out Test) is
procedure Process_Text (Item : in String;
Quality : in Quality_Type);
Count : Natural := 0;
procedure Process_Text (Item : in String;
Quality : in Quality_Type) is
begin
T.Assert (Item = "text/plain" or Item = "text/html" or Item = "text/x-dvi"
or Item = "text/x-c", "Invalid item: " & Item);
T.Assert (Quality = 0.5 or Quality = 0.8 or Quality = 1.0,
"Invalid quality");
if Item = "text/plain" then
T.Assert (Quality = 0.5, "Invalid quality for " & Item);
elsif Item = "text/x-dvi" or Item = "text/html" then
T.Assert (Quality = 0.8, "Invalid quality for " & Item);
else
T.Assert (Quality = 1.0, "Invalid quality for " & Item);
end if;
Count := Count + 1;
end Process_Text;
begin
Split_Header ("text/plain; q=0.5, text/html,text/x-dvi; q=0.8, text/x-c",
Process_Text'Access);
Util.Tests.Assert_Equals (T, 4, Count, "Invalid number of items");
end Test_Split_Header;
-- ------------------------------
-- Test the Accept_Locales procedure.
-- ------------------------------
procedure Test_Accept_Locales (T : in out Test) is
procedure Process_Locale (Locale : in Util.Locales.Locale;
Quality : in Quality_Type);
use Util.Locales;
Req : ASF.Requests.Mockup.Request;
Count : Natural := 0;
procedure Process_Locale (Locale : in Util.Locales.Locale;
Quality : in Quality_Type) is
pragma Unreferenced (Quality);
Lang : constant String := Util.Locales.Get_Language (Locale);
begin
Log.Info ("Found locale: {0}", Util.Locales.To_String (Locale));
T.Assert (Lang = "da" or Lang = "en_GB" or Lang = "en",
"Invalid lang: " & Lang);
Count := Count + 1;
end Process_Locale;
begin
Req.Set_Header ("Accept-Language", "da, en-gb;q=0.8, en;q=0.7");
Req.Accept_Locales (Process_Locale'Access);
Util.Tests.Assert_Equals (T, 3, Count, "Invalid number of calls");
end Test_Accept_Locales;
end ASF.Requests.Tests;
|
-----------------------------------------------------------------------
-- asf-requests-tests - Unit tests for requests
-- 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 Util.Test_Caller;
with Util.Log.Loggers;
with ASF.Requests.Mockup;
package body ASF.Requests.Tests is
use Util.Tests;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Requests.Tests");
package Caller is new Util.Test_Caller (Test, "Requests");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Requests.Split_Header",
Test_Split_Header'Access);
Caller.Add_Test (Suite, "Test ASF.Requests.Accept_Locales",
Test_Accept_Locales'Access);
Caller.Add_Test (Suite, "Test ASF.Requests.Set_Attribute",
Test_Set_Attribute'Access);
end Add_Tests;
-- ------------------------------
-- Test the Split_Header procedure.
-- ------------------------------
procedure Test_Split_Header (T : in out Test) is
procedure Process_Text (Item : in String;
Quality : in Quality_Type);
Count : Natural := 0;
procedure Process_Text (Item : in String;
Quality : in Quality_Type) is
begin
T.Assert (Item = "text/plain" or Item = "text/html" or Item = "text/x-dvi"
or Item = "text/x-c", "Invalid item: " & Item);
T.Assert (Quality = 0.5 or Quality = 0.8 or Quality = 1.0,
"Invalid quality");
if Item = "text/plain" then
T.Assert (Quality = 0.5, "Invalid quality for " & Item);
elsif Item = "text/x-dvi" or Item = "text/html" then
T.Assert (Quality = 0.8, "Invalid quality for " & Item);
else
T.Assert (Quality = 1.0, "Invalid quality for " & Item);
end if;
Count := Count + 1;
end Process_Text;
begin
Split_Header ("text/plain; q=0.5, text/html,text/x-dvi; q=0.8, text/x-c",
Process_Text'Access);
Util.Tests.Assert_Equals (T, 4, Count, "Invalid number of items");
end Test_Split_Header;
-- ------------------------------
-- Test the Accept_Locales procedure.
-- ------------------------------
procedure Test_Accept_Locales (T : in out Test) is
procedure Process_Locale (Locale : in Util.Locales.Locale;
Quality : in Quality_Type);
use Util.Locales;
Req : ASF.Requests.Mockup.Request;
Count : Natural := 0;
procedure Process_Locale (Locale : in Util.Locales.Locale;
Quality : in Quality_Type) is
pragma Unreferenced (Quality);
Lang : constant String := Util.Locales.Get_Language (Locale);
begin
Log.Info ("Found locale: {0}", Util.Locales.To_String (Locale));
T.Assert (Lang = "da" or Lang = "en_GB" or Lang = "en",
"Invalid lang: " & Lang);
Count := Count + 1;
end Process_Locale;
begin
Req.Accept_Locales (Process_Locale'Access);
Util.Tests.Assert_Equals (T, 1, Count, "Invalid number of calls");
Count := 0;
Req.Set_Header ("Accept-Language", "da, en-gb;q=0.8, en;q=0.7");
Req.Accept_Locales (Process_Locale'Access);
Util.Tests.Assert_Equals (T, 3, Count, "Invalid number of calls");
end Test_Accept_Locales;
-- ------------------------------
-- Test the Set_Attribute procedure.
-- ------------------------------
procedure Test_Set_Attribute (T : in out Test) is
use Util.Beans.Objects;
Req : ASF.Requests.Mockup.Request;
begin
Req.Set_Attribute ("page", Util.Beans.Objects.To_Object (Integer (1)));
Util.Tests.Assert_Equals (T, 1, Util.Beans.Objects.To_Integer (Req.Get_Attribute ("page")),
"Invalid page attribute");
Req.Remove_Attribute ("page");
T.Assert (Util.Beans.Objects.Is_Null (Req.Get_Attribute ("page")),
"Attribute page is not null");
Req.Set_Attribute ("page", Util.Beans.Objects.To_Object (Integer (1)));
Req.Set_Attribute ("page", Util.Beans.Objects.Null_Object);
T.Assert (Util.Beans.Objects.Is_Null (Req.Get_Attribute ("page")),
"Attribute page is not null");
end Test_Set_Attribute;
end ASF.Requests.Tests;
|
Add a new test to verify the Set/Get/Remove attribute on a request
|
Add a new test to verify the Set/Get/Remove attribute on a request
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
e24e7399e3b4d8710b46a3cf7a9baf62e568e7ef
|
src/security-policies-roles.adb
|
src/security-policies-roles.adb
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based 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 Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Strings.Tokenizers;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Data := new Role_Policy_Context;
Data.Roles := Roles;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
Map : Role_Map;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Role_Policy'Class (Policy.all).Set_Roles (Roles, Map);
Data := new Role_Policy_Context;
Data.Roles := Map;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- ------------------------------
-- 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;
-- ------------------------------
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
-- ------------------------------
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map) is
procedure Process (Role : in String;
Done : out Boolean);
procedure Process (Role : in String;
Done : out Boolean) is
begin
Into (Manager.Find_Role (Role)) := True;
Done := False;
end Process;
begin
Into := (others => False);
Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles,
Pattern => ",",
Process => Process'Access,
Going => Ada.Strings.Forward);
end Set_Roles;
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.
-- ------------------------------
procedure Prepare_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 Prepare_Config;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Policy : in out Role_Policy) is
use type Ada.Strings.Unbounded.String_Access;
begin
for I in Policy.Names'Range loop
exit when Policy.Names (I) = null;
Ada.Strings.Unbounded.Free (Policy.Names (I));
end loop;
end Finalize;
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-policies-roles -- Role based 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 Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Strings.Tokenizers;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Data := new Role_Policy_Context;
Data.Roles := Roles;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
Map : Role_Map;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Role_Policy'Class (Policy.all).Set_Roles (Roles, Map);
Data := new Role_Policy_Context;
Data.Roles := Map;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- ------------------------------
-- 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;
-- ------------------------------
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
-- ------------------------------
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map) is
procedure Process (Role : in String;
Done : out Boolean);
procedure Process (Role : in String;
Done : out Boolean) is
begin
Into (Manager.Find_Role (Role)) := True;
Done := False;
end Process;
begin
Into := (others => False);
Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles,
Pattern => ",",
Process => Process'Access,
Going => Ada.Strings.Forward);
end Set_Roles;
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.
-- ------------------------------
procedure Prepare_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 Prepare_Config;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Policy : in out Role_Policy) is
use type Ada.Strings.Unbounded.String_Access;
begin
for I in Policy.Names'Range loop
exit when Policy.Names (I) = null;
Ada.Strings.Unbounded.Free (Policy.Names (I));
end loop;
end Finalize;
-- ------------------------------
-- Get the role policy associated with the given policy manager.
-- Returns the role policy instance or null if it was not registered in the policy manager.
-- ------------------------------
function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return Role_Policy_Access is
Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME);
begin
if Policy = null or else not (Policy.all in Role_Policy'Class) then
return null;
else
return Role_Policy'Class (Policy.all)'Access;
end if;
end Get_Role_Policy;
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;
|
Implement the new function Get_Role_Policy
|
Implement the new function Get_Role_Policy
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
43b14d88d056317616f283a0017a7db0a4c161c7
|
src/util-encoders.ads
|
src/util-encoders.ads
|
-----------------------------------------------------------------------
-- util-encoders -- Encode/Decode streams and strings from one format to another
-- Copyright (C) 2009, 2010, 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Interfaces;
-- The <b>Util.Encoders</b> package defines the <b>Encoder</b> object
-- which represents a mechanism to transform a stream from one format into
-- another format.
package Util.Encoders is
pragma Preelaborate;
Not_Supported : exception;
Encoding_Error : exception;
-- Encoder/decoder for Base64 (RFC 4648)
BASE_64 : constant String := "base64";
-- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet
-- (+ and / are replaced by - and _)
BASE_64_URL : constant String := "base64url";
-- Encoder/decoder for Base16 (RFC 4648)
BASE_16 : constant String := "base16";
HEX : constant String := "hex";
-- Encoder for SHA1 (RFC 3174)
HASH_SHA1 : constant String := "sha1";
-- ------------------------------
-- Encoder context object
-- ------------------------------
-- The <b>Encoder</b> provides operations to encode and decode
-- strings or stream of data from one format to another.
-- The <b>Encoded</b> contains two <b>Transformer</b>
-- which either <i>encodes</i> or <i>decodes</i> the stream.
type Encoder is tagged limited private;
-- Encodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be encoded.
-- Raises the <b>Not_Supported</b> exception if the encoding is not
-- supported.
function Encode (E : in Encoder;
Data : in String) return String;
-- Decodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be decoded.
-- Raises the <b>Not_Supported</b> exception if the decoding is not
-- supported.
function Decode (E : in Encoder;
Data : in String) return String;
-- Create the encoder object for the specified encoding format.
function Create (Name : String) return Encoder;
-- ------------------------------
-- Stream Transformation interface
-- ------------------------------
-- The <b>Transformer</b> interface defines the operation to transform
-- a stream from one data format to another.
type Transformer is limited interface;
type Transformer_Access is access all Transformer'Class;
-- Transform the input stream represented by <b>Data</b> into
-- the output stream <b>Into</b>. The transformation made by
-- the object can be of any nature (Hex encoding, Base64 encoding,
-- Hex decoding, Base64 decoding, ...).
--
-- 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.
procedure Transform (E : in Transformer;
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 abstract;
procedure Transform (E : in Transformer;
Data : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String) is null;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in Transformer'Class;
Data : in String) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer and return the data in
-- the <b>Into</b> array, setting <b>Last</b> to the last index.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
procedure Transform (E : in Transformer'Class;
Data : in String;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting
-- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits
-- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated
-- to indicate the position of the last valid byte written in <tt>Into</tt>.
procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : in Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
-- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting
-- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated
-- to indicate the last position in the byte array.
procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : out Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
private
type Encoder is new Ada.Finalization.Limited_Controlled with record
Encode : Transformer_Access := null;
Decode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Encoder);
end Util.Encoders;
|
-----------------------------------------------------------------------
-- util-encoders -- Encode/Decode streams and strings from one format to another
-- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Interfaces;
-- The <b>Util.Encoders</b> package defines the <b>Encoder</b> object
-- which represents a mechanism to transform a stream from one format into
-- another format.
package Util.Encoders is
pragma Preelaborate;
Not_Supported : exception;
Encoding_Error : exception;
-- Encoder/decoder for Base64 (RFC 4648)
BASE_64 : constant String := "base64";
-- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet
-- (+ and / are replaced by - and _)
BASE_64_URL : constant String := "base64url";
-- Encoder/decoder for Base16 (RFC 4648)
BASE_16 : constant String := "base16";
HEX : constant String := "hex";
-- Encoder for SHA1 (RFC 3174)
HASH_SHA1 : constant String := "sha1";
-- ------------------------------
-- Encoder context object
-- ------------------------------
-- The <b>Encoder</b> provides operations to encode and decode
-- strings or stream of data from one format to another.
-- The <b>Encoded</b> contains two <b>Transformer</b>
-- which either <i>encodes</i> or <i>decodes</i> the stream.
type Encoder is tagged limited private;
-- Encodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be encoded.
-- Raises the <b>Not_Supported</b> exception if the encoding is not
-- supported.
function Encode (E : in Encoder;
Data : in String) return String;
-- Decodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be decoded.
-- Raises the <b>Not_Supported</b> exception if the decoding is not
-- supported.
function Decode (E : in Encoder;
Data : in String) return String;
-- Create the encoder object for the specified encoding format.
function Create (Name : String) return Encoder;
-- ------------------------------
-- Stream Transformation interface
-- ------------------------------
-- The <b>Transformer</b> interface defines the operation to transform
-- a stream from one data format to another.
type Transformer is limited interface;
type Transformer_Access is access all Transformer'Class;
-- Transform the input stream represented by <b>Data</b> into
-- the output stream <b>Into</b>. The transformation made by
-- the object can be of any nature (Hex encoding, Base64 encoding,
-- Hex decoding, Base64 decoding, ...).
--
-- 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.
procedure Transform (E : in out Transformer;
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 abstract;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in String) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer and return the data in
-- the <b>Into</b> array, setting <b>Last</b> to the last index.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
procedure Transform (E : in out Transformer'Class;
Data : in String;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting
-- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits
-- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated
-- to indicate the position of the last valid byte written in <tt>Into</tt>.
procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : in Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
-- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting
-- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated
-- to indicate the last position in the byte array.
procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : out Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
private
type Encoder is new Ada.Finalization.Limited_Controlled with record
Encode : Transformer_Access := null;
Decode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Encoder);
end Util.Encoders;
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
17f2df6dce3b220d0d0656f55a55f4da11cdac77
|
regtests/security-openid-tests.adb
|
regtests/security-openid-tests.adb
|
-----------------------------------------------------------------------
-- security-openid - Tests for OpenID
-- 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.Unbounded;
with Util.Http.Clients.Mockups;
with Util.Http.Clients.Files;
with Util.Test_Caller;
with Ada.Text_IO;
package body Security.Openid.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Openid");
procedure Check_Discovery (T : in out Test;
Name : in String;
URI : in String);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OpenID.Discover",
Test_Discovery'Access);
Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature",
Test_Verify_Signature'Access);
end Add_Tests;
procedure Check_Discovery (T : in out Test;
Name : in String;
URI : in String) is
pragma Unreferenced (URI, T);
M : Manager;
Dir : constant String := "regtests/files/discover/";
Path : constant String := Util.Tests.Get_Path (Dir);
Result : End_Point;
begin
ASF.Clients.Files.Register;
ASF.Clients.Files.Set_File (Path & Name & ".xrds");
M.Discover (Name => Name,
Result => Result);
Ada.Text_IO.Put_Line ("Result: " & To_String (Result));
end Check_Discovery;
-- ------------------------------
-- Test Yadis discovery using static files
-- ------------------------------
procedure Test_Discovery (T : in out Test) is
begin
Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud");
Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth");
Check_Discovery (T, "claimid", "");
Check_Discovery (T, "livejournal", "");
Check_Discovery (T, "myopenid", "");
Check_Discovery (T, "myspace", "");
Check_Discovery (T, "orange", "");
Check_Discovery (T, "verisign", "");
Check_Discovery (T, "steamcommunity", "");
end Test_Discovery;
-- ------------------------------
-- Test the OpenID verify signature process
-- ------------------------------
procedure Test_Verify_Signature (T : in out Test) is
Assoc : Association;
Req : ASF.Requests.Mockup.Request;
M : Manager;
Result : Authentication;
begin
M.Return_To := To_Unbounded_String ("http://localhost/openId");
-- Below is a part of the authentication process on Google OpenId.
-- In theory, you cannot use the following information to authenticate again...
Assoc.Session_Type := To_Unbounded_String ("no-encryption");
Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1");
Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk");
Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI=");
Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0");
Req.Set_Parameter ("openid.mode", "id_res");
Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud");
Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw");
Req.Set_Parameter ("openid.return_to", "http://localhost/openId");
Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk");
Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname");
Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE=");
Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E");
Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E");
Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0");
Req.Set_Parameter ("openid.ext1.mode", "fetch_response");
Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first");
Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane");
Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email");
Req.Set_Parameter ("openid.ext1.value.email", "[email protected]");
Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language");
Req.Set_Parameter ("openid.ext1.value.language", "fr");
Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last");
Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez");
M.Verify (Assoc, Req, Result);
-- If the verification is succeeds, the signature is correct, we should be authenticated.
T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated");
Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email");
end Test_Verify_Signature;
end Security.Openid.Tests;
|
-----------------------------------------------------------------------
-- security-openid - Tests for OpenID
-- 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.Unbounded;
with Util.Http.Mockups;
with Util.Http.Clients.Mockups;
with Util.Test_Caller;
with Ada.Text_IO;
package body Security.Openid.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Openid");
procedure Check_Discovery (T : in out Test;
Name : in String;
URI : in String);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OpenID.Discover",
Test_Discovery'Access);
Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature",
Test_Verify_Signature'Access);
end Add_Tests;
procedure Check_Discovery (T : in out Test;
Name : in String;
URI : in String) is
pragma Unreferenced (URI, T);
M : Manager;
Dir : constant String := "regtests/files/discover/";
Path : constant String := Util.Tests.Get_Path (Dir);
Result : End_Point;
begin
Util.Http.Clients.Mockups.Register;
Util.Http.Clients.Mockups.Set_File (Path & Name & ".xrds");
M.Discover (Name => Name,
Result => Result);
Ada.Text_IO.Put_Line ("Result: " & To_String (Result));
end Check_Discovery;
-- ------------------------------
-- Test Yadis discovery using static files
-- ------------------------------
procedure Test_Discovery (T : in out Test) is
begin
Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud");
Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth");
Check_Discovery (T, "claimid", "");
Check_Discovery (T, "livejournal", "");
Check_Discovery (T, "myopenid", "");
Check_Discovery (T, "myspace", "");
Check_Discovery (T, "orange", "");
Check_Discovery (T, "verisign", "");
Check_Discovery (T, "steamcommunity", "");
end Test_Discovery;
-- ------------------------------
-- Test the OpenID verify signature process
-- ------------------------------
procedure Test_Verify_Signature (T : in out Test) is
Assoc : Association;
Req : Util.Http.Mockups.Mockup_Request;
M : Manager;
Result : Authentication;
begin
M.Return_To := To_Unbounded_String ("http://localhost/openId");
-- Below is a part of the authentication process on Google OpenId.
-- In theory, you cannot use the following information to authenticate again...
Assoc.Session_Type := To_Unbounded_String ("no-encryption");
Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1");
Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk");
Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI=");
Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0");
Req.Set_Parameter ("openid.mode", "id_res");
Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud");
Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw");
Req.Set_Parameter ("openid.return_to", "http://localhost/openId");
Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk");
Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname");
Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE=");
Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E");
Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E");
Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0");
Req.Set_Parameter ("openid.ext1.mode", "fetch_response");
Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first");
Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane");
Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email");
Req.Set_Parameter ("openid.ext1.value.email", "[email protected]");
Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language");
Req.Set_Parameter ("openid.ext1.value.language", "fr");
Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last");
Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez");
M.Verify (Assoc, Req, Result);
-- If the verification is succeeds, the signature is correct, we should be authenticated.
T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated");
Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email");
end Test_Verify_Signature;
end Security.Openid.Tests;
|
Use the new util HTTP mockups
|
Use the new util HTTP mockups
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
8b980aa35fcecd3f52a163f66e9fbdf41ee4f16a
|
src/util-beans-objects-readers.adb
|
src/util-beans-objects-readers.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-readers -- Datasets
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO;
package body Util.Beans.Objects.Readers is
use type Maps.Map_Bean_Access;
use type Vectors.Vector_Bean_Access;
-- Start a document.
overriding
procedure Start_Document (Handler : in out Reader) is
begin
Object_Stack.Clear (Handler.Context);
Object_Stack.Push (Handler.Context);
Object_Stack.Current (Handler.Context).Map := new Maps.Map_Bean;
end Start_Document;
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.Map := new Maps.Map_Bean;
if Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.List, DYNAMIC));
else
Current.List.Append (To_Object (Next.List, DYNAMIC));
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
begin
Object_Stack.Pop (Handler.Context);
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.List := new Vectors.Vector_Bean;
if Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.List, DYNAMIC));
else
Current.List.Append (To_Object (Next.List, DYNAMIC));
end if;
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) is
begin
Object_Stack.Pop (Handler.Context);
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
begin
if Current.Map /= null then
Current.Map.Set_Value (Name, Value);
else
Current.List.Append (Value);
end if;
end Set_Member;
end Util.Beans.Objects.Readers;
|
-----------------------------------------------------------------------
-- util-beans-objects-readers -- Datasets
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Readers is
use type Maps.Map_Bean_Access;
use type Vectors.Vector_Bean_Access;
-- Start a document.
overriding
procedure Start_Document (Handler : in out Reader) is
begin
Object_Stack.Clear (Handler.Context);
Object_Stack.Push (Handler.Context);
Object_Stack.Current (Handler.Context).Map := new Maps.Map_Bean;
end Start_Document;
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.Map := new Maps.Map_Bean;
if Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.List, DYNAMIC));
else
Current.List.Append (To_Object (Next.List, DYNAMIC));
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.List := new Vectors.Vector_Bean;
if Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.List, DYNAMIC));
else
Current.List.Append (To_Object (Next.List, DYNAMIC));
end if;
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Count, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is
pragma Unreferenced (Logger, Attribute);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
begin
if Current.Map /= null then
Current.Map.Set_Value (Name, Value);
else
Current.List.Append (Value);
end if;
end Set_Member;
end Util.Beans.Objects.Readers;
|
Fix compilation warning unused Logger parameter
|
Fix compilation warning unused Logger parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
bde3e22cd4e16df5d55201822e84a1299454f47d
|
src/ado-drivers-connections.ads
|
src/ado-drivers-connections.ads
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Statements;
with ADO.Schemas;
with Util.Properties;
with Util.Strings;
with Util.Refs;
-- The <b>ADO.Drivers</b> package represents the database driver that will create
-- database connections and provide the database specific implementation.
package ADO.Drivers.Connections is
use ADO.Statements;
type Driver is abstract tagged limited private;
type Driver_Access is access all Driver'Class;
-- ------------------------------
-- Database connection implementation
-- ------------------------------
--
type Database_Connection is abstract new Util.Refs.Ref_Entity with record
Ident : String (1 .. 8) := (others => ' ');
end record;
type Database_Connection_Access is access all Database_Connection'Class;
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is abstract;
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is abstract;
-- Create a delete statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is abstract;
-- Create an insert statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is abstract;
-- Create an update statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is abstract;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Database_Connection) is abstract;
-- Commit the current transaction.
procedure Commit (Database : in out Database_Connection) is abstract;
-- Rollback the current transaction.
procedure Rollback (Database : in out Database_Connection) is abstract;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is abstract;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Database_Connection)
return Driver_Access is abstract;
-- Closes the database connection
procedure Close (Database : in out Database_Connection) is abstract;
package Ref is
new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class,
Element_Access => Database_Connection_Access);
-- ------------------------------
-- The database configuration properties
-- ------------------------------
type Configuration is new Ada.Finalization.Controlled with private;
type Configuration_Access is access all Configuration'Class;
-- 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);
-- 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);
-- Get a property from the data source configuration.
-- If the property does not exist, an empty string is returned.
function Get_Property (Controller : in Configuration;
Name : in String) return String;
-- Set the server hostname.
procedure Set_Server (Controller : in out Configuration;
Server : in String);
-- Get the server hostname.
function Get_Server (Controller : in Configuration) return String;
-- Set the server port.
procedure Set_Port (Controller : in out Configuration;
Port : in Natural);
-- Get the server port.
function Get_Port (Controller : in Configuration) return Natural;
-- Set the database name.
procedure Set_Database (Controller : in out Configuration;
Database : in String);
-- Get the database name.
function Get_Database (Controller : in Configuration) return String;
-- Get the database driver name.
function Get_Driver (Controller : in Configuration) return String;
-- Create a new connection using the configuration parameters.
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class);
-- ------------------------------
-- Database Driver
-- ------------------------------
-- Create a new connection using the configuration parameters.
procedure Create_Connection (D : in out Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is abstract;
-- Get the driver unique index.
function Get_Driver_Index (D : in Driver) return Driver_Index;
-- Get the driver name.
function Get_Driver_Name (D : in Driver) return String;
-- Register a database driver.
procedure Register (Driver : in Driver_Access);
-- Get a database driver given its name.
function Get_Driver (Name : in String) return Driver_Access;
private
type Driver is abstract new Ada.Finalization.Limited_Controlled with record
Name : Util.Strings.Name_Access;
Index : Driver_Index;
end record;
type Configuration is new Ada.Finalization.Controlled with record
URI : Unbounded_String := Null_Unbounded_String;
Server : Unbounded_String := Null_Unbounded_String;
Port : Natural := 0;
Database : Unbounded_String := Null_Unbounded_String;
Properties : Util.Properties.Manager;
Driver : Driver_Access;
end record;
end ADO.Drivers.Connections;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Statements;
with ADO.Schemas;
with Util.Properties;
with Util.Strings;
with Util.Refs;
-- The <b>ADO.Drivers</b> package represents the database driver that will create
-- database connections and provide the database specific implementation.
package ADO.Drivers.Connections is
use ADO.Statements;
type Driver is abstract tagged limited private;
type Driver_Access is access all Driver'Class;
-- ------------------------------
-- Database connection implementation
-- ------------------------------
--
type Database_Connection is abstract new Util.Refs.Ref_Entity with record
Ident : String (1 .. 8) := (others => ' ');
end record;
type Database_Connection_Access is access all Database_Connection'Class;
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is abstract;
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is abstract;
-- Create a delete statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is abstract;
-- Create an insert statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is abstract;
-- Create an update statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is abstract;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Database_Connection) is abstract;
-- Commit the current transaction.
procedure Commit (Database : in out Database_Connection) is abstract;
-- Rollback the current transaction.
procedure Rollback (Database : in out Database_Connection) is abstract;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is abstract;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Database_Connection)
return Driver_Access is abstract;
-- Closes the database connection
procedure Close (Database : in out Database_Connection) is abstract;
package Ref is
new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class,
Element_Access => Database_Connection_Access);
-- ------------------------------
-- The database configuration properties
-- ------------------------------
type Configuration is new Ada.Finalization.Controlled with private;
type Configuration_Access is access all Configuration'Class;
-- 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);
-- 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);
-- Get a property from the data source configuration.
-- If the property does not exist, an empty string is returned.
function Get_Property (Controller : in Configuration;
Name : in String) return String;
-- Set the server hostname.
procedure Set_Server (Controller : in out Configuration;
Server : in String);
-- Get the server hostname.
function Get_Server (Controller : in Configuration) return String;
-- Set the server port.
procedure Set_Port (Controller : in out Configuration;
Port : in Natural);
-- Get the server port.
function Get_Port (Controller : in Configuration) return Natural;
-- Set the database name.
procedure Set_Database (Controller : in out Configuration;
Database : in String);
-- Get the database name.
function Get_Database (Controller : in Configuration) return String;
-- Get the database driver name.
function Get_Driver (Controller : in Configuration) return String;
-- Create a new connection using the configuration parameters.
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class);
-- ------------------------------
-- Database Driver
-- ------------------------------
-- Create a new connection using the configuration parameters.
procedure Create_Connection (D : in out Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is abstract;
-- Get the driver unique index.
function Get_Driver_Index (D : in Driver) return Driver_Index;
-- Get the driver name.
function Get_Driver_Name (D : in Driver) return String;
-- Register a database driver.
procedure Register (Driver : in Driver_Access);
-- Get a database driver given its name.
function Get_Driver (Name : in String) return Driver_Access;
private
type Driver is abstract new Ada.Finalization.Limited_Controlled with record
Name : Util.Strings.Name_Access;
Index : Driver_Index;
end record;
type Configuration is new Ada.Finalization.Controlled with record
URI : Unbounded_String;
Log_URI : Unbounded_String;
Server : Unbounded_String;
Port : Natural := 0;
Database : Unbounded_String;
Properties : Util.Properties.Manager;
Driver : Driver_Access;
end record;
end ADO.Drivers.Connections;
|
Add a Log_URI member to the Configuration
|
Add a Log_URI member to the Configuration
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
f4daa515394f05e5b38a93a0489a3a1c0464a381
|
awt/example/src/package_test.adb
|
awt/example/src/package_test.adb
|
with GL.Types;
with Orka.Logging;
with Orka.Resources.Locations.Directories;
with Orka.Rendering.Programs.Modules;
with Orka.Rendering.Drawing;
with Orka.Windows;
with AWT.Drag_And_Drop;
package body Package_Test is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
protected body Dnd_Signal is
procedure Set is
begin
Dropped := True;
end Set;
entry Wait when Dropped is
begin
Dropped := False;
end Wait;
end Dnd_Signal;
overriding
function On_Close (Object : Test_Window) return Boolean is
begin
Messages.Log (Debug, "User is trying to close window");
return True;
end On_Close;
overriding
procedure On_Drag
(Object : in out Test_Window;
X, Y : AWT.Inputs.Fixed)
is
use all type AWT.Inputs.Action_Kind;
use type AWT.Inputs.Fixed;
begin
Messages.Log (Debug, "User dragged something to " &
"(" & Trim (X'Image) & ", " & Trim (Y'Image) & ")");
AWT.Drag_And_Drop.Set_Action (if X < 300.0 and Y < 300.0 then Copy else None);
end On_Drag;
overriding
procedure On_Drop
(Object : in out Test_Window)
is
use all type AWT.Inputs.Action_Kind;
Action : constant AWT.Inputs.Action_Kind := AWT.Drag_And_Drop.Valid_Action;
begin
Messages.Log (Info, "User dropped something. Action is " & Action'Image);
if Action /= None then
Dnd_Signal.Set;
end if;
end On_Drop;
overriding
procedure On_Configure
(Object : in out Test_Window;
State : Standard.AWT.Windows.Window_State) is
begin
Messages.Log (Debug, "Configured window surface");
Messages.Log (Debug, " size: " &
Trim (State.Width'Image) & " × " & Trim (State.Height'Image));
Messages.Log (Debug, " margin: " & Trim (State.Margin'Image));
Object.Resize := State.Visible and State.Width > 0 and State.Height > 0;
end On_Configure;
procedure Initialize_Framebuffer (Object : in out Test_Window) is
Alpha : constant Orka.Float_32 := (if Object.State.Transparent then 0.5 else 1.0);
begin
Object.FB :=
Orka.Rendering.Framebuffers.Create_Default_Framebuffer (Object.Width, Object.Height);
Object.FB.Set_Default_Values ((Color => (0.0, 0.0, 0.0, Alpha), others => <>));
Object.FB.Use_Framebuffer;
Messages.Log (Debug, "Changed size of framebuffer to " &
Trim (Object.Width'Image) & " × " & Trim (Object.Height'Image));
end Initialize_Framebuffer;
procedure Post_Initialize (Object : in out Test_Window) is
Location_Shaders : constant Orka.Resources.Locations.Location_Ptr :=
Orka.Resources.Locations.Directories.Create_Location ("data");
begin
Object.Initialize_Framebuffer;
Object.Program := Orka.Rendering.Programs.Create_Program
(Orka.Rendering.Programs.Modules.Create_Module
(Location_Shaders,
VS => "cursor.vert",
FS => "cursor.frag"));
Object.Program.Use_Program;
Object.Cursor := Object.Program.Uniform ("cursor");
end Post_Initialize;
procedure Render (Object : in out Test_Window) is
use type Orka.Float_32;
use Standard.AWT.Inputs;
Window_State : constant Standard.AWT.Windows.Window_State := Object.State;
Pointer_State : constant Standard.AWT.Inputs.Pointer_State := Object.State;
subtype Float_32 is Orka.Float_32;
Width : constant Float_32 := Float_32 (Window_State.Width + 2 * Window_State.Margin);
Height : constant Float_32 := Float_32 (Window_State.Height + 2 * Window_State.Margin);
PX : constant Float_32 := Float_32 (Pointer_State.Position (X));
PY : constant Float_32 := Float_32 (Pointer_State.Position (Y));
Horizontal : constant Float_32 := PX / Width * 2.0 - 1.0;
Vertical : constant Float_32 := PY / Height * 2.0 - 1.0;
begin
if Object.Resize then
Object.Resize := False;
Object.Initialize_Framebuffer;
end if;
Object.FB.Clear ((Color => True, others => False));
Object.Cursor.Set_Vector (Orka.Float_32_Array'(Horizontal, -Vertical));
Orka.Rendering.Drawing.Draw (GL.Types.Points, 0, 1);
Object.Swap_Buffers;
end Render;
overriding
function Create_Window
(Context : aliased Orka.Contexts.Surface_Context'Class;
Width, Height : Positive;
Title : String := "";
Samples : Natural := 0;
Visible, Resizable : Boolean := True;
Transparent : Boolean := False) return Test_Window is
begin
return Result : constant Test_Window :=
(Orka.Contexts.AWT.Create_Window
(Context, Width, Height, Title, Samples,
Visible => Visible,
Resizable => Resizable,
Transparent => Transparent) with others => <>);
end Create_Window;
end Package_Test;
|
with GL.Types;
with Orka.Logging;
with Orka.Resources.Locations.Directories;
with Orka.Rendering.Programs.Modules;
with Orka.Rendering.Drawing;
with Orka.Windows;
with AWT.Drag_And_Drop;
package body Package_Test is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
protected body Dnd_Signal is
procedure Set is
begin
Dropped := True;
end Set;
entry Wait when Dropped is
begin
Dropped := False;
end Wait;
end Dnd_Signal;
overriding
function On_Close (Object : Test_Window) return Boolean is
begin
Messages.Log (Debug, "User is trying to close window");
return True;
end On_Close;
overriding
procedure On_Drag
(Object : in out Test_Window;
X, Y : AWT.Inputs.Fixed)
is
use all type AWT.Inputs.Action_Kind;
use type AWT.Inputs.Fixed;
begin
Messages.Log (Debug, "User dragged something to " &
"(" & Trim (X'Image) & ", " & Trim (Y'Image) & ")");
AWT.Drag_And_Drop.Set_Action (if X < 300.0 and Y < 300.0 then Copy else None);
end On_Drag;
overriding
procedure On_Drop
(Object : in out Test_Window)
is
use all type AWT.Inputs.Action_Kind;
Action : constant AWT.Inputs.Action_Kind := AWT.Drag_And_Drop.Valid_Action;
begin
Messages.Log (Info, "User dropped something. Action is " & Action'Image);
if Action /= None then
Dnd_Signal.Set;
end if;
end On_Drop;
overriding
procedure On_Configure
(Object : in out Test_Window;
State : Standard.AWT.Windows.Window_State) is
begin
Messages.Log (Debug, "Configured window surface");
Messages.Log (Debug, " size: " &
Trim (State.Width'Image) & " × " & Trim (State.Height'Image));
Messages.Log (Debug, " margin: " & Trim (State.Margin'Image));
Object.Resize := State.Visible and State.Width > 0 and State.Height > 0;
end On_Configure;
procedure Initialize_Framebuffer (Object : in out Test_Window) is
Alpha : constant Orka.Float_32 := (if Object.State.Transparent then 0.5 else 1.0);
begin
Object.FB :=
Orka.Rendering.Framebuffers.Create_Default_Framebuffer (Object.Width, Object.Height);
Object.FB.Set_Default_Values ((Color => (0.0, 0.0, 0.0, Alpha), others => <>));
Object.FB.Use_Framebuffer;
Messages.Log (Debug, "Changed size of framebuffer to " &
Trim (Object.Width'Image) & " × " & Trim (Object.Height'Image));
end Initialize_Framebuffer;
procedure Post_Initialize (Object : in out Test_Window) is
Location_Shaders : constant Orka.Resources.Locations.Location_Ptr :=
Orka.Resources.Locations.Directories.Create_Location ("data");
begin
Object.Initialize_Framebuffer;
Object.Program := Orka.Rendering.Programs.Create_Program
(Orka.Rendering.Programs.Modules.Create_Module
(Location_Shaders,
VS => "cursor.vert",
FS => "cursor.frag"));
Object.Program.Use_Program;
Object.Cursor := Object.Program.Uniform ("cursor");
end Post_Initialize;
procedure Render (Object : in out Test_Window) is
use type Orka.Float_32;
use Standard.AWT.Inputs;
Window_State : constant Standard.AWT.Windows.Window_State := Object.State;
Pointer_State : constant Standard.AWT.Inputs.Pointer_State := Object.State;
subtype Float_32 is Orka.Float_32;
Width : constant Float_32 := Float_32 (Window_State.Width + 2 * Window_State.Margin);
Height : constant Float_32 := Float_32 (Window_State.Height + 2 * Window_State.Margin);
PX : constant Float_32 := Float_32 (Pointer_State.Position (X));
PY : constant Float_32 := Float_32 (Pointer_State.Position (Y));
Horizontal : constant Float_32 := PX / Width * 2.0 - 1.0;
Vertical : constant Float_32 := PY / Height * 2.0 - 1.0;
begin
if Object.Resize then
Object.Resize := False;
Object.Initialize_Framebuffer;
end if;
Object.FB.Clear ((Color => True, others => False));
Object.Cursor.Set_Vector (Orka.Float_32_Array'(Horizontal, Vertical));
Orka.Rendering.Drawing.Draw (GL.Types.Points, 0, 1);
Object.Swap_Buffers;
end Render;
overriding
function Create_Window
(Context : aliased Orka.Contexts.Surface_Context'Class;
Width, Height : Positive;
Title : String := "";
Samples : Natural := 0;
Visible, Resizable : Boolean := True;
Transparent : Boolean := False) return Test_Window is
begin
return Result : constant Test_Window :=
(Orka.Contexts.AWT.Create_Window
(Context, Width, Height, Title, Samples,
Visible => Visible,
Resizable => Resizable,
Transparent => Transparent) with others => <>);
end Create_Window;
end Package_Test;
|
Fix rendering of green cursor dot after changing origin of window
|
awt: Fix rendering of green cursor dot after changing origin of window
The origin of window coordinates was changed to upper-left corner in
commit b4078f1 to be consistent with most rendering APIs and windowing
systems.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
47890306125c1940c88c0da420adac7d442b7f47
|
awa/plugins/awa-tags/src/awa-tags.ads
|
awa/plugins/awa-tags/src/awa-tags.ads
|
-----------------------------------------------------------------------
-- awa-tags -- Tags management
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Tags</b> module allows to associate general purpose tags to any database entity.
-- It provides a JSF component that allows to insert easily a list of tags in a page and
-- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt>
-- to define the tags and it will use the <tt>awa:tagList</tt> component to display them.
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png]
--
-- @include awa-tags-modules.ads
-- @include awa-tags-beans.ads
-- @include awa-tags-components.ads
--
package AWA.Tags is
pragma Pure;
end AWA.Tags;
|
-----------------------------------------------------------------------
-- awa-tags -- Tags management
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Tags</b> module allows to associate general purpose tags to any database entity.
-- It provides a JSF component that allows to insert easily a list of tags in a page and
-- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt>
-- to define the tags and it will use the <tt>awa:tagList</tt> component to display them.
-- A tag cloud is also provided by the <tt>awa:tagCloud</tt> component.
--
-- == Model ==
-- The database model is generic and it uses the <tt>Entity_Type</tt> provided by
-- [http://ada-ado.googlecode.com ADO] to associate a tag to entities stored in different
-- tables. The <tt>Entity_Type</tt> identifies the database table and the stored identifier
-- in <tt>for_entity_id</tt> defines the entity in that table.
--
-- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png]
--
-- @include awa-tags-modules.ads
-- @include awa-tags-beans.ads
-- @include awa-tags-components.ads
--
package AWA.Tags is
pragma Pure;
end AWA.Tags;
|
Document the tag model
|
Document the tag model
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
cf9e0bacdd66d846feea3c642f48dca8c4126e6c
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
end Babel.Files;
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
-- ------------------------------
procedure Set_Size (Element : in File_Type;
Size : in File_Size) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
end Babel.Files;
|
Implement the Set_Size procedure and set the FILE_MODIFIED flag if the new size is different
|
Implement the Set_Size procedure and set the FILE_MODIFIED flag if the new size is different
|
Ada
|
apache-2.0
|
stcarrez/babel
|
599e538b888ba7c7880596a730f9e5c30260b4b6
|
src/util-properties.ads
|
src/util-properties.ads
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
function Get (Self : in Manager'Class;
Name : in String) return Manager;
-- Create a property manager and associated it with the given name.
function Create (Self : in out Manager'Class;
Name : in String) return Manager;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
-- Get the property manager represented by the item value.
-- Raise the Conversion_Error exception if the value is not a property manager.
function To_Manager (Item : in Value) return Manager;
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
Shared : Boolean := False;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
function Get (Self : in Manager'Class;
Name : in String) return Manager;
-- Create a property manager and associated it with the given name.
function Create (Self : in out Manager'Class;
Name : in String) return Manager;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
-- Get the property manager represented by the item value.
-- Raise the Conversion_Error exception if the value is not a property manager.
function To_Manager (Item : in Value) return Manager;
-- Returns True if the item value represents a property manager.
function Is_Manager (Item : in Value) return Boolean;
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
Shared : Boolean := False;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
Declare the Is_Manager function
|
Declare the Is_Manager function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.